repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/api/gamepad
data/mdn-content/files/en-us/web/api/gamepad/vibrationactuator/index.md
--- title: "Gamepad: vibrationActuator property" short-title: vibrationActuator slug: Web/API/Gamepad/vibrationActuator page-type: web-api-instance-property status: - non-standard browser-compat: api.Gamepad.vibrationActuator --- {{APIRef("Gamepad")}}{{Non-standard_Header}}{{SecureContext_Header}} The **`vibrationActuator`** read-only property of the {{domxref("Gamepad")}} interface returns a {{domxref("GamepadHapticActuator")}} object, which represents haptic feedback hardware available on the controller. ## Value A {{domxref("GamepadHapticActuator")}} object. ## Examples ```js const gamepad = navigator.getGamepads()[0]; gamepad.vibrationActuator.playEffect("dual-rumble", { startDelay: 0, duration: 200, weakMagnitude: 1.0, strongMagnitude: 1.0, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
0
data/mdn-content/files/en-us/web/api/gamepad
data/mdn-content/files/en-us/web/api/gamepad/mapping/index.md
--- title: "Gamepad: mapping property" short-title: mapping slug: Web/API/Gamepad/mapping page-type: web-api-instance-property browser-compat: api.Gamepad.mapping --- {{APIRef("Gamepad API")}}{{SecureContext_Header}} The **`Gamepad.mapping`** property of the {{domxref("Gamepad")}} interface returns a string indicating whether the browser has remapped the controls on the device to a known layout. The currently supported known layouts are: - "standard" for the [standard gamepad](https://w3c.github.io/gamepad/#remapping). - "xr-standard for the [standard XR gamepad](https://immersive-web.github.io/webxr-gamepads-module/#xr-standard-heading). See also {{domxref("XRInputSource.gamepad")}}. ## Examples ```js let gp = navigator.getGamepads()[0]; console.log(gp.mapping); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
0
data/mdn-content/files/en-us/web/api/gamepad
data/mdn-content/files/en-us/web/api/gamepad/timestamp/index.md
--- title: "Gamepad: timestamp property" short-title: timestamp slug: Web/API/Gamepad/timestamp page-type: web-api-instance-property browser-compat: api.Gamepad.timestamp --- {{APIRef("Gamepad API")}}{{SecureContext_Header}} The **`Gamepad.timestamp`** property of the {{domxref("Gamepad")}} interface returns a {{domxref("DOMHighResTimeStamp")}} representing the last time the data for this gamepad was updated. The idea behind this is to allow developers to determine if the `axes` and `button` data have been updated from the hardware. The value must be relative to the `navigationStart` attribute of the {{domxref("PerformanceTiming")}} interface. Values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as newer values will always be greater than or equal to older values. > **Note:** This property is not currently supported anywhere. ## Value A {{domxref("DOMHighResTimeStamp")}} object. ## Examples ```js const gp = navigator.getGamepads()[0]; console.log(gp.timestamp); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
0
data/mdn-content/files/en-us/web/api/gamepad
data/mdn-content/files/en-us/web/api/gamepad/index/index.md
--- title: "Gamepad: index property" short-title: index slug: Web/API/Gamepad/index page-type: web-api-instance-property browser-compat: api.Gamepad.index --- {{APIRef("Gamepad API")}}{{SecureContext_Header}} The **`Gamepad.index`** property of the {{domxref("Gamepad") }} interface returns an integer that is auto-incremented to be unique for each device currently connected to the system. This can be used to distinguish multiple controllers; a gamepad that is disconnected and reconnected will retain the same index. ## Value A {{jsxref("number") }}. ## Examples ```js window.addEventListener("gamepadconnected", () => { const gp = navigator.getGamepads()[0]; gamepadInfo.textContent = `Gamepad connected at index ${gp.index}: ${gp.id}.`; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
0
data/mdn-content/files/en-us/web/api/gamepad
data/mdn-content/files/en-us/web/api/gamepad/connected/index.md
--- title: "Gamepad: connected property" short-title: connected slug: Web/API/Gamepad/connected page-type: web-api-instance-property browser-compat: api.Gamepad.connected --- {{APIRef("Gamepad API")}}{{SecureContext_Header}} The **`Gamepad.connected`** property of the {{domxref("Gamepad") }} interface returns a boolean indicating whether the gamepad is still connected to the system. If the gamepad is connected, the value is `true`; if not, it is `false`. ## Value A boolean. ## Examples ```js const gp = navigator.getGamepads()[0]; console.log(gp.connected); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/web_periodic_background_synchronization_api/index.md
--- title: Web Periodic Background Synchronization API slug: Web/API/Web_Periodic_Background_Synchronization_API page-type: web-api-overview status: - experimental browser-compat: - api.PeriodicSyncManager - api.ServiceWorkerGlobalScope.periodicsync_event spec-urls: https://wicg.github.io/periodic-background-sync/ --- {{DefaultAPISidebar("Periodic Background Sync")}}{{SecureContext_Header}}{{SeeCompatTable}} The **Web Periodic Background Synchronization API** provides a way to register tasks to be run in a {{domxref("Service Worker API", "service worker", "", "nocode")}} at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests. ## Concepts and Usage The Periodic Background Sync API allows web applications to alert their service worker to make any updates, at a periodic time interval. Uses may include fetching latest content whilst a device is connected to Wi-Fi, or allowing background updates to an application. The minimum time interval is set when the API is invoked; however the user agent might also take into account other factors which affect when the service worker receives the event. For instance previous website engagement, or connection to a known network. The {{domxref('PeriodicSyncManager')}} interface is available through {{domxref('ServiceWorkerRegistration.periodicSync')}}. A unique tag identifier is set to 'name' the sync event, which can then be listened for within the {{domxref('ServiceWorker')}} script. Once the event is received you can then run any functionality available, such as updating caches or fetching new resources. As this API relies on service workers, functionality provided by this API is only available in a secure context. ## Interfaces - {{domxref("PeriodicSyncManager")}} {{Experimental_Inline}} - : Registers tasks to be run in a service worker at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests. - {{domxref("PeriodicSyncEvent")}} {{Experimental_Inline}} - : Represents a synchronization event, sent to the {{domxref("ServiceWorkerGlobalScope", "global scope", "", "nocode")}} of a {{domxref("Service Worker API", "ServiceWorker", "", "nocode")}}. It provides a way to run tasks in the service worker with network connectivity. ### Extensions to other interfaces The following additions to the {{domxref("Service Worker API", "", "", "nocode")}} are specified in the Periodic Background Sync specification to provide an entry point for using Periodic Background Sync. - {{domxref("ServiceWorkerRegistration.periodicSync")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to the {{domxref("PeriodicSyncManager")}} interface for registering tasks to run at specific intervals. - {{domxref("ServiceWorkerGlobalScope/periodicsync_event", "periodicsync")}} event {{Experimental_Inline}} - : Occurs at periodic intervals, which were specified when registering a {{domxref("PeriodicSyncManager")}}. ## Examples The following examples show how to use the interface. ### Requesting a Periodic Background Sync The following asynchronous function registers a periodic background sync at a minimum interval of one day from a browsing context: ```js async function registerPeriodicNewsCheck() { const registration = await navigator.serviceWorker.ready; try { await registration.periodicSync.register("get-latest-news", { minInterval: 24 * 60 * 60 * 1000, }); } catch { console.log("Periodic Sync could not be registered!"); } } ``` ### Verifying a Background Periodic Sync by Tag This code checks to see if a Periodic Background Sync task with a given tag is registered. ```js navigator.serviceWorker.ready.then((registration) => { registration.periodicSync.getTags().then((tags) => { if (tags.includes("get-latest-news")) skipDownloadingLatestNewsOnPageLoad(); }); }); ``` ### Removing a Periodic Background Sync Task The following code removes a Periodic Background Sync task to stop articles syncing in the background. ```js navigator.serviceWorker.ready.then((registration) => { registration.periodicSync.unregister("get-latest-news"); }); ``` ### Listening for a Periodic Background Sync within a Service Worker The following example shows how to respond to a periodic sync event in the service worker. ```js self.addEventListener("periodicsync", (event) => { if (event.tag === "get-latest-news") { event.waitUntil(fetchAndCacheLatestNews()); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [An article on using Periodic Background Sync](https://developer.chrome.com/docs/capabilities/periodic-background-sync) - [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/audioworkletglobalscope/index.md
--- title: AudioWorkletGlobalScope slug: Web/API/AudioWorkletGlobalScope page-type: web-api-interface browser-compat: api.AudioWorkletGlobalScope --- {{APIRef("Web Audio API")}} The **`AudioWorkletGlobalScope`** interface of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) represents a global execution context for user-supplied code, which defines custom {{domxref("AudioWorkletProcessor")}}-derived classes. Each {{domxref("BaseAudioContext")}} has a single {{domxref("AudioWorklet")}} available under the {{domxref("BaseAudioContext.audioWorklet", "audioWorklet")}} property, which runs its code in a single `AudioWorkletGlobalScope`. As the global execution context is shared across the current `BaseAudioContext`, it's possible to define any other variables and perform any actions allowed in worklets β€” apart from defining `AudioWorkletProcessor` derived classes. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties defined on its parent interface, {{domxref("WorkletGlobalScope")}}._ - {{domxref("AudioWorkletGlobalScope.currentFrame", "currentFrame")}} {{ReadOnlyInline}} - : Returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. It is incremented by 128 (the size of a render quantum) after the processing of each audio block. - {{domxref("AudioWorkletGlobalScope.currentTime", "currentTime")}} {{ReadOnlyInline}} - : Returns a double that represents the ever-increasing context time of the audio block being processed. It is equal to the {{domxref("BaseAudioContext.currentTime", "currentTime")}} property of the {{domxref("BaseAudioContext")}} the worklet belongs to. - {{domxref("AudioWorkletGlobalScope.sampleRate", "sampleRate")}} {{ReadOnlyInline}} - : Returns a float that represents the sample rate of the associated {{domxref("BaseAudioContext")}}. ## Instance methods _This interface also inherits methods defined on its parent interface, {{domxref("WorkletGlobalScope")}}._ - {{domxref("AudioWorkletGlobalScope.registerProcessor", "registerProcessor()")}} - : Registers a class derived from the {{domxref('AudioWorkletProcessor')}} interface. The class can then be used by creating an {{domxref("AudioWorkletNode")}}, providing its registered name. ## Examples In this example we output all global properties into the console in the constructor of a custom {{domxref("AudioWorkletProcessor")}}. First we need to define the processor, and register it. Note that this should be done in a separate file. ```js // AudioWorkletProcessor defined in : test-processor.js class TestProcessor extends AudioWorkletProcessor { constructor() { super(); // Logs the current sample-frame and time at the moment of instantiation. // They are accessible from the AudioWorkletGlobalScope. console.log(currentFrame); console.log(currentTime); } // The process method is required - output silence, // which the outputs are already filled with. process(inputs, outputs, parameters) { return true; } } // Logs the sample rate, that is not going to change ever, // because it's a read-only property of a BaseAudioContext // and is set only during its instantiation. console.log(sampleRate); // You can declare any variables and use them in your processors // for example it may be an ArrayBuffer with a wavetable const usefulVariable = 42; console.log(usefulVariable); registerProcessor("test-processor", TestProcessor); ``` Next, in our main scripts file we'll load the processor, create an instance of {{domxref("AudioWorkletNode")}} β€” passing the name of the processor to it β€” and connect the node to an audio graph. We should see the output of {{domxref("console/log_static", "console.log()")}} calls in the console: ```js const audioContext = new AudioContext(); await audioContext.audioWorklet.addModule("test-processor.js"); const testNode = new AudioWorkletNode(audioContext, "test-processor"); testNode.connect(audioContext.destination); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API) - [Using AudioWorklet](/en-US/docs/Web/API/Web_Audio_API/Using_AudioWorklet)
0
data/mdn-content/files/en-us/web/api/audioworkletglobalscope
data/mdn-content/files/en-us/web/api/audioworkletglobalscope/currenttime/index.md
--- title: "AudioWorkletGlobalScope: currentTime property" short-title: currentTime slug: Web/API/AudioWorkletGlobalScope/currentTime page-type: web-api-instance-property browser-compat: api.AudioWorkletGlobalScope.currentTime --- {{APIRef("Web Audio API")}} The read-only **`currentTime`** property of the {{domxref("AudioWorkletGlobalScope")}} interface returns a double that represents the ever-increasing context time of the audio block being processed. It is equal to the {{domxref("BaseAudioContext.currentTime", "currentTime")}} property of the {{domxref("BaseAudioContext")}} the worklet belongs to. ## Value A floating-point number representing the time. ## Examples The {{domxref("AudioWorkletProcessor")}} has access to the specific {{domxref("AudioWorkletGlobalScope")}} properties: ```js // AudioWorkletProcessor defined in : test-processor.js class TestProcessor extends AudioWorkletProcessor { constructor() { super(); // Logs the current sample-frame and time at the moment of instantiation. // They are accessible from the AudioWorkletGlobalScope. console.log(currentFrame); console.log(currentTime); } // The process method is required - output silence, // which the outputs are already filled with. process(inputs, outputs, parameters) { return true; } } // Logs the sample rate, that is not going to change ever, // because it's a read-only property of a BaseAudioContext // and is set only during its instantiation. console.log(sampleRate); // You can declare any variables and use them in your processors // for example it may be an ArrayBuffer with a wavetable. const usefulVariable = 42; console.log(usefulVariable); registerProcessor("test-processor", TestProcessor); ``` The main script loads the processor, creates an instance of {{domxref("AudioWorkletNode")}}, passes the name of the processor to it, and connects the node to an audio graph. We should see the output of {{domxref("console/log_static", "console.log()")}} calls in the console: ```js const audioContext = new AudioContext(); await audioContext.audioWorklet.addModule("test-processor.js"); const testNode = new AudioWorkletNode(audioContext, "test-processor"); testNode.connect(audioContext.destination); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/audioworkletglobalscope
data/mdn-content/files/en-us/web/api/audioworkletglobalscope/registerprocessor/index.md
--- title: "AudioWorkletGlobalScope: registerProcessor() method" short-title: registerProcessor() slug: Web/API/AudioWorkletGlobalScope/registerProcessor page-type: web-api-instance-method browser-compat: api.AudioWorkletGlobalScope.registerProcessor --- {{ APIRef("Web Audio API") }} The **`registerProcessor`** method of the {{domxref("AudioWorkletGlobalScope")}} interface registers a class constructor derived from {{domxref("AudioWorkletProcessor")}} interface under a specified _name_. ## Syntax ```js-nolint registerProcessor(name, processorCtor) ``` ### Parameters - `name` - : A string representing the name under which the processor will be registered. - `processorCtor` - : The constructor of a class derived from {{domxref("AudioWorkletProcessor")}}. > **Note:** A key-value pair `{ name: constructor }` > is saved internally in the {{domxref("AudioWorkletGlobalScope")}} once the processor > is registered. The _name_ is to be referred to when creating an > {{domxref("AudioWorkletNode")}} based on the registered processor. A new processor by > the given name is internally created and associated with the new node. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown under the following conditions: - The _name_ is an empty string. - A constructor under the given _name_ is already registered. Registering the same name twice is not allowed. - {{jsxref("TypeError")}} - : Thrown under the following conditions: - The _processorCtor_ is not a callable constructor. - The {{domxref("AudioWorkletProcessor.parameterDescriptors", "parameterDescriptors")}} property of the constructor exists and doesn't return an array of {{domxref("AudioParamDescriptor")}}-based objects. ## Examples In this example we create a custom `AudioWorkletNode` that outputs silence. First, we need to define a custom {{domxref("AudioWorkletProcessor")}} and register it. Note that this should be done in a separate file. ```js // test-processor.js class TestProcessor extends AudioWorkletProcessor { process(inputs, outputs, parameters) { return true; } } registerProcessor("test-processor", TestProcessor); ``` Next, in our main script file we'll load the processor, create an instance of `AudioWorkletNode` β€” passing it the processor name that we used when calling `registerProcessor` β€” and connect it to an audio graph. ```js const audioContext = new AudioContext(); await audioContext.audioWorklet.addModule("test-processor.js"); const node = new AudioWorkletNode(audioContext, "test-processor"); node.connect(audioContext.destination); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/audioworkletglobalscope
data/mdn-content/files/en-us/web/api/audioworkletglobalscope/currentframe/index.md
--- title: "AudioWorkletGlobalScope: currentFrame property" short-title: currentFrame slug: Web/API/AudioWorkletGlobalScope/currentFrame page-type: web-api-instance-property browser-compat: api.AudioWorkletGlobalScope.currentFrame --- {{APIRef("Web Audio API")}} The read-only **`currentFrame`** property of the {{domxref("AudioWorkletGlobalScope")}} interface returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. It is incremented by 128 (the size of a render quantum) after the processing of each audio block. ## Value An integer number. ## Examples The {{domxref("AudioWorkletProcessor")}} has access to the specific {{domxref("AudioWorkletGlobalScope")}} properties: ```js // AudioWorkletProcessor defined in : test-processor.js class TestProcessor extends AudioWorkletProcessor { constructor() { super(); // Logs the current sample-frame and time at the moment of instantiation. // They are accessible from the AudioWorkletGlobalScope. console.log(currentFrame); console.log(currentTime); } // The process method is required - output silence, // which the outputs are already filled with. process(inputs, outputs, parameters) { return true; } } // Logs the sample rate, that is not going to change ever, // because it's a read-only property of a BaseAudioContext // and is set only during its instantiation. console.log(sampleRate); // You can declare any variables and use them in your processors // for example it may be an ArrayBuffer with a wavetable. const usefulVariable = 42; console.log(usefulVariable); registerProcessor("test-processor", TestProcessor); ``` The main script loads the processor, creates an instance of {{domxref("AudioWorkletNode")}}, passes the name of the processor to it, and connects the node to an audio graph. We should see the output of {{domxref("console/log_static", "console.log()")}} calls in the console: ```js const audioContext = new AudioContext(); await audioContext.audioWorklet.addModule("test-processor.js"); const testNode = new AudioWorkletNode(audioContext, "test-processor"); testNode.connect(audioContext.destination); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/audioworkletglobalscope
data/mdn-content/files/en-us/web/api/audioworkletglobalscope/samplerate/index.md
--- title: "AudioWorkletGlobalScope: sampleRate property" short-title: sampleRate slug: Web/API/AudioWorkletGlobalScope/sampleRate page-type: web-api-instance-property browser-compat: api.AudioWorkletGlobalScope.sampleRate --- {{APIRef("Web Audio API")}} The read-only **`sampleRate`** property of the {{domxref("AudioWorkletGlobalScope")}} interface returns a float that represents the sample rate of the associated {{domxref("BaseAudioContext")}} the worklet belongs to. ## Value A floating-point number representing the associated sample rate. ## Examples The {{domxref("AudioWorkletProcessor")}} has access to the specific {{domxref("AudioWorkletGlobalScope")}} properties: ```js // AudioWorkletProcessor defined in : test-processor.js class TestProcessor extends AudioWorkletProcessor { constructor() { super(); // Logs the current sample-frame and time at the moment of instantiation. // They are accessible from the AudioWorkletGlobalScope. console.log(currentFrame); console.log(currentTime); } // The process method is required - output silence, // which the outputs are already filled with. process(inputs, outputs, parameters) { return true; } } // Logs the sample rate, that is not going to change ever, // because it's a read-only property of a BaseAudioContext // and is set only during its instantiation. console.log(sampleRate); // You can declare any variables and use them in your processors // for example it may be an ArrayBuffer with a wavetable. const usefulVariable = 42; console.log(usefulVariable); registerProcessor("test-processor", TestProcessor); ``` The main script loads the processor, creates an instance of {{domxref("AudioWorkletNode")}}, passes the name of the processor to it, and connects the node to an audio graph. We should see the output of {{domxref("console/log_static", "console.log()")}} calls in the console: ```js const audioContext = new AudioContext(); await audioContext.audioWorklet.addModule("test-processor.js"); const testNode = new AudioWorkletNode(audioContext, "test-processor"); testNode.connect(audioContext.destination); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/datatransfer/index.md
--- title: DataTransfer slug: Web/API/DataTransfer page-type: web-api-interface browser-compat: api.DataTransfer --- {{APIRef("HTML Drag and Drop API")}} The **`DataTransfer`** object is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see [HTML Drag and Drop API](/en-US/docs/Web/API/HTML_Drag_and_Drop_API). This object is available from the {{domxref("DragEvent.dataTransfer","dataTransfer")}} property of all {{domxref("DragEvent","drag events")}}. ## Constructor - {{domxref("DataTransfer.DataTransfer","DataTransfer()")}} - : Creates and returns a new `DataTransfer` object. ## Instance properties ### Standard properties - {{domxref("DataTransfer.dropEffect")}} - : Gets the type of drag-and-drop operation currently selected or sets the operation to a new type. The value must be `none`, `copy`, `link` or `move`. - {{domxref("DataTransfer.effectAllowed")}} - : Provides all of the types of operations that are possible. Must be one of `none`, `copy`, `copyLink`, `copyMove`, `link`, `linkMove`, `move`, `all` or `uninitialized`. - {{domxref("DataTransfer.files")}} {{ReadOnlyInline}} - : Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list. - {{domxref("DataTransfer.items")}} {{ReadOnlyInline}} - : Gives a {{domxref("DataTransferItemList")}} object which is a list of all of the drag data. - {{domxref("DataTransfer.types")}} {{ReadOnlyInline}} - : An array of strings giving the formats that were set in the {{domxref("HTMLElement/dragstart_event", "dragstart")}} event. ### Gecko properties {{SeeCompatTable}} ## Instance methods ### Standard methods - {{domxref("DataTransfer.clearData()")}} - : Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect. - {{domxref("DataTransfer.getData()")}} - : Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data. - {{domxref("DataTransfer.setData()")}} - : Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position. - {{domxref("DataTransfer.setDragImage()")}} - : Set the image to be used for dragging if a custom one is desired. ### Gecko methods {{Non-standard_Header}} ## Examples Every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/files/index.md
--- title: "DataTransfer: files property" short-title: files slug: Web/API/DataTransfer/files page-type: web-api-instance-property browser-compat: api.DataTransfer.files --- {{APIRef("HTML Drag and Drop API")}} The **`files`** read-only property of [`DataTransfer`](/en-US/docs/Web/API/DataTransfer) objects is a {{domxref("FileList","list of the files")}} in the drag operation. If the operation includes no files, the list is empty. This feature can be used to drag files from a user's desktop to the browser. > **Note:** The `files` property of [`DataTransfer`](/en-US/docs/Web/API/DataTransfer) objects can only be accessed from within the `drop` event. For all other events, the `files` property will be empty β€” because its underlying data store will be in a [protected mode](https://html.spec.whatwg.org/multipage/dnd.html#the-drag-data-store). ## Value A {{domxref("FileList","list")}} of the files in a drag operation, one list item for each file in the operation. If the drag operation had no files, the list is empty. ## Examples There are two live examples of this interface: - Firefox only: <https://jsfiddle.net/9C2EF/> - All browsers: [https://jsbin.com/hiqasek/](https://jsbin.com/hiqasek/edit?html,js,output) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/datatransfer/index.md
--- title: "DataTransfer: DataTransfer() constructor" short-title: DataTransfer() slug: Web/API/DataTransfer/DataTransfer page-type: web-api-constructor browser-compat: api.DataTransfer.DataTransfer --- {{APIRef("HTML Drag and Drop API")}} The **`DataTransfer`** constructor creates a new {{domxref("DataTransfer")}} object instance. ## Syntax ```js-nolint new DataTransfer() ``` ### Parameters None. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/cleardata/index.md
--- title: "DataTransfer: clearData() method" short-title: clearData() slug: Web/API/DataTransfer/clearData page-type: web-api-instance-method browser-compat: api.DataTransfer.clearData --- {{APIRef("HTML Drag and Drop API")}} The **`DataTransfer.clearData()`** method removes the drag operation's {{domxref("DataTransfer","drag data")}} for the given type. If data for the given type does not exist, this method does nothing. If this method is called with no arguments or the format is an empty string, the data of all types will be removed. This method does _not_ remove files from the drag operation, so it's possible for there still to be an entry with the type `"Files"` left in the object's {{domxref("DataTransfer.types")}} list if there are any files included in the drag. > **Note:** This method can only be used in the handler for the {{domxref("HTMLElement/dragstart_event", "dragstart")}} event, > because that's the only time the drag operation's data store is writable. ## Syntax ```js-nolint clearData() clearData(format) ``` ### Parameters - `format` {{optional_inline}} - : A string which specifies the type of data to remove. If this parameter is an empty string or is not provided, the data for all types is removed. ### Return value None ({{jsxref("undefined")}}). ## Examples This example shows the use of the {{domxref("DataTransfer")}} object's {{domxref("DataTransfer.getData()","getData()")}}, {{domxref("DataTransfer.setData()","setData()")}} and {{domxref("DataTransfer.clearData()","clearData()")}} methods. ### HTML ```html <span class="tweaked" id="source" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element. </span> <span class="tweaked" id="target">Drop Zone</span> <div>Status: <span id="status">Drag to start</span></div> <div>Data is: <span id="data">uninitialized</span></div> ``` ### CSS ```css span.tweaked { display: inline-block; margin: 1em 0; padding: 1em 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } ``` ### JavaScript ```js window.addEventListener("DOMContentLoaded", () => { // Select HTML elements const draggable = document.getElementById("source"); const droppable = document.getElementById("target"); const status = document.getElementById("status"); const data = document.getElementById("data"); let dropped = false; // Register event handlers draggable.addEventListener("dragstart", dragStartHandler); draggable.addEventListener("dragend", dragEndHandler); droppable.addEventListener("dragover", dragOverHandler); droppable.addEventListener("dragleave", dragLeaveHandler); droppable.addEventListener("drop", dropHandler); function dragStartHandler(event) { status.textContent = "Drag in process"; // Change target element's border to signify drag has started event.currentTarget.style.border = "1px dashed blue"; // Start by clearing existing clipboards; this will affect all types since we // don't give a specific type. event.dataTransfer.clearData(); // Set the drag's format and data (use event target's id for data) event.dataTransfer.setData("text/plain", event.target.id); data.textContent = event.dataTransfer.getData("text/plain"); } function dragEndHandler(event) { if (!dropped) { status.textContent = "Drag canceled"; } data.textContent = event.dataTransfer.getData("text/plain") || "empty"; // Change border to signify drag is no longer in process event.currentTarget.style.border = "1px solid black"; if (dropped) { // Remove all event listeners draggable.removeEventListener("dragstart", dragStartHandler); draggable.removeEventListener("dragend", dragEndHandler); droppable.removeEventListener("dragover", dragOverHandler); droppable.removeEventListener("dragleave", dragLeaveHandler); droppable.removeEventListener("drop", dropHandler); } } function dragOverHandler(event) { status.textContent = "Drop available"; event.preventDefault(); } function dragLeaveHandler(event) { status.textContent = "Drag in process (drop was available)"; event.preventDefault(); } function dropHandler(event) { dropped = true; status.textContent = "Drop done"; event.preventDefault(); // Get data linked to event format Β« text Β» const _data = event.dataTransfer.getData("text/plain"); const element = document.getElementById(_data); // Append drag source element to event's target element event.target.appendChild(element); // Change CSS styles and displayed text element.style.cssText = "border: 1px solid black;display: block; color: red"; element.textContent = "I'm in the Drop Zone!"; } }); ``` {{EmbedLiveSample('Examples', 300, 300)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/setdragimage/index.md
--- title: "DataTransfer: setDragImage() method" short-title: setDragImage() slug: Web/API/DataTransfer/setDragImage page-type: web-api-instance-method browser-compat: api.DataTransfer.setDragImage --- {{APIRef("HTML Drag and Drop API")}} When a drag occurs, a translucent image is generated from the drag target (the element the {{domxref("HTMLElement/dragstart_event", "dragstart")}} event is fired at), and follows the mouse pointer during the drag. This image is created automatically, so you do not need to create it yourself. However, if a custom image is desired, the **`DataTransfer.setDragImage()`** method can be used to set the custom image to be used. The image will typically be an {{HTMLElement("img")}} element but it can also be a {{HTMLElement("canvas")}} or any other visible element. The method's `x` and `y` coordinates define how the image should appear relative to the mouse pointer. These coordinates define the offset into the image where the mouse cursor should be. For instance, to display the image so that the pointer is at its center, use values that are half the width and height of the image. This method must be called in the {{domxref("HTMLElement/dragstart_event", "dragstart")}} event handler. ## Syntax ```js-nolint setDragImage(imgElement, xOffset, yOffset) ``` ### Parameters - `imgElement` - : An image {{domxref("Element")}} element to use for the drag feedback image. If {{domxref("Element")}} is an img element, then set the drag data store bitmap to the element's image (at its intrinsic size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified). Note: If the {{domxref("Element")}} is an existing {{domxref("HTMLElement")}} it needs to be visible in the viewport in order to be shown as a drag feedback image. Alternatively, you can create a new DOM element that might be off-screen specifically for this purpose. - `xOffset` - : A `long` indicating the horizontal offset within the image. - `yOffset` - : A `long` indicating the vertical offset within the image. ### Return value None ({{jsxref("undefined")}}). ## Examples This example shows how to use the `setDragImage()` method. Note the example refers to an image file named `example.gif`. If that file is present, it will be used as the drag image and if that file is not present, the browser will use its default drag image. [demo](https://codepen.io/webgeeker/full/KBzrxE/) ```html <!doctype html> <html lang="en"> <head> <title>Example of DataTransfer.setDragImage()</title> <meta name="viewport" content="width=device-width" /> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> <script> function dragStartHandler(ev) { console.log("dragStart"); // Set the drag's format and data. Use the event target's id for the data ev.dataTransfer.setData("text/plain", ev.target.id); // Create an image and use it for the drag image // NOTE: change "example.gif" to an existing image or the image will not // be created and the default drag image will be used. const img = new Image(); img.src = "example.gif"; ev.dataTransfer.setDragImage(img, 10, 10); } function dragOverHandler(ev) { console.log("dragOver"); ev.preventDefault(); } function dropHandler(ev) { console.log("Drop"); ev.preventDefault(); // Get the data, which is the id of the drop target const data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <h1>Example of <code>DataTransfer.setDragImage()</code></h1> <div> <p id="source" ondragstart="dragStartHandler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element. </p> </div> <div id="target" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);"> Drop Zone </div> </body> </html> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/addelement/index.md
--- title: "DataTransfer: addElement() method" short-title: addElement() slug: Web/API/DataTransfer/addElement page-type: web-api-instance-method status: - experimental - non-standard browser-compat: api.DataTransfer.addElement --- {{APIRef("HTML Drag and Drop API")}}{{SeeCompatTable}}{{Non-standard_header}} The **`DataTransfer.addElement()`** method sets the drag source to the given element. This element will be the element to which {{domxref("HTMLElement/drag_event", "drag")}} and {{domxref("HTMLElement/dragend_event", "dragend")}} events are fired, and not the default target (the node that was dragged). > **Note:** This method is Firefox-specific. ## Syntax ```js-nolint addElement(element) ``` ### Parameters - `element` - : The {{domxref("Element")}} to set as the drag source. ### Return value None ({{jsxref("undefined")}}). ## Examples This example shows the use of the `addElement()` method ```js function change_drag_node(event, node) { const dt = event.dataTransfer; dt.addElement(node); } ``` ## Specifications This method is not defined in any Web standard. ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/items/index.md
--- title: "DataTransfer: items property" short-title: items slug: Web/API/DataTransfer/items page-type: web-api-instance-property browser-compat: api.DataTransfer.items --- {{APIRef("HTML Drag and Drop API")}} The read-only {{domxref("DataTransfer")}} property `items` property is a {{domxref("DataTransferItemList","list")}} of the {{domxref("DataTransferItem","data transfer items", "", "nocode")}} in a drag operation. The list includes one item for each item in the operation and if the operation had no items, the list is empty. ## Value A {{domxref("DataTransferItemList")}} object containing {{domxref("DataTransferItem")}} objects representing the items being dragged in a drag operation, one list item for each object being dragged. If the drag operation had no data, the list is empty. ## Examples ### Logging dragged items This example uses `items` to log information about dragged items. #### HTML ```html <ul> <li id="source1" draggable="true">Drag Item 1 to the Drop Zone</li> <li id="source2" draggable="true">Drag Item 2 to the Drop Zone</li> </ul> <div id="target">Drop Zone</div> <button id="reset">Reset</button> ``` #### CSS ```css div { margin: 0em; padding: 2em; } #target { border: 1px solid black; } ``` #### JavaScript ```js function dragstartHandler(ev) { console.log(`dragstart: target.id = ${ev.target.id}`); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.dataTransfer.setData("text/plain", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function dropHandler(ev) { ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM const data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); // Print each item's "kind" and "type" if (ev.dataTransfer.items) { for (const item of ev.dataTransfer.items) { console.log(`kind = ${item.kind}, type = ${item.type}`); } } } function dragoverHandler(ev) { ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move"; } const source1 = document.querySelector("#source1"); const source2 = document.querySelector("#source2"); const target = document.querySelector("#target"); source1.addEventListener("dragstart", dragstartHandler); source2.addEventListener("dragstart", dragstartHandler); target.addEventListener("dragover", dragoverHandler); target.addEventListener("drop", dropHandler); const reset = document.querySelector("#reset"); reset.addEventListener("click", () => document.location.reload()); ``` #### Result {{EmbedLiveSample("Logging dragged items", 0, 400)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/types/index.md
--- title: "DataTransfer: types property" short-title: types slug: Web/API/DataTransfer/types page-type: web-api-instance-property browser-compat: api.DataTransfer.types --- {{APIRef("HTML Drag and Drop API")}} The **`DataTransfer.types`** read-only property returns the available types that exist in the {{domxref("DataTransfer.items","items")}}. ## Value An array of the data formats used in the drag operation. Each format is a string which is generally a MIME type such as `text/plain` or `text/html`. If the drag operation included no data, this list will be empty. If any files are included in the drag operation, then one of the types will be the string `Files`. ## Examples This example shows the use of the `types` and {{domxref("DataTransfer.items","items")}} properties. ```html <!doctype html> <html lang="en"> <title>Examples of DataTransfer.{types,items} properties</title> <meta content="width=device-width" /> <style> div { margin: 0em; padding: 2em; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragStart: target.id = " + ev.target.id); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.dataTransfer.setData("text/plain", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function drop_handler(ev) { console.log("drop: target.id = " + ev.target.id); ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM const data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); // Print each format type for (let i = 0; i < ev.dataTransfer.types.length; i++) { console.log(`… types[${i}] = ${ev.dataTransfer.types[i]}`); } // Print each item's "kind" and "type" for (let i = 0; i < ev.dataTransfer.items.length; i++) { console.log( `… items[${i}].kind = ${ev.dataTransfer.items[i].kind}; type = ${ev.dataTransfer.items[i].type}`, ); } } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move"; } </script> <body> <h1> Examples of <code>DataTransfer</code>.{<code>types</code>, <code>items</code>} properties </h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="true"> Drag Item 1 to the Drop Zone </li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="true"> Drag Item 2 to the Drop Zone </li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);"> Drop Zone </div> </body> </html> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/getdata/index.md
--- title: "DataTransfer: getData() method" short-title: getData() slug: Web/API/DataTransfer/getData page-type: web-api-instance-method browser-compat: api.DataTransfer.getData --- {{APIRef("HTML DOM")}} The **`DataTransfer.getData()`** method retrieves drag data (as a string) for the specified type. If the drag operation does not include data, this method returns an empty string. Example data types are `text/plain` and `text/uri-list`. ## Syntax ```js-nolint getData(format) ``` ### Parameters - `format` - : A string representing the type of data to retrieve. ### Return value A string representing the drag data for the specified `format`. If the drag operation has no data or the operation has no data for the specified `format`, this method returns an empty string. ### Caveats - Data availability - : The [HTML Drag and Drop Specification](https://www.w3.org/TR/2011/WD-html5-20110113/dnd.html#drag-data-store-mode) dictates a `drag data store mode`. This may result in unexpected behavior, being **`DataTransfer.getData()`** not returning an expected value, because not all browsers enforce this restriction. During the `dragstart` and `drop` events, it is safe to access the data. For all other events, the data should be considered unavailable. Despite this, the items and their formats can still be enumerated. ## Examples This example shows the use of the {{domxref("DataTransfer")}} object's {{domxref("DataTransfer.getData()","getData()")}} and {{domxref("DataTransfer.setData()","setData()")}} methods. ### HTML ```html <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> <span id="drag" draggable="true" ondragstart="drag(event)" >drag me to the other box</span > </div> <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> ``` ### CSS ```css #div1, #div2 { width: 100px; height: 50px; padding: 10px; border: 1px solid #aaaaaa; } ``` ### JavaScript ```js function allowDrop(allowdropevent) { allowdropevent.target.style.color = "blue"; allowdropevent.preventDefault(); } function drag(dragevent) { dragevent.dataTransfer.setData("text", dragevent.target.id); dragevent.target.style.color = "green"; } function drop(dropevent) { dropevent.preventDefault(); const data = dropevent.dataTransfer.getData("text"); dropevent.target.appendChild(document.getElementById(data)); document.getElementById("drag").style.color = "black"; } ``` ### Result {{EmbedLiveSample('Examples', 600) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/effectallowed/index.md
--- title: "DataTransfer: effectAllowed property" short-title: effectAllowed slug: Web/API/DataTransfer/effectAllowed page-type: web-api-instance-property browser-compat: api.DataTransfer.effectAllowed --- {{APIRef("HTML Drag and Drop API")}} The **`DataTransfer.effectAllowed`** property specifies the effect that is allowed for a drag operation. The _copy_ operation is used to indicate that the data being dragged will be copied from its present location to the drop location. The _move_ operation is used to indicate that the data being dragged will be moved, and the _link_ operation is used to indicate that some form of relationship or connection will be created between the source and drop locations. This property should be set in the {{domxref("HTMLElement/dragstart_event", "dragstart")}} event to set the desired drag effect for the drag source. Within the {{domxref("HTMLElement/dragenter_event", "dragenter")}} and {{domxref("HTMLElement/dragover_event", "dragover")}} event handlers, this property will be set to whatever value was assigned during the {{domxref("HTMLElement/dragstart_event", "dragstart")}} event, thus `effectAllowed` may be used to determine which effect is permitted. Assigning a value to `effectAllowed` in events other than {{domxref("HTMLElement/dragstart_event", "dragstart")}} has no effect. ## Value A string representing the drag operation that is allowed. The possible values are: - `none` - : The item may not be dropped. - `copy` - : A copy of the source item may be made at the new location. - `copyLink` - : A copy or link operation is permitted. - `copyMove` - : A copy or move operation is permitted. - `link` - : A link may be established to the source at the new location. - `linkMove` - : A link or move operation is permitted. - `move` - : An item may be moved to a new location. - `all` - : All operations are permitted. - `uninitialized` - : The default value when the effect has not been set, equivalent to all. Assigning any other value to `effectAllowed` has no effect and the old value is retained. ## Examples ### Setting effectAllowed In this example we set `effectAllowed` to `"move"` in the `dragstart` handler. #### HTML ```html <div> <p id="source" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element. </p> </div> <div id="target">Drop Zone</div> <pre id="output"></pre> <button id="reset">Reset</button> ``` #### CSS ```css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } #output { height: 100px; overflow: scroll; } ``` #### JavaScript ```js function dragstartHandler(ev) { log(`dragstart: effectAllowed = ${ev.dataTransfer.effectAllowed}`); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.dataTransfer.setData("text", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function dropHandler(ev) { log(`drop: effectAllowed = ${ev.dataTransfer.effectAllowed}`); ev.preventDefault(); // Get the id of the target and add the element to the target's DOM const data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragoverHandler(ev) { log(`dragover: effectAllowed = ${ev.dataTransfer.effectAllowed}`); ev.preventDefault(); } const source = document.querySelector("#source"); const target = document.querySelector("#target"); source.addEventListener("dragstart", dragstartHandler); target.addEventListener("dragover", dragoverHandler); target.addEventListener("drop", dropHandler); function log(message) { const output = document.querySelector("#output"); output.textContent = `${output.textContent}\n${message}`; output.scrollTop = output.scrollHeight; } const reset = document.querySelector("#reset"); reset.addEventListener("click", () => document.location.reload()); ``` #### Result {{EmbedLiveSample("Setting effectAllowed", 0, 400)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/setdata/index.md
--- title: "DataTransfer: setData() method" short-title: setData() slug: Web/API/DataTransfer/setData page-type: web-api-instance-method browser-compat: api.DataTransfer.setData --- {{APIRef("HTML Drag and Drop API")}} The **`DataTransfer.setData()`** method sets the drag operation's {{domxref("DataTransfer","drag data")}} to the specified data and type. If data for the given type does not exist, it is added at the end of the drag data store, such that the last item in the {{domxref("DataTransfer.types","types")}} list will be the new type. If data for the given type already exists, the existing data is replaced in the same position. That is, the order of the {{domxref("DataTransfer.types","types")}} list is not changed when replacing data of the same type. Example data types are `text/plain` and `text/uri-list`. ## Syntax ```js-nolint setData(format, data) ``` ### Parameters - `format` - : A string representing the type of the drag data to add to the {{domxref("DataTransfer","drag object")}}. - `data` - : A string representing the data to add to the {{domxref("DataTransfer","drag object")}}. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Dragging an element In this example we can drag a {{HTMLElement("p")}} element into a target {{HTMLElement("div")}} element. - In the `dragstart` handler, we use {{domxref("DataTransfer.setData","setData()")}} to add the `id` of the `<p>` element to the {{domxref("DataTransfer")}} object. - In the `drop` handler we retrieve the `id` and use it to move the `<p>` element into the target. #### HTML ```html <div> <p id="source" draggable="true"> Select this element, drag it to the drop zone and then release the selection to move the element. </p> </div> <div id="target">Drop Zone</div> <button id="reset">Reset example</button> ``` #### CSS ```css div { margin: 0.5em 0; padding: 2em; } #target, #source { border: 1px solid black; padding: 0.5rem; } .dragging { background-color: pink; } ``` #### JavaScript ```js const source = document.querySelector("#source"); source.addEventListener("dragstart", (ev) => { console.log("dragStart"); // Change the source element's background color // to show that drag has started ev.currentTarget.classList.add("dragging"); // Clear the drag data cache (for all formats/types) ev.dataTransfer.clearData(); // Set the drag's format and data. // Use the event target's id for the data ev.dataTransfer.setData("text/plain", ev.target.id); }); source.addEventListener("dragend", (ev) => ev.target.classList.remove("dragging"), ); const target = document.querySelector("#target"); target.addEventListener("dragover", (ev) => { console.log("dragOver"); ev.preventDefault(); }); target.addEventListener("drop", (ev) => { console.log("Drop"); ev.preventDefault(); // Get the data, which is the id of the source element const data = ev.dataTransfer.getData("text"); const source = document.getElementById(data); ev.target.appendChild(source); }); const reset = document.querySelector("#reset"); reset.addEventListener("click", () => document.location.reload()); ``` #### Result {{EmbedLiveSample("Dragging an element", "", 250)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api/datatransfer
data/mdn-content/files/en-us/web/api/datatransfer/dropeffect/index.md
--- title: "DataTransfer: dropEffect property" short-title: dropEffect slug: Web/API/DataTransfer/dropEffect page-type: web-api-instance-property browser-compat: api.DataTransfer.dropEffect --- {{APIRef("HTML Drag and Drop API")}} The **`DataTransfer.dropEffect`** property controls the feedback (typically visual) the user is given during a drag and drop operation. It will affect which cursor is displayed while dragging. For example, when the user hovers over a target drop element, the browser's cursor may indicate which type of operation will occur. When the {{domxref("DataTransfer")}} object is created, `dropEffect` is set to a string value. On getting, it returns its current value. On setting, if the new value is one of the values listed below, then the property's current value will be set to the new value and other values will be ignored. For the {{domxref("HTMLElement/dragenter_event", "dragenter")}} and {{domxref("HTMLElement/dragover_event", "dragover")}} events, `dropEffect` will be initialized based on what action the user is requesting. How this is determined is platform specific, but typically the user can press modifier keys such as the alt key to adjust the desired action. Within event handlers for {{domxref("HTMLElement/dragenter_event", "dragenter")}} and {{domxref("HTMLElement/dragover_event", "dragover")}} events, `dropEffect` should be modified if a different action is desired than the action that the user is requesting. For the {{domxref("HTMLElement/drop_event", "drop")}} and {{domxref("HTMLElement/dragend_event", "dragend")}} events, `dropEffect` will be set to the action that was desired, which will be the value `dropEffect` had after the last {{domxref("HTMLElement/dragenter_event", "dragenter")}} or {{domxref("HTMLElement/dragover_event", "dragover")}} event. In a {{domxref("HTMLElement/dragend_event", "dragend")}} event, for instance, if the desired dropEffect is "move", then the data being dragged should be removed from the source. ## Value A string representing the drag operation effect. The possible values are: - `copy` - : A copy of the source item is made at the new location. - `move` - : An item is moved to a new location. - `link` - : A link is established to the source at the new location. - `none` - : The item may not be dropped. Assigning any other value to `dropEffect` has no effect and the old value is retained. ## Example This example shows the use of the `dropEffect` and {{domxref("DataTransfer.effectAllowed","effectAllowed")}} properties. ### HTML ```html <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element. </p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);"> Drop Zone </div> ``` ### CSS ```css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } ``` ### JavaScript ```js function dragstart_handler(ev) { console.log( `dragStart: dropEffect = ${ev.dataTransfer.dropEffect} ; effectAllowed = ${ev.dataTransfer.effectAllowed}`, ); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.dataTransfer.setData("text", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function drop_handler(ev) { console.log( `drop: dropEffect = ${ev.dataTransfer.dropEffect} ; effectAllowed = ${ev.dataTransfer.effectAllowed}`, ); ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM const data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log( `dragOver: dropEffect = ${ev.dataTransfer.dropEffect} ; effectAllowed = ${ev.dataTransfer.effectAllowed}`, ); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move"; } ``` {{EmbedLiveSample('Example', 300, 250)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drag and drop](/en-US/docs/Web/API/HTML_Drag_and_Drop_API) - [Drag Operations](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - [Recommended Drag Types](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types) - [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/credential_management_api/index.md
--- title: Credential Management API slug: Web/API/Credential_Management_API page-type: web-api-overview browser-compat: - api.Credential - api.CredentialsContainer - api.FederatedCredential - api.PasswordCredential spec-urls: https://w3c.github.io/webappsec-credential-management/ --- {{DefaultAPISidebar("Credential Management API")}}{{securecontext_header}} The Credential Management API lets a website store and retrieve password, public key, and federated credentials. These capabilities allow users to sign in without typing passwords, see the federated account they used to sign in to a site, and resume a session without the explicit sign-in flow of an expired session. ## Concepts and usage This API lets websites interact with a user agent's password system directly so that websites can deal in a uniform way with site credentials and user agents can provide better assistance with the management of their credentials. For example, user agents have a particularly hard time dealing with federated identity providers or esoteric sign-in mechanisms. To address these problems, the Credential Management API provides ways for a website to store and retrieve different types of credentials. This gives users capabilities such as seeing the federated account they used to sign on to a site, or resuming a session without the explicit sign-in flow of an expired session. > **Note:** This API is restricted to top-level contexts. Calls to `get()` and `store()` within an `<iframe>` element will resolve without effect. ### Subdomain-shared credentials Later versions of the spec allow credentials to be retrieved from a different subdomain. For example, a password stored in `login.example.com` may be used to log in to `www.example.com`. To take advantage of this, a password must be explicitly stored by calling {{domxref("CredentialsContainer.store()")}}. This is sometimes referred to as public suffix list (PSL) matching; however the spec only _recommends_ using PSL to determine the effective scope of a credential. It does not require it. Hence browsers may vary in their implementation. ## Interfaces - {{domxref("Credential")}} - : Provides information about an entity as a prerequisite to a trust decision. - {{domxref("CredentialsContainer")}} - : Exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. This interface is accessible from `navigator.credentials`. - {{domxref("FederatedCredential")}} - : Provides information about credentials from a federated identity provider, which is an entity that a website trusts to correctly authenticate a user, and which provides an API for that purpose. [OpenID Connect](https://openid.net/developers/specs/) is an example of such a framework. - {{domxref("PasswordCredential")}} - : Provides information about a username/password pair. ### Extensions to other interfaces - {{domxref("Navigator.credentials")}} {{ReadOnlyInline}} - : Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Web Authentication API", "", "", "nocode")}} - {{domxref("WebOTP API", "", "", "nocode")}} - {{domxref("FedCM API", "Federated Credential Management (FedCM) API", "", "nocode")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice/index.md
--- title: BluetoothRemoteGATTService slug: Web/API/BluetoothRemoteGATTService page-type: web-api-interface status: - experimental browser-compat: api.BluetoothRemoteGATTService --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The `BluetoothRemoteGATTService` interface of the [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API) represents a service provided by a GATT server, including a device, a list of referenced services, and a list of the characteristics of this service. {{InheritanceDiagram}} ## Instance properties - {{domxref("BluetoothRemoteGATTService.device")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns information about a Bluetooth device through an instance of {{domxref("BluetoothDevice")}}. - {{domxref("BluetoothRemoteGATTService.isPrimary")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a boolean value indicating whether this is a primary or secondary service. - {{domxref("BluetoothRemoteGATTService.uuid")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a string representing the UUID of this service. ## Instance methods - {{domxref("BluetoothRemoteGATTService.getCharacteristic()")}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} to an instance of {{domxref("BluetoothRemoteGATTCharacteristic")}} for a given universally unique identifier (UUID). - {{domxref("BluetoothRemoteGATTService.getCharacteristics()")}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} to an {{jsxref("Array")}} of {{domxref("BluetoothRemoteGATTCharacteristic")}} instances for an optional universally unique identifier (UUID). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} {{APIRef("Web Bluetooth")}}
0
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice/getcharacteristics/index.md
--- title: "BluetoothRemoteGATTService: getCharacteristics() method" short-title: getCharacteristics() slug: Web/API/BluetoothRemoteGATTService/getCharacteristics page-type: web-api-instance-method status: - experimental browser-compat: api.BluetoothRemoteGATTService.getCharacteristics --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`BluetoothGATTService.getCharacteristics()`** method returns a {{jsxref("Promise")}} to a list of {{domxref("BluetoothRemoteGATTCharacteristic")}} instances for a given universally unique identifier (UUID). ## Syntax ```js-nolint getCharacteristics(characteristics) ``` ### Parameters - `characteristics` - : The UUID of a characteristic, for example `'00002a37-0000-1000-8000-00805f9b34fb'` for the Heart Rate Measurement characteristic. ### Return value A {{jsxref("Promise")}} to an {{jsxref("Array")}} of {{domxref("BluetoothRemoteGATTCharacteristic")}} instances. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} {{APIRef("Web Bluetooth")}}
0
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice/device/index.md
--- title: "BluetoothRemoteGATTService: device property" short-title: device slug: Web/API/BluetoothRemoteGATTService/device page-type: web-api-instance-property status: - experimental browser-compat: api.BluetoothRemoteGATTService.device --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`BluetoothGATTService.device`** read-only property returns information about a Bluetooth device through an instance of {{domxref("BluetoothDevice")}}. ## Value An instance of {{domxref("BluetoothDevice")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} {{APIRef("Web Bluetooth")}}
0
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice/uuid/index.md
--- title: "BluetoothRemoteGATTService: uuid property" short-title: uuid slug: Web/API/BluetoothRemoteGATTService/uuid page-type: web-api-instance-property status: - experimental browser-compat: api.BluetoothRemoteGATTService.uuid --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`BluetoothGATTService.uuid`** read-only property returns a string representing the UUID of this service. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} {{APIRef("Web Bluetooth")}}
0
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice/getcharacteristic/index.md
--- title: "BluetoothRemoteGATTService: getCharacteristic() method" short-title: getCharacteristic() slug: Web/API/BluetoothRemoteGATTService/getCharacteristic page-type: web-api-instance-method status: - experimental browser-compat: api.BluetoothRemoteGATTService.getCharacteristic --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`BluetoothGATTService.getCharacteristic()`** method returns a {{jsxref("Promise")}} to an instance of {{domxref("BluetoothRemoteGATTCharacteristic")}} for a given universally unique identifier (UUID). ## Syntax ```js-nolint getCharacteristic(characteristic) ``` ### Parameters - `characteristic` - : The UUID of a characteristic, for example `'00002a37-0000-1000-8000-00805f9b34fb'` for the Heart Rate Measurement characteristic. ### Return value A {{jsxref("Promise")}} to an instance of {{domxref("BluetoothRemoteGATTCharacteristic")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} {{APIRef("Web Bluetooth")}}
0
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice
data/mdn-content/files/en-us/web/api/bluetoothremotegattservice/isprimary/index.md
--- title: "BluetoothRemoteGATTService: isPrimary property" short-title: isPrimary slug: Web/API/BluetoothRemoteGATTService/isPrimary page-type: web-api-instance-property status: - experimental browser-compat: api.BluetoothRemoteGATTService.isPrimary --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`BluetoothGATTService.isPrimary`** read-only property returns a boolean value that indicates whether this is a primary service. If it is not a primary service, it is a secondary service. ## Value A boolean value. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} {{APIRef("Web Bluetooth")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/web_workers_api/index.md
--- title: Web Workers API slug: Web/API/Web_Workers_API page-type: web-api-overview spec-urls: https://html.spec.whatwg.org/multipage/workers.html#workers --- {{DefaultAPISidebar("Web Workers API")}} **Web Workers** makes it possible to run a script operation in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down. ## Web Workers concepts and usage A worker is an object created using a constructor (e.g. {{DOMxRef("Worker.Worker", "Worker()")}}) that runs a named JavaScript file β€” this file contains the code that will run in the worker thread. In addition to the standard [JavaScript](/en-US/docs/Web/JavaScript) set of functions (such as {{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("Object")}}, {{jsxref("JSON")}}, etc.), you can run almost any code you like inside a worker thread. There are some exceptions: for example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("Window")}} object. For information about the code that you _can_ run see [worker global context and functions](#worker_global_contexts_and_functions), and [supported web APIs](#supported_web_apis) below. Data is sent between workers and the main thread via a system of messages β€” both sides send their messages using the `postMessage()` method, and respond to messages via the `onmessage` event handler (the message is contained within the {{domxref("Worker/message_event", "message")}} event's `data` property). The data is copied rather than shared. Workers may in turn spawn new workers, as long as those workers are hosted within the same {{glossary("origin")}} as the parent page. In addition, workers can make network requests using the {{domxref("fetch()")}} or {{domxref("XMLHttpRequest")}} APIs (although note that the {{domxref("XMLHttpRequest.responseXML", "responseXML")}} attribute of `XMLHttpRequest` will always be `null`). ### Worker types There are a number of different types of workers: - {{domxref("Worker", "Dedicated workers", "", "nocode")}} are workers that are utilized by a single script. This context is represented by a {{DOMxRef("DedicatedWorkerGlobalScope")}} object. - {{domxref("SharedWorker", "Shared workers", "", "nocode")}} are workers that can be utilized by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complex than dedicated workers β€” scripts must communicate via an active port. - {{domxref("Service Worker API", "Service Workers", "", "nocode")}} essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs. > **Note:** As per the [Web workers Spec](https://html.spec.whatwg.org/multipage/workers.html#runtime-script-errors-2), worker error events should not bubble (see [Firefox bug 1188141](https://bugzil.la/1188141)). This has been implemented in Firefox 42. ### Worker global contexts and functions Workers run in a different global context than the current {{DOMxRef("window")}}! While {{domxref("Window")}} is not directly available to workers, many of the same methods are defined in a shared mixin (`WindowOrWorkerGlobalScope`), and made available to workers through their own {{domxref("WorkerGlobalScope")}}-derived contexts: - {{domxref("DedicatedWorkerGlobalScope")}} for dedicated workers - {{domxref("SharedWorkerGlobalScope")}} for shared workers - {{domxref("ServiceWorkerGlobalScope")}} for [service workers](/en-US/docs/Web/API/Service_Worker_API) Some of the functions (a subset) that are common to all workers and to the main thread (from `WindowOrWorkerGlobalScope`) are: - {{domxref("atob", "atob()")}} - {{domxref("btoa", "btoa()")}} - {{domxref("clearInterval()")}} - {{domxref("clearTimeout()")}} - {{domxref("createImageBitmap()")}} - {{domxref("WorkerGlobalScope.dump()", "dump()")}} {{non-standard_inline}} - {{domxref("fetch()")}} - {{domxref("queueMicrotask()")}} - {{domxref("reportError()")}} - {{domxref("setInterval()")}} - {{domxref("setTimeout()")}} - {{domxref("structuredClone()")}} - {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()", "requestAnimationFrame()")}} (dedicated workers only) - {{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()", "cancelAnimationFrame()")}} (dedicated workers only) The following functions are **only** available to workers: - {{domxref("WorkerGlobalScope.importScripts()", "importScripts()")}}, - {{domxref("DedicatedWorkerGlobalScope.postMessage()", "postMessage()")}} (dedicated workers only). ### Supported Web APIs > **Note:** If a listed API is supported by a platform in a particular version, then it can generally be assumed to be available in web workers. You can also test support for a particular object/function using the site: <https://worker-playground.glitch.me/> The following Web APIs are available to workers: - {{domxref("Background Fetch API", "", "", "nocode")}} - {{domxref("Background Synchronization API", "", "", "nocode")}} - {{domxref("Barcode Detection API", "", "", "nocode")}} - {{domxref("Broadcast Channel API", "", "", "nocode")}} - {{domxref("Canvas API", "", "", "nocode")}} - {{domxref("Channel Messaging API", "", "", "nocode")}} - {{domxref("Console API", "", "", "nocode")}} - {{domxref("Compression Streams API", "", "", "nocode")}} - {{domxref("CSS Font Loading API", "", "", "nocode")}} - {{domxref("CustomEvent")}} - {{domxref("Encoding API", "", "", "nocode")}} (e.g. {{domxref("TextEncoder")}}, {{domxref("TextDecoder")}}) - {{domxref("Fetch API", "", "", "nocode")}} - {{domxref("File API", "", "", "nocode")}} - {{domxref("File System API", "", "", "nocode")}} - {{domxref("Idle Detection API", "", "", "nocode")}} - {{domxref("IndexedDB API", "", "", "nocode")}} - {{domxref("Media Capabilities API", "", "", "nocode")}} - {{domxref("Media Source Extensions API", "", "", "nocode")}} (dedicated workers only) - {{domxref("Network Information API", "", "", "nocode")}} - {{domxref("Notifications API", "", "", "nocode")}} - {{domxref("Payment Handler API", "", "", "nocode")}} - {{domxref("Performance API", "", "", "nocode")}} - {{domxref("Permissions API", "", "", "nocode")}} - {{domxref("Prioritized Task Scheduling API", "", "", "nocode")}} - {{domxref("Push API", "", "", "nocode")}} - {{domxref("Server-Sent Events", "", "", "nocode")}} - {{domxref("Service Worker API", "", "", "nocode")}} - {{domxref("Streams API", "", "", "nocode")}} - {{domxref("Trusted Types API", "", "", "nocode")}} - {{domxref("URL API", "", "", "nocode")}} (e.g. {{domxref("URL")}}) - {{domxref("URL Pattern API", "", "", "nocode")}} - {{domxref("User-Agent Client Hints API", "", "", "nocode")}} - {{domxref("WebCodecs API", "", "", "nocode")}} - {{domxref("Web Crypto API", "", "", "nocode")}} (e.g. {{domxref("Crypto")}}) - {{domxref("Web Locks API", "", "", "nocode")}} - {{domxref("Web Serial API", "", "", "nocode")}} - {{domxref("Web Periodic Background Synchronization API", "", "", "nocode")}} - {{domxref("WebGPU API", "", "", "nocode")}} - {{domxref("WebUSB API", "", "", "nocode")}} - {{domxref("WebSockets API", "", "", "nocode")}} - {{domxref("XMLHttpRequest API", "", "", "nocode")}} Workers can also spawn other workers, so these APIs are also available: - {{domxref("Worker")}} - {{domxref("WorkerGlobalScope")}} - {{domxref("WorkerLocation")}} - {{domxref("WorkerNavigator")}} ## Web Worker interfaces - {{DOMxRef("Worker")}} - : Represents a running worker thread, allowing you to pass messages to the running worker code. - {{DOMxRef("WorkerLocation")}} - : Defines the absolute location of the script executed by the {{domxref("Worker")}}. - {{DOMxRef("SharedWorker")}} - : Represents a specific kind of worker that can be accessed from several {{glossary("browsing context", "browsing contexts")}} (i.e. windows, tabs, or iframes) or even other workers. - {{DOMxRef("WorkerGlobalScope")}} - : Represents the generic scope of any worker (doing the same job as {{DOMxRef("Window")}} does for normal web content). Different types of worker have scope objects that inherit from this interface and add more specific features. - {{DOMxRef("DedicatedWorkerGlobalScope")}} - : Represents the scope of a dedicated worker, inheriting from {{DOMxRef("WorkerGlobalScope")}} and adding some dedicated features. - {{DOMxRef("SharedWorkerGlobalScope")}} - : Represents the scope of a shared worker, inheriting from {{DOMxRef("WorkerGlobalScope")}} and adding some dedicated features. - {{DOMxRef("WorkerNavigator")}} - : Represents the identity and state of the user agent (the client). ## Examples We have created a couple of demos to show web worker usage: - [Basic dedicated worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-web-worker) ([run dedicated worker](https://mdn.github.io/dom-examples/web-workers/simple-web-worker/)). - [Basic shared worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker) ([run shared worker](https://mdn.github.io/dom-examples/web-workers/simple-shared-worker/)). - [OffscreenCanvas worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/offscreen-canvas-worker) ([run OffscreenCanvas worker](https://mdn.github.io/dom-examples/web-workers/offscreen-canvas-worker/)). You can find out more information on how these demos work in [Using Web Workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers). ## Specifications {{Specifications}} ## See also - [Using Web Workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) - {{domxref("Worker")}} interface - {{domxref("SharedWorker")}} interface - {{domxref("Service Worker API", "", "", "nocode")}}
0
data/mdn-content/files/en-us/web/api/web_workers_api
data/mdn-content/files/en-us/web/api/web_workers_api/functions_and_classes_available_to_workers/index.md
--- title: Functions and classes available to Web Workers slug: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers page-type: guide --- {{DefaultAPISidebar("Web Workers API")}} In addition to the standard [JavaScript](/en-US/docs/Web/JavaScript) set of functions (such as {{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("Object")}}, {{jsxref("JSON")}}, etc.), there are a variety of functions available from the DOM to workers. This article provides a list of those. ## Worker Contexts & Functions **Workers run in a different global context than the current window!** While {{domxref("Window")}} is not directly available to workers, many of the same methods are defined in a shared mixin (`WindowOrWorkerGlobalScope`), and made available to workers through their own {{domxref("WorkerGlobalScope")}}-derived contexts: - {{domxref("DedicatedWorkerGlobalScope")}} for dedicated workers - {{domxref("SharedWorkerGlobalScope")}} for shared workers - {{domxref("ServiceWorkerGlobalScope")}} for [service workers](/en-US/docs/Web/API/Service_Worker_API) Some of the functions (a subset) that are common to all workers and to the main thread (from `WindowOrWorkerGlobalScope`) are: - {{domxref("atob", "atob()")}} - {{domxref("btoa", "btoa()")}} - {{domxref("clearInterval()")}} - {{domxref("clearTimeout()")}} - {{domxref("createImageBitmap()")}} - {{domxref("WorkerGlobalScope.dump()", "dump()")}} {{non-standard_inline}} - {{domxref("fetch()")}} - {{domxref("queueMicrotask()")}} - {{domxref("reportError()")}} - {{domxref("setInterval()")}} - {{domxref("setTimeout()")}} - {{domxref("structuredClone()")}} - {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()", "requestAnimationFrame()")}} (dedicated workers only) - {{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()", "cancelAnimationFrame()")}} (dedicated workers only) The following functions are **only** available to workers: - {{domxref("WorkerGlobalScope.importScripts", "WorkerGlobalScope.importScripts()")}} (all workers) - {{domxref("DedicatedWorkerGlobalScope.postMessage")}} (dedicated workers only) ## Web APIs available in workers > **Note:** If a listed API is supported by a platform in a particular version, then it can generally be assumed to be available in web workers. You can also test support for a particular object/function using the site: <https://worker-playground.glitch.me/> The following Web APIs are available to workers: - {{domxref("Background Fetch API", "", "", "nocode")}} - {{domxref("Background Synchronization API", "", "", "nocode")}} - {{domxref("Barcode Detection API", "", "", "nocode")}} - {{domxref("Broadcast Channel API", "", "", "nocode")}} - {{domxref("Canvas API", "", "", "nocode")}} - {{domxref("Channel Messaging API", "", "", "nocode")}} - {{domxref("Console API", "", "", "nocode")}} - {{domxref("Compression Streams API", "", "", "nocode")}} - {{domxref("CSS Font Loading API", "", "", "nocode")}} - {{domxref("CustomEvent")}} - {{domxref("Encoding API", "", "", "nocode")}} (e.g. {{domxref("TextEncoder")}}, {{domxref("TextDecoder")}}) - {{domxref("Fetch API", "", "", "nocode")}} - {{domxref("File API", "", "", "nocode")}} - {{domxref("File System API", "", "", "nocode")}} - {{domxref("Idle Detection API", "", "", "nocode")}} - {{domxref("IndexedDB API", "", "", "nocode")}} - {{domxref("Media Capabilities API", "", "", "nocode")}} - {{domxref("Media Source Extensions API", "", "", "nocode")}} (dedicated workers only) - {{domxref("Network Information API", "", "", "nocode")}} - {{domxref("Notifications API", "", "", "nocode")}} - {{domxref("Payment Handler API", "", "", "nocode")}} - {{domxref("Performance API", "", "", "nocode")}} - {{domxref("Permissions API", "", "", "nocode")}} - {{domxref("Prioritized Task Scheduling API", "", "", "nocode")}} - {{domxref("Push API", "", "", "nocode")}} - {{domxref("Server-sent events", "", "", "nocode")}} - {{domxref("Service Worker API", "", "", "nocode")}} - {{domxref("Streams API", "", "", "nocode")}} - {{domxref("Trusted Types API", "", "", "nocode")}} - {{domxref("URL API", "", "", "nocode")}} (e.g. {{domxref("URL")}}) - {{domxref("URL Pattern API", "", "", "nocode")}} - {{domxref("User-Agent Client Hints API", "", "", "nocode")}} - {{domxref("WebCodecs API", "", "", "nocode")}} - {{domxref("Web Crypto API", "", "", "nocode")}} (e.g. {{domxref("Crypto")}}) - {{domxref("Web Locks API", "", "", "nocode")}} - {{domxref("Web Serial API", "", "", "nocode")}} - {{domxref("Web Periodic Background Synchronization API", "", "", "nocode")}} - {{domxref("WebGPU API", "", "", "nocode")}} - {{domxref("WebUSB API", "", "", "nocode")}} - {{domxref("WebSockets API", "", "", "nocode")}} - {{domxref("XMLHttpRequest API", "", "", "nocode")}} Workers can also spawn other workers, so these APIs are also available: - {{domxref("Worker")}} - {{domxref("WorkerGlobalScope")}} - {{domxref("WorkerLocation")}} - {{domxref("WorkerNavigator")}} ## See also - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) - {{domxref("Worker")}}
0
data/mdn-content/files/en-us/web/api/web_workers_api
data/mdn-content/files/en-us/web/api/web_workers_api/using_web_workers/index.md
--- title: Using Web Workers slug: Web/API/Web_Workers_API/Using_web_workers page-type: guide spec-urls: https://html.spec.whatwg.org/multipage/#workers --- {{DefaultAPISidebar("Web Workers API")}} Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can make network requests using the {{domxref("fetch()")}} or {{domxref("XMLHttpRequest")}} APIs. Once created, a worker can send messages to the JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa). This article provides a detailed introduction to using web workers. ## Web Workers API A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file β€” this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. Thus, using the {{domxref("window")}} shortcut to get the current global scope (instead of {{domxref("window.self","self")}}) within a {{domxref("Worker")}} will return an error. The worker context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}). A dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts. > **Note:** See [The Web Workers API landing page](/en-US/docs/Web/API/Web_Workers_API) for reference documentation on workers and additional guides. You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under `window`, including [WebSockets](/en-US/docs/Web/API/WebSockets_API), and data storage mechanisms like [IndexedDB](/en-US/docs/Web/API/IndexedDB_API). See [Functions and classes available to workers](/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers) for more details. Data is sent between workers and the main thread via a system of messages β€” both sides send their messages using the `postMessage()` method, and respond to messages via the `onmessage` event handler (the message is contained within the {{domxref("Worker/message_event", "message")}} event's data attribute). The data is copied rather than shared. Workers may in turn spawn new workers, as long as those workers are hosted within the same {{glossary("origin")}} as the parent page. In addition, workers can make network requests using the {{domxref("fetch()")}} or [`XMLHttpRequest`](/en-US/docs/Web/API/XMLHttpRequest) APIs (although note that the {{domxref("XMLHttpRequest.responseXML", "responseXML")}} attribute of `XMLHttpRequest` will always be `null`). ## Dedicated workers As mentioned above, a dedicated worker is only accessible by the script that called it. In this section we'll discuss the JavaScript found in our [Basic dedicated worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-web-worker) ([run dedicated worker](https://mdn.github.io/dom-examples/web-workers/simple-web-worker/)): This allows you to enter two numbers to be multiplied together. The numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed. This example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. More advanced details are covered later on in the article. ### Worker feature detection For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following ([main.js](https://github.com/mdn/dom-examples/blob/main/web-workers/simple-web-worker/main.js)): ```js if (window.Worker) { // … } ``` ### Spawning a dedicated worker Creating a new worker is simple. All you need to do is call the {{domxref("Worker.Worker", "Worker()")}} constructor, specifying the URI of a script to execute in the worker thread ([main.js](https://github.com/mdn/dom-examples/blob/main/web-workers/simple-web-worker/main.js)): ```js const myWorker = new Worker("worker.js"); ``` ### Sending messages to and from a dedicated worker The magic of workers happens via the {{domxref("Worker.postMessage", "postMessage()")}} method and the {{domxref("Worker.message_event", "onmessage")}} event handler. When you want to send a message to the worker, you post messages to it like this ([main.js](https://github.com/mdn/dom-examples/blob/main/web-workers/simple-web-worker/main.js)): ```js first.onchange = () => { myWorker.postMessage([first.value, second.value]); console.log("Message posted to worker"); }; second.onchange = () => { myWorker.postMessage([first.value, second.value]); console.log("Message posted to worker"); }; ``` So here we have two {{htmlelement("input")}} elements represented by the variables `first` and `second`; when the value of either is changed, `myWorker.postMessage([first.value,second.value])` is used to send the value inside both to the worker, as an array. You can send pretty much anything you like in the message. In the worker, we can respond when the message is received by writing an event handler block like this ([worker.js](https://github.com/mdn/dom-examples/blob/main/web-workers/simple-web-worker/worker.js)): ```js onmessage = (e) => { console.log("Message received from main script"); const workerResult = `Result: ${e.data[0] * e.data[1]}`; console.log("Posting message back to main script"); postMessage(workerResult); }; ``` The `onmessage` handler allows us to run some code whenever a message is received, with the message itself being available in the `message` event's `data` attribute. Here we multiply together the two numbers then use `postMessage()` again, to post the result back to the main thread. Back in the main thread, we use `onmessage` again, to respond to the message sent back from the worker: ```js myWorker.onmessage = (e) => { result.textContent = e.data; console.log("Message received from worker"); }; ``` Here we grab the message event data and set it as the `textContent` of the result paragraph, so the user can see the result of the calculation. > **Note:** Notice that `onmessage` and `postMessage()` need to be hung off the `Worker` object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope. > **Note:** When a message is passed between the main thread and worker, it is copied or "transferred" (moved), not shared. Read [Transferring data to and from workers: further details](#transferring_data_to_and_from_workers_further_details) for a much more thorough explanation. ### Terminating a worker If you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's {{domxref("Worker", "terminate")}} method: ```js myWorker.terminate(); ``` The worker thread is killed immediately. ### Handling errors When a runtime error occurs in the worker, its `onerror` event handler is called. It receives an event named `error` which implements the `ErrorEvent` interface. The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's [`preventDefault()`](/en-US/docs/Web/API/Event/preventDefault) method. The error event has the following three fields that are of interest: - `message` - : A human-readable error message. - `filename` - : The name of the script file in which the error occurred. - `lineno` - : The line number of the script file on which the error occurred. ### Spawning subworkers Workers may spawn more workers if they wish. So-called sub-workers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are. ### Importing scripts and libraries Worker threads have access to a global function, `importScripts()`, which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all the following examples are valid: ```js importScripts(); /* imports nothing */ importScripts("foo.js"); /* imports just "foo.js" */ importScripts("foo.js", "bar.js"); /* imports two scripts */ importScripts( "//example.com/hello.js", ); /* You can import scripts from other origins */ ``` The browser loads each listed script and executes it. Any global objects from each script may then be used by the worker. If the script can't be loaded, `NETWORK_ERROR` is thrown, and subsequent code will not be executed. Previously executed code (including code deferred using {{domxref("setTimeout()")}}) will still be functional though. Function declarations **after** the `importScripts()` method are also kept, since these are always evaluated before the rest of the code. > **Note:** Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into `importScripts()`. This is done synchronously; `importScripts()` does not return until all the scripts have been loaded and executed. ## Shared workers A shared worker is accessible by multiple scripts β€” even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the JavaScript found in our [Basic shared worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker) ([run shared worker](https://mdn.github.io/dom-examples/web-workers/simple-shared-worker/)): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: _multiplying two numbers_, or _squaring a number_. Both scripts use the same worker to do the actual calculation required. Here we'll concentrate on the differences between dedicated and shared workers. Note that in this example we have two HTML pages, each with JavaScript applied that uses the same single worker file. > **Note:** If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port). > **Note:** In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ([Firefox bug 1177621](https://bugzil.la/1177621)). ### Spawning a shared worker Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see [index.html](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker/index.html) and [index2.html](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker/index2.html)) β€” each one has to spin up the worker using code like the following: ```js const myWorker = new SharedWorker("worker.js"); ``` One big difference is that with a shared worker you have to communicate via a `port` object β€” an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers). The port connection needs to be started either implicitly by use of the `onmessage` event handler or explicitly with the `start()` method before any messages can be posted. Calling `start()` is only needed if the `message` event is wired up via the `addEventListener()` method. > **Note:** When using the `start()` method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed. ### Sending messages to and from a shared worker Now messages can be sent to the worker as before, but the `postMessage()` method has to be invoked through the port object (again, you'll see similar constructs in both [multiply.js](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker/multiply.js) and [square.js](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker/square.js)): ```js squareNumber.onchange = () => { myWorker.port.postMessage([squareNumber.value, squareNumber.value]); console.log("Message posted to worker"); }; ``` Now, on to the worker. There is a bit more complexity here as well ([worker.js](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker/worker.js)): ```js onconnect = (e) => { const port = e.ports[0]; port.onmessage = (e) => { const workerResult = `Result: ${e.data[0] * e.data[1]}`; port.postMessage(workerResult); }; }; ``` First, we use an `onconnect` handler to fire code when a connection to the port happens (i.e. when the `onmessage` event handler in the parent thread is set up, or when the `start()` method is explicitly called in the parent thread). We use the `ports` attribute of this event object to grab the port and store it in a variable. Next, we add an `onmessage` handler on the port to do the calculation and return the result to the main thread. Setting up this `onmessage` handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to `port.start()` is not actually needed, as noted above. Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both [multiply.js](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker/multiply.js) and [square.js](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker/square.js)): ```js myWorker.port.onmessage = (e) => { result2.textContent = e.data; console.log("Message received from worker"); }; ``` When a message comes back through the port from the worker, we insert the calculation result inside the appropriate result paragraph. ## About thread safety The {{domxref("Worker")}} interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause "interesting" effects in your code if you aren't careful. However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code. ## Content security policy Workers are considered to have their own execution context, distinct from the document that created them. For this reason they are, in general, not governed by the [content security policy](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy) of the document (or parent worker) that created them. So for example, suppose a document is served with the following header: ```http Content-Security-Policy: script-src 'self' ``` Among other things, this will prevent any scripts it includes from using [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). However, if the script constructs a worker, code running in the worker's context _will_ be allowed to use `eval()`. To specify a content security policy for the worker, set a [Content-Security-Policy](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) response header for the request which delivered the worker script itself. The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the CSP of the document or worker that created it. ## Transferring data to and from workers: further details Data passed between the main page and workers is **copied**, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker **do not share the same instance**, so the end result is that **a duplicate** is created on each end. Most browsers implement this feature as [structured cloning](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). To illustrate this, let's create a function named `emulateMessage()`, which will simulate the behavior of a value that is _cloned and not shared_ during the passage from a `worker` to the main page or vice versa: ```js function emulateMessage(vVal) { return eval(`(${JSON.stringify(vVal)})`); } // Tests // test #1 const example1 = new Number(3); console.log(typeof example1); // object console.log(typeof emulateMessage(example1)); // number // test #2 const example2 = true; console.log(typeof example2); // boolean console.log(typeof emulateMessage(example2)); // boolean // test #3 const example3 = new String("Hello World"); console.log(typeof example3); // object console.log(typeof emulateMessage(example3)); // string // test #4 const example4 = { name: "Carina Anand", age: 43, }; console.log(typeof example4); // object console.log(typeof emulateMessage(example4)); // object // test #5 function Animal(type, age) { this.type = type; this.age = age; } const example5 = new Animal("Cat", 3); alert(example5.constructor); // Animal alert(emulateMessage(example5).constructor); // Object ``` A value that is cloned and not shared is called _message_. As you will probably know by now, _messages_ can be sent to and from the main thread by using `postMessage()`, and the `message` event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker. **example.html**: (the main page): ```js const myWorker = new Worker("my_task.js"); myWorker.onmessage = (event) => { console.log(`Worker said : ${event.data}`); }; myWorker.postMessage("ali"); ``` **my_task.js** (the worker): ```js postMessage("I'm working before postMessage('ali')."); onmessage = (event) => { postMessage(`Hi, ${event.data}`); }; ``` The [structured cloning](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) algorithm can accept JSON and a few things that JSON can't β€” like circular references. ### Passing data examples #### Example 1: Advanced passing JSON Data and creating a switching system If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together. First, we create a `QueryableWorker` class that takes the URL of the worker, a default listener, and an error handler, and this class is going to keep track of a list of listeners and help us communicate with the worker: ```js function QueryableWorker(url, defaultListener, onError) { const instance = this; const worker = new Worker(url); const listeners = {}; this.defaultListener = defaultListener ?? (() => {}); if (onError) { worker.onerror = onError; } this.postMessage = (message) => { worker.postMessage(message); }; this.terminate = () => { worker.terminate(); }; } ``` Then we add the methods of adding/removing listeners: ```js this.addListeners = (name, listener) => { listeners[name] = listener; }; this.removeListeners = (name) => { delete listeners[name]; }; ``` Here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after three seconds. In order to achieve that we first implement a `sendQuery` method which queries if the worker actually has the corresponding methods to do what we want. ```js // This functions takes at least one argument, the method name we want to query. // Then we can pass in the arguments that the method needs. this.sendQuery = (queryMethod, ...queryMethodArguments) => { if (!queryMethod) { throw new TypeError( "QueryableWorker.sendQuery takes at least one argument", ); } worker.postMessage({ queryMethod, queryMethodArguments, }); }; ``` We finish QueryableWorker with the `onmessage` method. If the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in `listeners`.: ```js worker.onmessage = (event) => { if ( event.data instanceof Object && Object.hasOwn(event.data, "queryMethodListener") && Object.hasOwn(event.data, "queryMethodArguments") ) { listeners[event.data.queryMethodListener].apply( instance, event.data.queryMethodArguments, ); } else { this.defaultListener.call(instance, event.data); } }; ``` Now onto the worker. First we need to have the methods to handle the two simple operations: ```js const queryableFunctions = { getDifference(a, b) { reply("printStuff", a - b); }, waitSomeTime() { setTimeout(() => { reply("doAlert", 3, "seconds"); }, 3000); }, }; function reply(queryMethodListener, ...queryMethodArguments) { if (!queryMethodListener) { throw new TypeError("reply - takes at least one argument"); } postMessage({ queryMethodListener, queryMethodArguments, }); } /* This method is called when main page calls QueryWorker's postMessage method directly*/ function defaultReply(message) { // do something } ``` And the `onmessage` method is now trivial: ```js onmessage = (event) => { if ( event.data instanceof Object && Object.hasOwn(event.data, "queryMethod") && Object.hasOwn(event.data, "queryMethodArguments") ) { queryableFunctions[event.data.queryMethod].apply( self, event.data.queryMethodArguments, ); } else { defaultReply(event.data); } }; ``` Here are the full implementation: **example.html** (the main page): ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <title>MDN Example - Queryable worker</title> <script type="text/javascript"> // QueryableWorker instances methods: // * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc.): calls a Worker's queryable function // * postMessage(string or JSON Data): see Worker.prototype.postMessage() // * terminate(): terminates the Worker // * addListener(name, function): adds a listener // * removeListener(name): removes a listener // QueryableWorker instances properties: // * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly function QueryableWorker(url, defaultListener, onError) { const instance = this; const worker = new Worker(url); const listeners = {}; this.defaultListener = defaultListener ?? (() => {}); if (onError) { worker.onerror = onError; } this.postMessage = (message) => { worker.postMessage(message); }; this.terminate = () => { worker.terminate(); }; this.addListener = (name, listener) => { listeners[name] = listener; }; this.removeListener = (name) => { delete listeners[name]; }; // This functions takes at least one argument, the method name we want to query. // Then we can pass in the arguments that the method needs. this.sendQuery = (queryMethod, ...queryMethodArguments) => { if (!queryMethod) { throw new TypeError( "QueryableWorker.sendQuery takes at least one argument", ); } worker.postMessage({ queryMethod, queryMethodArguments, }); }; worker.onmessage = (event) => { if ( event.data instanceof Object && Object.hasOwn(event.data, "queryMethodListener") && Object.hasOwn(event.data, "queryMethodArguments") ) { listeners[event.data.queryMethodListener].apply( instance, event.data.queryMethodArguments, ); } else { this.defaultListener.call(instance, event.data); } }; } // your custom "queryable" worker const myTask = new QueryableWorker("my_task.js"); // your custom "listeners" myTask.addListener("printStuff", (result) => { document .getElementById("firstLink") .parentNode.appendChild( document.createTextNode(`The difference is ${result}!`), ); }); myTask.addListener("doAlert", (time, unit) => { alert(`Worker waited for ${time} ${unit} :-)`); }); </script> </head> <body> <ul> <li> <a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);" >What is the difference between 5 and 3?</a > </li> <li> <a href="javascript:myTask.sendQuery('waitSomeTime');" >Wait 3 seconds</a > </li> <li> <a href="javascript:myTask.terminate();">terminate() the Worker</a> </li> </ul> </body> </html> ``` **my_task.js** (the worker): ```js const queryableFunctions = { // example #1: get the difference between two numbers: getDifference(minuend, subtrahend) { reply("printStuff", minuend - subtrahend); }, // example #2: wait three seconds waitSomeTime() { setTimeout(() => { reply("doAlert", 3, "seconds"); }, 3000); }, }; // system functions function defaultReply(message) { // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly // do something } function reply(queryMethodListener, ...queryMethodArguments) { if (!queryMethodListener) { throw new TypeError("reply - not enough arguments"); } postMessage({ queryMethodListener, queryMethodArguments, }); } onmessage = (event) => { if ( event.data instanceof Object && Object.hasOwn(event.data, "queryMethod") && Object.hasOwn(event.data, "queryMethodArguments") ) { queryableFunctions[event.data.queryMethod].apply( self, event.data.queryMethodArguments, ); } else { defaultReply(event.data); } }; ``` It is possible to switch the content of each mainpage -> worker and worker -> mainpage message. And the property names "queryMethod", "queryMethodListeners", "queryMethodArguments" can be anything as long as they are consistent in `QueryableWorker` and the `worker`. ### Passing data by transferring ownership (transferable objects) Modern browsers contain an additional way to pass certain types of objects to or from a worker with high performance. [Transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) are transferred from one context to another with a zero-copy operation, which results in a vast performance improvement when sending large data sets. For example, when transferring an {{jsxref("ArrayBuffer")}} from your main app to a worker script, the original {{jsxref("ArrayBuffer")}} is cleared and no longer usable. Its content is (quite literally) transferred to the worker context. ```js // Create a 32MB "file" and fill it with consecutive values from 0 to 255 – 32MB = 1024 * 1024 * 32 const uInt8Array = new Uint8Array(1024 * 1024 * 32).map((v, i) => i); worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]); ``` ## Embedded workers There is not an "official" way to embed the code of a worker within a web page, like {{HTMLElement("script")}} elements do for normal scripts. But a {{HTMLElement("script")}} element that does not have a `src` attribute and has a `type` attribute that does not identify an executable MIME type can be considered a data block element that JavaScript could use. "Data blocks" is a more general feature of HTML that can carry almost any textual data. So, a worker could be embedded in this way: ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <title>MDN Example - Embedded worker</title> <script type="text/js-worker"> // This script WON'T be parsed by JS engines because its MIME type is text/js-worker. const myVar = 'Hello World!'; // Rest of your worker code goes here. </script> <script> // This script WILL be parsed by JS engines because its MIME type is text/javascript. function pageLog(sMsg) { // Use a fragment: browser will only render/reflow once. const frag = document.createDocumentFragment(); frag.appendChild(document.createTextNode(sMsg)); frag.appendChild(document.createElement("br")); document.querySelector("#logDisplay").appendChild(frag); } </script> <script type="text/js-worker"> // This script WON'T be parsed by JS engines because its MIME type is text/js-worker. onmessage = (event) => { postMessage(myVar); }; // Rest of your worker code goes here. </script> <script> // This script WILL be parsed by JS engines because its MIME type is text/javascript. // In the past blob builder existed, but now we use Blob const blob = new Blob( Array.prototype.map.call( document.querySelectorAll("script[type='text\/js-worker']"), (script) => script.textContent, ), { type: "text/javascript" }, ); // Creating a new document.worker property containing all our "text/js-worker" scripts. document.worker = new Worker(window.URL.createObjectURL(blob)); document.worker.onmessage = (event) => { pageLog(`Received: ${event.data}`); }; // Start the worker. window.onload = () => { document.worker.postMessage(""); }; </script> </head> <body> <div id="logDisplay"></div> </body> </html> ``` The embedded worker is now nested into a new custom `document.worker` property. It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example: ```js function fn2workerURL(fn) { const blob = new Blob([`(${fn.toString()})()`], { type: "text/javascript" }); return URL.createObjectURL(blob); } ``` ## Further examples This section provides further examples of how to use web workers. ### Performing computations in the background Workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibonacci numbers. #### The JavaScript code The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section. ```js self.onmessage = (event) => { const userNum = Number(event.data); self.postMessage(fibonacci(userNum)); }; function fibonacci(num) { let a = 1; let b = 0; while (num > 0) { [a, b] = [a + b, a]; num--; } return b; } ``` The worker sets the property `onmessage` to a function which will receive messages sent when the worker object's `postMessage()` is called. This performs the math and eventually returns the result back to the main thread. #### The HTML code ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>Fibonacci number generator</title> <style> body { width: 500px; } div, p { margin-bottom: 20px; } </style> </head> <body> <form> <div> <label for="number" >Enter a number that is a zero-based index position in the fibonacci sequence to see what number is in that position. For example, enter 6 and you'll get a result of 8 β€” the fibonacci number at index position 6 is 8.</label > <input type="number" id="number" /> </div> <div> <input type="submit" /> </div> </form> <p id="result"></p> <script> const form = document.querySelector("form"); const input = document.querySelector('input[type="number"]'); const result = document.querySelector("p#result"); const worker = new Worker("fibonacci.js"); worker.onmessage = (event) => { result.textContent = event.data; console.log(`Got: ${event.data}`); }; worker.onerror = (error) => { console.log(`Worker error: ${error.message}`); throw error; }; form.onsubmit = (e) => { e.preventDefault(); worker.postMessage(input.value); input.value = ""; }; </script> </body> </html> ``` The web page creates a `<p>` element with the ID `result`, which gets used to display the result, then spawns the worker. After spawning the worker, the `onmessage` handler is configured to display the results by setting the contents of the `<p>` element, and the `onerror` handler is set to log the error message to the devtools console. Finally, a message is sent to the worker to start it. [Try this example live](https://mdn.github.io/dom-examples/web-workers/fibonacci-worker/). ### Dividing tasks among multiple workers As multicore computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores. ## Other types of workers In addition to dedicated and shared web workers, there are other types of workers available: - [ServiceWorkers](/en-US/docs/Web/API/Service_Worker_API) essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs. - [Audio Worklet](/en-US/docs/Web/API/Web_Audio_API#audio_processing_in_javascript) provide the ability for direct scripted audio processing to be done in a worklet (a lightweight version of worker) context. ## Debugging worker threads Most browsers enable you to debug web workers in their JavaScript debuggers in _exactly the same way_ as debugging the main thread! For example, both Firefox and Chrome list JavaScript source files for both the main thread and active worker threads, and all of these files can be opened to set breakpoints and logpoints. To learn how to debug web workers, see the documentation for each browser's JavaScript debugger: - [Chrome Sources panel](https://developer.chrome.com/docs/devtools/javascript/sources/) - [Firefox JavaScript Debugger](https://firefox-source-docs.mozilla.org/devtools-user/debugger/) ## Functions and interfaces available in workers You can use most standard JavaScript features inside a web worker, including: - {{domxref("Navigator")}} - {{domxref("fetch()")}} - {{jsxref("Global_Objects/Array", "Array")}}, {{jsxref("Global_Objects/Date", "Date")}}, {{jsxref("Global_Objects/Math", "Math")}}, and {{jsxref("Global_Objects/String", "String")}} - {{domxref("setTimeout()")}} and {{domxref("setInterval()")}} The main thing you _can't_ do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}, then doing the changes in event handler. > **Note:** You can test whether a method is available to workers using the site: <https://worker-playground.glitch.me/>. For example, if you enter [EventSource](/en-US/docs/Web/API/EventSource) into the site on Firefox 84 you'll see that this is not supported in service workers, but is in dedicated and shared workers. > **Note:** For a complete list of functions available to workers, see [Functions and interfaces available to workers](/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers). ## Specifications {{Specifications}} ## See also - [`Worker`](/en-US/docs/Web/API/Worker) interface - [`SharedWorker`](/en-US/docs/Web/API/SharedWorker) interface - [Functions available to workers](/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers) - [`OffscreenCanvas`](/en-US/docs/Web/API/OffscreenCanvas) interface
0
data/mdn-content/files/en-us/web/api/web_workers_api
data/mdn-content/files/en-us/web/api/web_workers_api/transferable_objects/index.md
--- title: Transferable objects slug: Web/API/Web_Workers_API/Transferable_objects page-type: guide --- {{DefaultAPISidebar("Web Workers API")}} **Transferable objects** are objects that own resources that can be _transferred_ from one context to another, ensuring that the resources are only available in one context at a time. Following a transfer, the original object is no longer usable; it no longer points to the transferred resource, and any attempt to read or write the object will throw an exception. _Transferable objects_ are commonly used to share resources that can only be safely exposed to a single JavaScript thread at a time. For example, an {{jsxref("ArrayBuffer")}} is a transferable object that owns a block of memory. When such a buffer is transferred between threads, the associated memory resource is detached from the original buffer and attached to the buffer object created in the new thread. The buffer object in the original thread is no longer usable because it no longer owns a memory resource. Transferring may also be used when creating deep copies of objects with {{domxref("structuredClone()")}}. Following the cloning operation, the transferred resources are moved rather than copied to the cloned object. The mechanism used to transfer an object's resources depends on the object. For example, when an {{jsxref("ArrayBuffer")}} is transferred between threads, the memory resource that it points to is _literally_ moved between contexts in a fast and efficient zero-copy operation. Other objects may be transferred by copying the associated resource and then deleting it from the old context. Not all objects are transferable. A list of transferable objects is [provided below](#supported_objects). ## Transferring objects between threads The code below demonstrates how transferring works when sending a message from a main thread to a {{domxref("Web Workers API", "web worker thread","","true")}}. The {{jsxref("Uint8Array")}} is copied (duplicated) in the worker while its buffer is transferred. After transfer any attempt to read or write `uInt8Array` from the main thread will throw, but you can still check the `byteLength` to confirm it is now zero. ```js // Create an 8MB "file" and fill it. 8MB = 1024 * 1024 * 8 B const uInt8Array = new Uint8Array(1024 * 1024 * 8).map((v, i) => i); console.log(uInt8Array.byteLength); // 8388608 // Transfer the underlying buffer to a worker worker.postMessage(uInt8Array, [uInt8Array.buffer]); console.log(uInt8Array.byteLength); // 0 ``` > **Note:** [Typed arrays](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) like {{jsxref("Int32Array")}} and {{jsxref("Uint8Array")}}, are {{Glossary("serializable object","serializable")}}, but not transferable. > However their underlying buffer is an {{jsxref("ArrayBuffer")}}, which is a transferable object. > We could have sent `uInt8Array.buffer` in the data parameter, but not `uInt8Array` in the transfer array. ### Transferring during a cloning operation The code below shows a {{domxref("structuredClone()")}} operation where the underlying buffer is copied from the original object to the clone. ```js const original = new Uint8Array(1024); const clone = structuredClone(original); console.log(original.byteLength); // 1024 console.log(clone.byteLength); // 1024 original[0] = 1; console.log(clone[0]); // 0 // Transferring the Uint8Array would throw an exception as it is not a transferable object // const transferred = structuredClone(original, {transfer: [original]}); // We can transfer Uint8Array.buffer. const transferred = structuredClone(original, { transfer: [original.buffer] }); console.log(transferred.byteLength); // 1024 console.log(transferred[0]); // 1 // After transferring Uint8Array.buffer cannot be used. console.log(original.byteLength); // 0 ``` ## Supported objects The items that various specifications indicate can be _transferred_ are: - {{jsxref("ArrayBuffer")}} - {{domxref("MessagePort")}} - {{domxref("ReadableStream")}} - {{domxref("WritableStream")}} - {{domxref("TransformStream")}} - {{domxref("WebTransportReceiveStream")}} - {{domxref("WebTransportSendStream")}} - {{domxref("AudioData")}} - {{domxref("ImageBitmap")}} - {{domxref("VideoFrame")}} - {{domxref("OffscreenCanvas")}} - {{domxref("RTCDataChannel")}} Browser support should be indicated in the respective object's compatibility information by the `transferable` subfeature (see [`RTCDataChannel`](/en-US/docs/Web/API/RTCDataChannel#browser_compatibility) for an example). At time of writing, not all transferable objects have been updated with this information. > **Note:** Transferable objects are marked up in [Web IDL files](https://github.com/w3c/webref/tree/main/ed/idl) with the attribute `[Transferable]`. ## See also - [Transferable Objects: Lightning Fast!](https://developer.chrome.com/blog/transferable-objects-lightning-fast/) - [Using Web Workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) - [Transferable objects in the HTML specification](https://html.spec.whatwg.org/multipage/structured-data.html#transferable-objects) - {{domxref("DedicatedWorkerGlobalScope.postMessage()")}}
0
data/mdn-content/files/en-us/web/api/web_workers_api
data/mdn-content/files/en-us/web/api/web_workers_api/structured_clone_algorithm/index.md
--- title: The structured clone algorithm slug: Web/API/Web_Workers_API/Structured_clone_algorithm page-type: guide --- {{DefaultAPISidebar("Web Workers API") }} The **structured clone algorithm** copies complex JavaScript objects. It is used internally when invoking {{domxref("structuredClone()")}}, to transfer data between [Workers](/en-US/docs/Web/API/Worker) via {{domxref("Worker.postMessage()", "postMessage()")}}, storing objects with [IndexedDB](/en-US/docs/Glossary/IndexedDB), or copying objects for [other APIs](#see_also). It clones by recursing through the input object while maintaining a map of previously visited references, to avoid infinitely traversing cycles. ## Things that don't work with structured clone - {{jsxref("Function")}} objects cannot be duplicated by the structured clone algorithm; attempting to throws a `DataCloneError` exception. - Cloning DOM nodes likewise throws a `DataCloneError` exception. - Certain object properties are not preserved: - The `lastIndex` property of {{jsxref("RegExp")}} objects is not preserved. - Property descriptors, setters, getters, and similar metadata-like features are not duplicated. For example, if an object is marked readonly with a [property descriptor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor), it will be read/write in the duplicate, since that's the default. - The prototype chain is not walked or duplicated. ## Supported types ### JavaScript types - {{jsxref("Array")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("Boolean")}} - {{jsxref("DataView")}} - {{jsxref("Date")}} - {{jsxref("Error")}} types (but see [Error types](#error_types) below). - {{jsxref("Map")}} - {{jsxref("Number")}} - {{jsxref("Object")}} objects: but only plain objects (e.g. from object literals). - [Primitive types](/en-US/docs/Web/JavaScript/Data_structures#primitive_values), except `symbol`. - {{jsxref("RegExp")}}: but note that `lastIndex` is not preserved. - {{jsxref("Set")}} - {{jsxref("String")}} - {{jsxref("TypedArray")}} #### Error types For `Error` types, the error name must be one of: {{jsxref("Error")}}, {{JSxRef("EvalError")}}, {{JSxRef("RangeError")}}, {{JSxRef("ReferenceError")}}, {{JSxRef("SyntaxError")}}, {{JSxRef("TypeError")}}, {{JSxRef("URIError")}} (or will be set to "Error"). Browsers must serialize the properties `name` and `message`, and are expected to serialize other "interesting" properties of the errors such as `stack`, `cause`, etc. {{JSxRef("AggregateError")}} support is expected to be added to the specification in [whatwg/html#5749](https://github.com/whatwg/html/pull/5749) (and is already supported in some browsers). ### Web/API types - {{domxref("AudioData")}} - {{domxref("Blob")}} - {{domxref("CropTarget")}} - {{domxref("CryptoKey")}} - {{domxref("DOMException")}}: browsers must serialize the properties {{domxref("DOMException.name","name")}} and {{domxref("DOMException.message","message")}}. Other attributes may also be serialized/cloned. - {{domxref("DOMMatrix")}} - {{domxref("DOMMatrixReadOnly")}} - {{domxref("DOMPoint")}} - {{domxref("DOMPointReadOnly")}} - {{domxref("DOMQuad")}} - {{domxref("DOMRect")}} - {{domxref("DOMRectReadOnly")}} - {{domxref("File")}} - {{domxref("FileList")}} - {{domxref("FileSystemDirectoryHandle")}} - {{domxref("FileSystemFileHandle")}} - {{domxref("FileSystemHandle")}} - {{domxref("GPUCompilationInfo")}} - {{domxref("GPUCompilationMessage")}} - {{domxref("ImageBitmap")}} - {{domxref("ImageData")}} - {{domxref("RTCCertificate")}} - {{domxref("VideoFrame")}} ## See also - [HTML Specification: Safe passing of structured data](https://html.spec.whatwg.org/multipage/infrastructure.html#safe-passing-of-structured-data) - [Transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) - {{domxref("structuredClone()")}} - {{domxref("window.postMessage()")}} - [Web Workers](/en-US/docs/Web/API/Web_Workers_API) - [IndexedDB](/en-US/docs/Web/API/IndexedDB_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/encoding_api/index.md
--- title: Encoding API slug: Web/API/Encoding_API page-type: web-api-overview browser-compat: - api.TextDecoder - api.TextEncoder - api.TextEncoderStream - api.TextDecoderStream --- {{DefaultAPISidebar("Encoding API")}} The **Encoding API** provides a mechanism for handling text in various {{Glossary("character encoding", "character encodings")}}, including legacy non-{{Glossary("UTF-8")}} encodings. The API provides four interfaces: {{domxref("TextDecoder")}}, {{domxref("TextEncoder")}}, {{domxref("TextDecoderStream")}} and {{domxref("TextEncoderStream")}}. {{AvailableInWorkers}} ## Interfaces - {{DOMxRef("TextDecoder")}} - {{DOMxRef("TextEncoder")}} - {{DOMxRef("TextDecoderStream")}} - {{DOMxRef("TextEncoderStream")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Encoding API Encodings](/en-US/docs/Web/API/Encoding_API/Encodings) - Encodings that must be supported for decoding text. - A [polyfill](https://github.com/inexorabletash/text-encoding) allowing to use this interface in browsers that don't support it
0
data/mdn-content/files/en-us/web/api/encoding_api
data/mdn-content/files/en-us/web/api/encoding_api/encodings/index.md
--- title: Encoding API Encodings slug: Web/API/Encoding_API/Encodings page-type: guide --- {{DefaultAPISidebar("Encoding API")}} The constructors for the [Encoding API](/en-US/docs/Web/API/Encoding_API) interfaces {{domxref("TextDecoder")}} and {{domxref("TextDecoderStream")}} can be passed an optional `label`, representing the encoding to be used. The default is `UTF-8`. The following table lists all encoding names and labels that user agents must support, as defined in the Encoding Spec. These are generally applicable anywhere character encodings are used. <table class="no-markdown"> <thead> <tr> <th scope="col">Label</th> <th scope="col">Encoding</th> </tr> </thead> <tbody> <tr> <td> "<code>unicode-1-1-utf-8</code>", "<code>utf-8</code>", "<code>utf8</code>" </td> <td><code>'utf-8'</code></td> </tr> <tr> <td> "<code>866</code>", "<code>cp866</code>", "<code>csibm866</code>", "<code>ibm866</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Code_page_866">ibm866</a> </td> </tr> <tr> <td> "<code>csisolatin2</code>", "<code>iso-8859-2</code>", "<code>iso-ir-101</code>", "<code>iso8859-2</code>", "<code>iso88592</code>", "<code>iso_8859-2</code>", "<code>iso_8859-2:1987</code>", "<code>l2</code>", "<code>latin2</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-2">iso-8859-2</a> </td> </tr> <tr> <td> "<code>csisolatin3</code>", "<code>iso-8859-3</code>", "<code>iso-ir-109</code>", "<code>iso8859-3</code>", "<code>iso88593</code>", "<code>iso_8859-3</code>", "<code>iso_8859-3:1988</code>", "<code>l3</code>", "<code>latin3</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-3">iso-8859-3</a> </td> </tr> <tr> <td> "<code>csisolatin4</code>", "<code>iso-8859-4</code>", "<code>iso-ir-110</code>", "<code>iso8859-4</code>", "<code>iso88594</code>", "<code>iso_8859-4</code>", "<code>iso_8859-4:1988</code>", "<code>l4</code>", "<code>latin4</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-4">iso-8859-4</a> </td> </tr> <tr> <td> "<code>csisolatincyrillic</code>", "<code>cyrillic</code>", "<code>iso-8859-5</code>", "<code>iso-ir-144</code>", "<code>iso88595</code>", "<code>iso_8859-5</code>", "<code>iso_8859-5:1988</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-5">iso-8859-5</a> </td> </tr> <tr> <td> "<code>arabic</code>", "<code>asmo-708</code>", "<code>csiso88596e</code>", "<code>csiso88596i</code>", "<code>csisolatinarabic</code>", "<code>ecma-114</code>", "<code>iso-8859-6</code>", "<code>iso-8859-6-e</code>", "<code>iso-8859-6-i</code>", "<code>iso-ir-127</code>", "<code>iso8859-6</code>", "<code>iso88596</code>", "<code>iso_8859-6</code>", "<code>iso_8859-6:1987</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-6">iso-8859-6</a> </td> </tr> <tr> <td> "<code>csisolatingreek</code>", "<code>ecma-118</code>", "<code>elot_928</code>", "<code>greek</code>", "<code>greek8</code>", "<code>iso-8859-7</code>", "<code>iso-ir-126</code>", "<code>iso8859-7</code>", "<code>iso88597</code>", "<code>iso_8859-7</code>", "<code>iso_8859-7:1987</code>", "<code>sun_eu_greek</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-7">iso-8859-7</a> </td> </tr> <tr> <td> "<code>csiso88598e</code>", "<code>csisolatinhebrew</code>", "<code>hebrew</code>", "<code>iso-8859-8</code>", "<code>iso-8859-8-e</code>", "<code>iso-ir-138</code>", "<code>iso8859-8</code>", "<code>iso88598</code>", "<code>iso_8859-8</code>", "<code>iso_8859-8:1988</code>", "<code>visual</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-8">iso-8859-8</a> </td> </tr> <tr> <td> "<code>csiso88598i</code>", "<code>iso-8859-8-i</code>", "<code>logical</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO-8859-8-I">iso-8859-8i</a> </td> </tr> <tr> <td> "<code>csisolatin6</code>", "<code>iso-8859-10</code>", "<code>iso-ir-157</code>", "<code>iso8859-10</code>", "<code>iso885910</code>", "<code>l6</code>", "<code>latin6</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-10">iso-8859-10</a> </td> </tr> <tr> <td> "<code>iso-8859-13</code>", "<code>iso8859-13</code>", "<code>iso885913</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-13">iso-8859-13</a> </td> </tr> <tr> <td> "<code>iso-8859-14</code>", "<code>iso8859-14</code>", "<code>iso885914</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-14">iso-8859-14</a> </td> </tr> <tr> <td> "<code>csisolatin9</code>", "<code>iso-8859-15</code>", "<code>iso8859-15</code>", "<code>iso885915</code>", "<code>l9</code>", "<code>latin9</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-15">iso-8859-15</a> </td> </tr> <tr> <td>"<code>iso-8859-16</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-16">iso-8859-16</a> </td> </tr> <tr> <td> "<code>cskoi8r</code>", "<code>koi</code>", "<code>koi8</code>", "<code>koi8-r</code>", "<code>koi8_r</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/KOI8-R">koi8-r</a> </td> </tr> <tr> <td>"<code>koi8-u</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/KOI8-U">koi8-u</a> </td> </tr> <tr> <td> "<code>csmacintosh</code>", "<code>mac</code>", "<code>macintosh</code>", "<code>x-mac-roman</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Mac_OS_Roman">macintosh</a> </td> </tr> <tr> <td> "<code>dos-874</code>", "<code>iso-8859-11</code>", "<code>iso8859-11</code>", "<code>iso885911</code>", "<code>tis-620</code>", "<code>windows-874</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-874">windows-874</a> </td> </tr> <tr> <td> "<code>cp1250</code>", "<code>windows-1250</code>", "<code>x-cp1250</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1250">windows-1250</a> </td> </tr> <tr> <td> "<code>cp1251</code>", "<code>windows-1251</code>", "<code>x-cp1251</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1251">windows-1251</a> </td> </tr> <tr> <td> "<code>ansi_x3.4-1968</code>", "<code>ascii</code>", "<code>cp1252</code>", "<code>cp819</code>", "<code>csisolatin1</code>", "<code>ibm819</code>", "<code>iso-8859-1</code>", "<code>iso-ir-100</code>", "<code>iso8859-1</code>", "<code>iso88591</code>", "<code>iso_8859-1</code>", "<code>iso_8859-1:1987</code>", "<code>l1</code>", "<code>latin1</code>", "<code>us-ascii</code>", "<code>windows-1252</code>", "<code>x-cp1252</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1252">windows-1252</a> </td> </tr> <tr> <td> "<code>cp1253</code>", "<code>windows-1253</code>", "<code>x-cp1253</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1253">windows-1253</a> </td> </tr> <tr> <td> "<code>cp1254</code>", "<code>csisolatin5</code>", "<code>iso-8859-9</code>", "<code>iso-ir-148</code>", "<code>iso8859-9</code>", "<code>iso88599</code>", "<code>iso_8859-9</code>", "<code>iso_8859-9:1989</code>", "<code>l5</code>", "<code>latin5</code>", "<code>windows-1254</code>", "<code>x-cp1254</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1254">windows-1254</a> </td> </tr> <tr> <td> "<code>cp1255</code>", "<code>windows-1255</code>", "<code>x-cp1255</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1255">windows-1255</a> </td> </tr> <tr> <td> "<code>cp1256</code>", "<code>windows-1256</code>", "<code>x-cp1256</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1256">windows-1256</a> </td> </tr> <tr> <td> "<code>cp1257</code>", "<code>windows-1257</code>", "<code>x-cp1257</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1257">windows-1257</a> </td> </tr> <tr> <td> "<code>cp1258</code>", "<code>windows-1258</code>", "<code>x-cp1258</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Windows-1258">windows-1258</a> </td> </tr> <tr> <td>"<code>x-mac-cyrillic</code>", "<code>x-mac-ukrainian</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/Macintosh_Cyrillic_encoding">x-mac-cyrillic</a> </td> </tr> <tr> <td> "<code>chinese</code>", "<code>csgb2312</code>", "<code>csiso58gb231280</code>", "<code>gb2312</code>", "<code>gb_2312</code>", "<code>gb_2312-80</code>", "<code>gbk</code>", "<code>iso-ir-58</code>", "<code>x-gbk</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/GBK">gbk</a> </td> </tr> <tr> <td>"<code>gb18030</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/GB_18030">gb18030</a> </td> </tr> <tr> <td>"<code>hz-gb-2312</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/HZ_(character_encoding)">hz-gb-2312</a> </td> </tr> <tr> <td> "<code>big5</code>", "<code>big5-hkscs</code>", "<code>cn-big5</code>", "<code>csbig5</code>", "<code>x-x-big5</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Big5">big5</a> </td> </tr> <tr> <td> "<code>cseucpkdfmtjapanese</code>", "<code>euc-jp</code>", "<code>x-euc-jp</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-JP">euc-jp</a> </td> </tr> <tr> <td>"<code>csiso2022jp</code>", "<code>iso-2022-jp</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-JP">iso-2022-jp</a> </td> </tr> <tr> <td> "<code>csshiftjis</code>", "<code>ms_kanji</code>", "<code>shift-jis</code>", "<code>shift_jis</code>", "<code>sjis</code>", "<code>windows-31j</code>", "<code>x-sjis</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Shift_JIS">shift-jis</a> </td> </tr> <tr> <td> "<code>cseuckr</code>", "<code>csksc56011987</code>", "<code>euc-kr</code>", "<code>iso-ir-149</code>", "<code>korean</code>", "<code>ks_c_5601-1987</code>", "<code>ks_c_5601-1989</code>", "<code>ksc5601</code>", "<code>ksc_5601</code>", "<code>windows-949</code>" </td> <td> <a href="https://en.wikipedia.org/wiki/Extended_Unix_Code#EUC-KR">euc-kr</a> </td> </tr> <tr> <td>"<code>csiso2022kr</code>", "<code>iso-2022-kr</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/ISO/IEC_2022#ISO-2022-KR">iso-2022-kr</a> </td> </tr> <tr> <td>"<code>utf-16be</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes">utf-16be</a> </td> </tr> <tr> <td>"<code>utf-16</code>", "<code>utf-16le</code>"</td> <td> <a href="https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes">utf-16le</a> </td> </tr> <tr> <td>"<code>x-user-defined</code>"</td> <td><code>'x-user-defined'</code></td> </tr> <tr> <td>"<code>iso-2022-cn</code>", "<code>iso-2022-cn-ext</code>"</td> <td><code>'replacement'</code></td> </tr> </tbody> </table>
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/presentationconnectionavailableevent/index.md
--- title: PresentationConnectionAvailableEvent slug: Web/API/PresentationConnectionAvailableEvent page-type: web-api-interface status: - experimental browser-compat: api.PresentationConnectionAvailableEvent --- {{SeeCompatTable}}{{securecontext_header}}{{APIRef("Presentation API")}} The **`PresentationConnectionAvailableEvent`** interface of the [Presentation API](/en-US/docs/Web/API/Presentation_API) is fired on a {{domxref("PresentationRequest")}} when a connection associated with the object is created. A [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent) [fires](https://www.w3.org/TR/presentation-api/#dfn-firing-an-event) a [trusted event](https://www.w3.org/TR/presentation-api/#dfn-trusted-event) named [`connectionavailable`](https://www.w3.org/TR/presentation-api/#dfn-connectionavailable) on a [`PresentationRequest`](https://www.w3.org/TR/presentation-api/#idl-def-presentationrequest) when a connection associated with the object is created. It is fired at the `PresentationRequest` instance, using the [`PresentationConnectionAvailableEvent`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnectionavailableevent) interface, with the [`connection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnectionavailableevent-connection) attribute set to the [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection) object that was created. The event is fired for each connection that is created for the [controller](https://www.w3.org/TR/presentation-api/#dfn-controller), either by the [controller](https://www.w3.org/TR/presentation-api/#dfn-controller) calling `start()` or `reconnect()`, or by the [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent) creating a connection on the controller's behalf via [`defaultRequest`](https://www.w3.org/TR/presentation-api/#dom-presentation-defaultrequest). {{InheritanceDiagram}} ## Constructor - {{domxref("PresentationConnectionAvailableEvent.PresentationConnectionAvailableEvent", "PresentationConnectionAvailableEvent()")}} {{Experimental_Inline}} - : Creates a new PresentationConnectionAvailableEvent. ## Instance properties - {{domxref("PresentationConnectionAvailableEvent.connection")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a references to the {{domxref("PresentationConnection")}} object that fired the event. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/presentationconnectionavailableevent
data/mdn-content/files/en-us/web/api/presentationconnectionavailableevent/presentationconnectionavailableevent/index.md
--- title: "PresentationConnectionAvailableEvent: PresentationConnectionAvailableEvent() constructor" short-title: PresentationConnectionAvailableEvent() slug: Web/API/PresentationConnectionAvailableEvent/PresentationConnectionAvailableEvent page-type: web-api-constructor status: - experimental browser-compat: api.PresentationConnectionAvailableEvent.PresentationConnectionAvailableEvent --- {{APIRef("Presentation API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`PresentationConnectionAvailableEvent()`** constructor creates a new {{domxref("PresentationConnectionAvailableEvent")}} object. ## Syntax ```js-nolint new PresentationConnectionAvailableInit(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers set it to `connectionavailable`. - `options` - : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties: - `connection` - : The association {{domxref("PresentationConnection")}} object. ### Return value A new {{domxref("PresentationConnectionAvailableEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/presentationconnectionavailableevent
data/mdn-content/files/en-us/web/api/presentationconnectionavailableevent/connection/index.md
--- title: "PresentationConnectionAvailableEvent: connection property" short-title: connection slug: Web/API/PresentationConnectionAvailableEvent/connection page-type: web-api-instance-property status: - experimental browser-compat: api.PresentationConnectionAvailableEvent.connection --- {{APIRef("Presentation API")}}{{SeeCompatTable}}{{SecureContext_Header}} When an incoming connection is created, a [receiving user agent](https://www.w3.org/TR/presentation-api/#dfn-receiving-user-agent) [fires](https://www.w3.org/TR/presentation-api/#dfn-firing-an-event) a [trusted event](https://www.w3.org/TR/presentation-api/#dfn-trusted-event), named [`connectionavailable`](https://www.w3.org/TR/presentation-api/#dfn-connectionavailable), on a [`PresentationReceiver`](https://www.w3.org/TR/presentation-api/#idl-def-presentationreceiver). The [trusted event](https://www.w3.org/TR/presentation-api/#dfn-trusted-event) is fired at the [presentation controller's monitor](https://www.w3.org/TR/presentation-api/#dfn-presentation-controllers-monitor), using the [`PresentationConnectionAvailableEvent`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnectionavailableevent) interface, with the [`connection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnectionavailableevent-connection) attribute set to the [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection) object that was created. The event is fired for all connections that are created when [monitoring incoming presentation connections](https://www.w3.org/TR/presentation-api/#dfn-monitoring-incoming-presentation-connections). ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/history_api/index.md
--- title: History API slug: Web/API/History_API page-type: web-api-overview browser-compat: api.History --- {{DefaultAPISidebar("History API")}} The **History API** provides access to the browser's session history (not to be confused with [WebExtensions history](/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history)) through the {{DOMxRef("Window.history","history")}} global object. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack. > **Note:** This API is only available on the main thread ({{domxref("Window")}}). It cannot be accessed in {{domxref("Worker")}} or {{domxref("Worklet")}} contexts. ## Concepts and usage Moving backward and forward through the user's history is done using the {{DOMxRef("History.back","back()")}}, {{DOMxRef("History.forward","forward()")}}, and {{DOMxRef("History.go","go()")}} methods. ### Moving forward and backward To move backward through history: ```js history.back(); ``` This acts exactly as if the user clicked on the <kbd><strong>Back</strong></kbd> button in their browser toolbar. Similarly, you can move forward (as if the user clicked the <kbd><strong>Forward</strong></kbd> button), like this: ```js history.forward(); ``` ### Moving to a specific point in history You can use the {{DOMxRef("History.go","go()")}} method to load a specific page from session history, identified by its relative position to the current page. (The current page's relative position is `0`.) To move back one page (the equivalent of calling {{DOMxRef("History.back","back()")}}): ```js history.go(-1); ``` To move forward a page, just like calling {{DOMxRef("History.forward","forward()")}}: ```js history.go(1); ``` Similarly, you can move forward 2 pages by passing `2`, and so forth. Another use for the `go()` method is to refresh the current page by either passing `0`, or by invoking it without an argument: ```js // The following statements // both have the effect of // refreshing the page history.go(0); history.go(); ``` You can determine the number of pages in the history stack by looking at the value of the `length` property: ```js const numberOfEntries = history.length; ``` ## Interfaces - {{domxref("History")}} - : Allows manipulation of the browser _session history_ (that is, the pages visited in the tab or frame that the current page is loaded in). - {{domxref("PopStateEvent")}} - : The interface of the {{domxref("Window.popstate_event", "popstate")}} event. ## Examples The following example assigns a listener for the {{domxref("Window.popstate_event", "popstate")}} event. It then illustrates some of the methods of the history object to add, replace, and move within the browser history for the current tab. ```js window.addEventListener("popstate", (event) => { alert( `location: ${document.location}, state: ${JSON.stringify(event.state)}`, ); }); history.pushState({ page: 1 }, "title 1", "?page=1"); history.pushState({ page: 2 }, "title 2", "?page=2"); history.replaceState({ page: 3 }, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null" history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3}" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.history", "history")}} global object - {{domxref("Window/popstate_event", "popstate")}} event
0
data/mdn-content/files/en-us/web/api/history_api
data/mdn-content/files/en-us/web/api/history_api/working_with_the_history_api/index.md
--- title: Working with the History API slug: Web/API/History_API/Working_with_the_History_API page-type: guide --- {{DefaultAPISidebar("History API")}} The History API enables a website to interact with the browser's session history: that is, the list of pages that the user has visited in a given window. As the user visits new pages, for example by clicking links, those new pages are added to the session history. The user can also move back and forth through the history using the browser's "Back" and "Forward" buttons. The main interface defined in the History API is the {{domxref("History")}} interface, and this defines two quite distinct sets of methods: 1. Methods to navigate to a page in the session history: - {{domxref("History.back()")}} - {{domxref("History.forward()")}} - {{domxref("History.go()")}} 2. Methods to modify the session history: - {{domxref("History.pushState()")}} - {{domxref("History.replaceState()")}} In this guide we'll be concerned only with the second set of methods, as these have more complex behavior. The `pushState()` method adds a new entry to the session history, while the `replaceState()` method updates the session history entry for the current page. Both these methods take a `state` parameter which can contain any {{Glossary("Serializable_object", "serializable object")}} . When the browser navigates to this history entry, the browser fires a {{domxref("Window.popstate_event", "popstate")}} event, which contains the state object associated with that entry. The main purpose of these APIs is to support websites like {{Glossary("SPA", "Single-page applications")}}, that use JavaScript APIs such as {{domxref("fetch()")}} to update the page with new content, instead of loading a whole new page. ## Single-page applications and session history Traditionally, websites are implemented as a collection of pages. When users navigate to different parts of the site by clicking links, the browser loads a whole new page each time. While this is great for many sites, it can have some disadvantages: - It can be inefficient to load a whole page every time, when only part of the page needs to be updated. - It is hard to maintain application state when navigating across pages For these reasons, a popular pattern for web apps is the {{Glossary("SPA", "single-page application")}} (SPA), in which the site consists of a single page, and when the user clicks links, the page: 1. Prevents the default behavior of loading a new page 2. {{domxref("fetch()", "Fetches", "", "nocode")}} new content to display 3. Updates the page with the new content For example: ```js document.addEventListener("click", async (event) => { const creature = event.target.getAttribute("data-creature"); if (creature) { // Prevent a new page from loading event.preventDefault(); try { // Fetch new content const response = await fetch(`creatures/${creature}.json`); const json = await response.json(); // Update the page with the new content displayContent(json); } catch (err) { console.error(err); } } }); ``` In this click handler, if the link contains a data attribute `"data-creature"`, then we use the value of that attribute to fetch a JSON file containing the new content for the page. The JSON file might look like this: ```json { "description": "Bald eagles are not actually bald.", "image": { "src": "images/eagle.jpg", "alt": "A bald eagle" }, "name": "Eagle" } ``` Our `displayContent()` function updates the page with the JSON: ```js // Update the page with the new content function displayContent(content) { document.title = `Creatures: ${content.name}`; const description = document.querySelector("#description"); description.textContent = content.description; const photo = document.querySelector("#photo"); photo.setAttribute("src", content.image.src); photo.setAttribute("alt", content.image.alt); } ``` The problem is that it breaks the expected behavior of the browser's "Back" and "Forward" buttons. From the user's point of view, they clicked a link and the page updated, so it looks like a new page. If they then press the browser's "Back" button, they expect to go to the state before they clicked the link. But as far as the browser is concerned, the last link didn't load a new page, so "Back" will take the browser to whichever page was loaded before the user opened the SPA. This is essentially the problem that `pushState()`, `replaceState()`, and the `popstate` event solve. They enable us to synthesize history entries, and to be notified when the current session history entry changes to one of these entries (for example, because the user pressed the "Back" or "Forward" buttons). ## Using `pushState()` We can add a history entry to the click handler above as follows: ```js document.addEventListener("click", async (event) => { const creature = event.target.getAttribute("data-creature"); if (creature) { event.preventDefault(); try { const response = await fetch(`creatures/${creature}.json`); const json = await response.json(); displayContent(json); // Add a new entry to the history. // This simulates loading a new page. history.pushState(json, "", creature); } catch (err) { console.error(err); } } }); ``` Here, we're calling `pushState()` with three arguments: - `json`: this is the content we just fetched. It will be stored with the history entry, and later included as the {{domxref("PopStateEvent.state", "state")}} property of the argument passed to the `popstate` event handler. - `""`: this is needed for backward compatibility with legacy sites, and should always be an empty string - `creature`: this will be used as the URL for the entry. It will be shown in the browser's URL bar, and will be used as the value of the {{httpheader("Referer")}} header in any HTTP requests that the page makes. Note that this must be {{Glossary("Same-origin policy", "same-origin")}} with the page. ## Using the `popstate` event Suppose the user: 1. Clicks a link in our SPA, so we update the page and add history entry A using `pushState()` 2. Clicks another link in our SPA, so we update the page and add history entry B using `pushState()` 3. Presses the "Back" button Now the new current history entry is A, so the browser fires the `popstate` event, and the event handler argument includes the JSON that we passed to `pushState()` when we handled the navigation to A. This means we can restore the correct content with an event handler like this: ```js // Handle forward/back buttons window.addEventListener("popstate", (event) => { // If a state has been provided, we have a "simulated" page // and we update the current page. if (event.state) { // Simulate the loading of the previous page displayContent(event.state); } }); ``` ## Using `replaceState()` There's one more piece we need to add. When the user loads the SPA, the browser adds a history entry. Because this was an actual page load, the entry has no state associated with it. So suppose the user: 1. Loads the SPA: the browser adds a history entry 2. Clicks a link inside the SPA: the click handler updates the page and adds a history entry with `pushState()` 3. Presses the "Back" button Now we want to go back to the SPA's initial state, but since this is a navigation in the same document, the page will not be reloaded, and since the history entry for the initial page has no state, we can't use `popstate` to restore it. The solution here is to use `replaceState()` to set the state object for the initial page. For example: ```js // Create state on page load and replace the current history with it const image = document.querySelector("#photo"); const initialState = { description: document.querySelector("#description").textContent, image: { src: image.getAttribute("src"), alt: image.getAttribute("alt"), }, name: "Home", }; history.replaceState(initialState, "", document.location.href); ``` On page load, we collect all the parts of the page that we need to restore when the user returns to the starting point for the SPA. This has the same structure as the JSON we fetch when handling other navigations. We pass this `initialState` object into `replaceState()`, which effectively adds the state object to the current history entry. When the user returns to our starting point, the `popstate` event will contain this initial state, and we can use our `displayContent()` function to update the page. ## A complete example You can find this complete example at <https://github.com/mdn/dom-examples/tree/main/history-api>, and see the demo live at <https://mdn.github.io/dom-examples/history-api/>. ## See also - [History API](/en-US/docs/Web/API/History_API) - {{domxref("window.history", "history")}} global object
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/authenticatorassertionresponse/index.md
--- title: AuthenticatorAssertionResponse slug: Web/API/AuthenticatorAssertionResponse page-type: web-api-interface browser-compat: api.AuthenticatorAssertionResponse --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`AuthenticatorAssertionResponse`** interface of the [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API) contains a [digital signature](/en-US/docs/Glossary/Signature/Security) from the private key of a particular WebAuthn credential. The relying party's server can verify this signature to authenticate a user, for example when they sign in. An `AuthenticatorAssertionResponse` object instance is available in the {{domxref("PublicKeyCredential.response", "response")}} property of a {{domxref("PublicKeyCredential")}} object returned by a successful {{domxref("CredentialsContainer.get()", "navigator.credentials.get()")}} call. This interface inherits from {{domxref("AuthenticatorResponse")}}. {{InheritanceDiagram}} > **Note:** This interface is restricted to top-level contexts. Use from within an {{HTMLElement("iframe")}} element will not have any effect. ## Instance properties _Also inherits properties from its parent, {{domxref("AuthenticatorResponse")}}._ - {{domxref("AuthenticatorAssertionResponse.authenticatorData")}} {{ReadOnlyInline}} - : An {{jsxref("ArrayBuffer")}} containing information from the authenticator such as the Relying Party ID Hash (rpIdHash), a signature counter, test of user presence and user verification flags, and any extensions processed by the authenticator. - {{domxref("AuthenticatorResponse.clientDataJSON")}} {{ReadOnlyInline}} - : Contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to authenticate with this credential β€” i.e., when {{domxref("CredentialsContainer.get()")}} is called with a `publicKey` option. This data contains some information from the options passed into the `get()` call, and some information controlled by the browser. - {{domxref("AuthenticatorAssertionResponse.signature")}} {{ReadOnlyInline}} - : An assertion signature over {{domxref("AuthenticatorAssertionResponse.authenticatorData")}} and {{domxref("AuthenticatorResponse.clientDataJSON")}}. The assertion signature is created with the private key of the key pair that was created during the originating {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} call and verified using the public key of that same key pair. - {{domxref("AuthenticatorAssertionResponse.userHandle")}} {{ReadOnlyInline}} - : An {{jsxref("ArrayBuffer")}} containing an opaque user identifier, specified as `user.id` in the options passed to the originating {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} call. ## Instance methods None. ## Examples See [User login using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/get#user_login_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("AuthenticatorAttestationResponse")}}: the interface for the type of response given when creating a new credential - {{domxref("AuthenticatorResponse")}}: the parent interface
0
data/mdn-content/files/en-us/web/api/authenticatorassertionresponse
data/mdn-content/files/en-us/web/api/authenticatorassertionresponse/userhandle/index.md
--- title: "AuthenticatorAssertionResponse: userHandle property" short-title: userHandle slug: Web/API/AuthenticatorAssertionResponse/userHandle page-type: web-api-instance-property browser-compat: api.AuthenticatorAssertionResponse.userHandle --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`userHandle`** read-only property of the {{domxref("AuthenticatorAssertionResponse")}} interface is an {{jsxref("ArrayBuffer")}} object providing an opaque identifier for the given user. Such an identifier can be used by the relying party's server to link the user account with its corresponding credentials and other data. This value is specified as `user.id` in the options passed to the originating {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} call. ## Value An {{jsxref("ArrayBuffer")}} object representing an identifier for the current user. This is not intended to be human-readable. The relying party should make sure that the `user.id` passed into the originating `create()` call does **not** contain any personally identifying information (for example user name, email, or phone number). For {{domxref("CredentialsContainer.create()","navigator.credentials.create()")}} calls made with a non-empty `allowCredentials` properties, the returned `userHandle` may be null. ## Examples See [User login using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/get#user_login_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("CredentialsContainer.create()")}} that sets the value of this property
0
data/mdn-content/files/en-us/web/api/authenticatorassertionresponse
data/mdn-content/files/en-us/web/api/authenticatorassertionresponse/authenticatordata/index.md
--- title: "AuthenticatorAssertionResponse: authenticatorData property" short-title: authenticatorData slug: Web/API/AuthenticatorAssertionResponse/authenticatorData page-type: web-api-instance-property browser-compat: api.AuthenticatorAssertionResponse.authenticatorData --- {{securecontext_header}}{{APIRef("Web Authentication API")}} The **`authenticatorData`** property of the {{domxref("AuthenticatorAssertionResponse")}} interface returns an {{jsxref("ArrayBuffer")}} containing information from the authenticator such as the Relying Party ID Hash (rpIdHash), a signature counter, test of user presence, user verification flags, and any extensions processed by the authenticator. ## Value An {{jsxref("ArrayBuffer")}} with a {{jsxref("ArrayBuffer.byteLength")}} of at least 37 bytes, which contains the data structure explained in [Authenticator data](/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data). ## Examples See [User login using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/get#user_login_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/authenticatorassertionresponse
data/mdn-content/files/en-us/web/api/authenticatorassertionresponse/signature/index.md
--- title: "AuthenticatorAssertionResponse: signature property" short-title: signature slug: Web/API/AuthenticatorAssertionResponse/signature page-type: web-api-instance-property browser-compat: api.AuthenticatorAssertionResponse.signature --- {{APIRef("Web Authentication API")}}{{securecontext_header}} The **`signature`** read-only property of the {{domxref("AuthenticatorAssertionResponse")}} interface is an {{jsxref("ArrayBuffer")}} object which is the signature of the authenticator for both {{domxref("AuthenticatorAssertionResponse.authenticatorData")}} and a SHA-256 hash of the client data ({{domxref("AuthenticatorResponse.clientDataJSON","AuthenticatorAssertionResponse.clientDataJSON")}}). This signature will be sent to the server for control, as part of the response. It provides the proof that an authenticator does possess the private key which was used for the credential's generation. ## Value An {{jsxref("ArrayBuffer")}} object which the signature of the authenticator (using its private key) for both {{domxref("AuthenticatorAssertionResponse.authenticatorData")}} and a SHA-256 hash given by the client for its data (the challenge, the origin, etc. and available from {{domxref("AuthenticatorResponse.clientDataJSON","AuthenticatorAssertionResponse.clientDataJSON")}}). ## Examples See [User login using the WebAuthn API](/en-US/docs/Web/API/CredentialsContainer/get#user_login_using_the_webauthn_api) for a detailed example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgmpathelement/index.md
--- title: SVGMPathElement slug: Web/API/SVGMPathElement page-type: web-api-interface browser-compat: api.SVGMPathElement --- {{APIRef("SVG")}} The **`SVGMPathElement`** interface corresponds to the {{SVGElement("mpath")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGMPathElement.href")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} that corresponds to the {{SVGAttr("href")}} or {{SVGAttr("xlink:href")}} {{deprecated_inline}} attribute of the given {{SVGElement("mpath")}} element. ## Instance methods _This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/keyboardlayoutmap/index.md
--- title: KeyboardLayoutMap slug: Web/API/KeyboardLayoutMap page-type: web-api-interface status: - experimental browser-compat: api.KeyboardLayoutMap --- {{SeeCompatTable}}{{APIRef("Keyboard API")}} The **`KeyboardLayoutMap`** interface of the {{domxref("Keyboard API", "", "", "nocode")}} is a read-only object with functions for retrieving the string associated with specific physical keys. A `KeyboardLayoutMap` instance is a read-only [`Map`-like object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#map-like_browser_apis), in which each key is a string identifying the unique physical key on the keyboard (a "key code"), and the corresponding value is the associated key attribute value (which may be affected by the keyboard layout, and so on). A list of valid keys is found in the [UI Events KeyboardEvent code Values](https://www.w3.org/TR/uievents-code/#key-alphanumeric-writing-system) specification. ## Instance properties - {{domxref('KeyboardLayoutMap.size')}} {{ReadOnlyInline}} {{experimental_inline}} - : Returns the number of elements in the `KeyboardLayoutMap` object. ## Instance methods - `KeyboardLayoutMap.[@@iterator]()` {{experimental_inline}} - : Returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the key/value pairs. - {{domxref('KeyboardLayoutMap.entries()')}} {{experimental_inline}} - : Returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the key/value pairs. - {{domxref('KeyboardLayoutMap.forEach()')}} {{experimental_inline}} - : Executes a provided function once for each element of `KeyboardLayoutMap`. - {{domxref('KeyboardLayoutMap.get()')}} {{experimental_inline}} - : Returns the element with the given key from the `KeyboardLayoutMap` object. - {{domxref('KeyboardLayoutMap.has()')}} {{experimental_inline}} - : Returns a boolean indicating whether the `KeyboardLayoutMap` object has an element with the specified key. - {{domxref('KeyboardLayoutMap.keys()')}} {{experimental_inline}} - : Returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the keys for each index in the `KeyboardLayoutMap` object. - {{domxref('KeyboardLayoutMap.values()')}} {{experimental_inline}} - : Returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the values for each index in the `KeyboardLayoutMap` object. ## Examples The following example demonstrates how to get the location- or layout-specific string associated with the keyboard code that corresponds to the 'W' key on an English QWERTY keyboard. ```js navigator.keyboard.getLayoutMap().then((keyboardLayoutMap) => { const upKey = keyboardLayoutMap.get("KeyW"); window.alert(`Press ${upKey} to move up.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/keyboardlayoutmap
data/mdn-content/files/en-us/web/api/keyboardlayoutmap/get/index.md
--- title: "KeyboardLayoutMap: get() method" short-title: get() slug: Web/API/KeyboardLayoutMap/get page-type: web-api-instance-method status: - experimental browser-compat: api.KeyboardLayoutMap.get spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.get --- {{APIRef("Keyboard API")}}{{SeeCompatTable}} The **`get()`** method of the {{domxref('KeyboardLayoutMap')}} interface returns the element with the given key. A list of valid keys is found in the [UI Events KeyboardEvent code Values](https://www.w3.org/TR/uievents-code/#key-alphanumeric-writing-system) spec. The method is otherwise the same as {{jsxref("Map.prototype.get()")}}. ## Syntax ```js-nolint get(key) ``` ### Parameters - `key` - : The key of the item to return from the map. ### Return value The value of the specified key. ## Examples The following example demonstrates how to get the location- or layout-specific string associated with the keyboard code that corresponds to the 'W' key on an English QWERTY keyboard. ```js navigator.keyboard.getLayoutMap().then((keyboardLayoutMap) => { const upKey = keyboardLayoutMap.get("KeyW"); window.alert(`Press ${upKey} to move up.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Map.prototype.get()")}}
0
data/mdn-content/files/en-us/web/api/keyboardlayoutmap
data/mdn-content/files/en-us/web/api/keyboardlayoutmap/has/index.md
--- title: "KeyboardLayoutMap: has() method" short-title: has() slug: Web/API/KeyboardLayoutMap/has page-type: web-api-instance-method status: - experimental browser-compat: api.KeyboardLayoutMap.has spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.has --- {{APIRef("Keyboard API")}}{{SeeCompatTable}} The **`has()`** method of the {{domxref('KeyboardLayoutMap')}} interface returns a boolean indicating whether the object has an element with the specified key. A list of valid keys is found in the [UI Events KeyboardEvent code Values](https://www.w3.org/TR/uievents-code/#key-alphanumeric-writing-system) spec. The method is otherwise the same as {{jsxref("Map.prototype.has()")}}. ## Syntax ```js-nolint has(key) ``` ### Parameters - `key` - : The key of an element to search for in the map. ### Return value A {{jsxref('Boolean')}} indicating whether the specified key was found. ## Examples The following example checks whether the location- or layout-specific string associated with the keyboard code that corresponds to the 'W' key on an English QWERTY keyboard exists. ```js navigator.keyboard.getLayoutMap().then((keyboardLayoutMap) => { console.log(keyboardLayoutMap.has("KeyW")); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Map.prototype.has()")}}
0
data/mdn-content/files/en-us/web/api/keyboardlayoutmap
data/mdn-content/files/en-us/web/api/keyboardlayoutmap/keys/index.md
--- title: "KeyboardLayoutMap: keys() method" short-title: keys() slug: Web/API/KeyboardLayoutMap/keys page-type: web-api-instance-method status: - experimental browser-compat: api.KeyboardLayoutMap.keys spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.keys --- {{SeeCompatTable}}{{APIRef("Keyboard API")}} The **`keys()`** method of the {{domxref("KeyboardLayoutMap")}} interface returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the keys for each index in the `KeyboardLayoutMap` object. The method is otherwise the same as {{jsxref("Map.prototype.keys()")}}. ## Value A new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object. ## Examples The following example iterates every keyboard code on an English QWERTY keyboard. ```js navigator.keyboard.getLayoutMap().then((keyboardLayoutMap) => { for (const code of keyboardLayoutMap.keys()) { console.log(`${code} keyboard code`); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Map.prototype.keys()")}}
0
data/mdn-content/files/en-us/web/api/keyboardlayoutmap
data/mdn-content/files/en-us/web/api/keyboardlayoutmap/size/index.md
--- title: "KeyboardLayoutMap: size property" short-title: size slug: Web/API/KeyboardLayoutMap/size page-type: web-api-instance-property status: - experimental browser-compat: api.KeyboardLayoutMap.size spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-get-map.prototype.size --- {{SeeCompatTable}}{{APIRef("Keyboard API")}} The **`size`** read-only property of the {{domxref("KeyboardLayoutMap")}} interface returns the number of elements in the map. The property is otherwise the same as {{jsxref("Map.prototype.size")}}. ## Value A number. ## Examples The following example get the count of the location- or layout-specific string and its associated keyboard code on an English QWERTY keyboard. ```js navigator.keyboard.getLayoutMap().then((keyboardLayoutMap) => { console.log(keyboardLayoutMap.size); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Map.prototype.size")}}
0
data/mdn-content/files/en-us/web/api/keyboardlayoutmap
data/mdn-content/files/en-us/web/api/keyboardlayoutmap/values/index.md
--- title: "KeyboardLayoutMap: values() method" short-title: values() slug: Web/API/KeyboardLayoutMap/values page-type: web-api-instance-method status: - experimental browser-compat: api.KeyboardLayoutMap.values spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.values --- {{SeeCompatTable}}{{APIRef("Keyboard API")}} The **`values()`** method of the {{domxref("KeyboardLayoutMap")}} interface returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the values for each index in the `KeyboardLayoutMap` object. The method is otherwise the same as {{jsxref("Map.prototype.values()")}}. ## Value A new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object. ## Examples The following example iterates every location- or layout-specific string on an English QWERTY keyboard. ```js navigator.keyboard.getLayoutMap().then((keyboardLayoutMap) => { for (const key of keyboardLayoutMap.values()) { console.log(`${key} key`); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Map.prototype.values()")}}
0
data/mdn-content/files/en-us/web/api/keyboardlayoutmap
data/mdn-content/files/en-us/web/api/keyboardlayoutmap/foreach/index.md
--- title: "KeyboardLayoutMap: forEach() method" short-title: forEach() slug: Web/API/KeyboardLayoutMap/forEach page-type: web-api-instance-method status: - experimental browser-compat: api.KeyboardLayoutMap.forEach spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.foreach --- {{APIRef("Keyboard API")}}{{SeeCompatTable}} The **`forEach()`** method of the {{domxref('KeyboardLayoutMap')}} interface executes a provided function once for each element of the map. The method is otherwise the same as {{jsxref("Map.prototype.forEach()")}}. ## Syntax ```js-nolint forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : The function to execute for each element, taking three arguments: - `currentValue` - : The value of the current element being processed. - `index` {{optional_inline}} - : The index of the current element being processed. - `array` {{optional_inline}} - : The KeyboardLayoutMap that `forEach()` is being called on. - `thisArg` {{Optional_inline}} - : Value to use as **`this`** (i.e., the reference `Object`) when executing `callback`. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example iterates every location- or layout-specific string and its associated keyboard code on an English QWERTY keyboard. ```js navigator.keyboard.getLayoutMap().then((keyboardLayoutMap) => { keyboardLayoutMap.forEach((key, code) => { console.log(`${code} keyboard code represents ${key} key`); }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Map.prototype.forEach()")}}
0
data/mdn-content/files/en-us/web/api/keyboardlayoutmap
data/mdn-content/files/en-us/web/api/keyboardlayoutmap/entries/index.md
--- title: "KeyboardLayoutMap: entries() method" short-title: entries() slug: Web/API/KeyboardLayoutMap/entries page-type: web-api-instance-method status: - experimental browser-compat: api.KeyboardLayoutMap.entries spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.entries --- {{SeeCompatTable}}{{APIRef("Keyboard API")}} The **`entries()`** method of the {{domxref("KeyboardLayoutMap")}} interface returns a new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object that contains the key/value pairs, in the same order as that provided by a {{jsxref("Statements/for...in", "for...in")}} loop (the difference being that a `for-in` loop enumerates properties in the prototype chain as well). The method is otherwise the same as {{jsxref("Map.prototype.entries()")}}. ## Value A new [Iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) object. ## Examples The following example iterates every location- or layout-specific string and its associated keyboard code on an English QWERTY keyboard. ```js navigator.keyboard.getLayoutMap().then((keyboardLayoutMap) => { for (const [code, key] of keyboardLayoutMap.entries()) { console.log(`${code} keyboard code represents ${key} key`); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Map.prototype.entries()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/stylepropertymap/index.md
--- title: StylePropertyMap slug: Web/API/StylePropertyMap page-type: web-api-interface browser-compat: api.StylePropertyMap --- {{APIRef("CSS Typed Object Model API")}} The **`StylePropertyMap`** interface of the [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Object_Model#css_typed_object_model_experimental) provides a representation of a CSS declaration block that is an alternative to {{DOMxRef("CSSStyleDeclaration")}}. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{DOMxRef("StylePropertyMapReadOnly")}}._ ## Instance methods _Inherits methods from its parent, {{DOMxRef("StylePropertyMapReadOnly")}}._ - {{DOMxRef("StylePropertyMap.append()")}} - : Adds a new CSS declaration to the `StylePropertyMap` with the given property and value. - {{DOMxRef("StylePropertyMap.clear()")}} - : Removes all declarations in the `StylePropertyMap`. - {{DOMxRef("StylePropertyMap.delete()")}} - : Removes the CSS declaration with the given property. - {{DOMxRef("StylePropertyMap.set()")}} - : Changes the CSS declaration with the given property. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/stylepropertymap
data/mdn-content/files/en-us/web/api/stylepropertymap/set/index.md
--- title: "StylePropertyMap: set() method" short-title: set() slug: Web/API/StylePropertyMap/set page-type: web-api-instance-method browser-compat: api.StylePropertyMap.set --- {{APIRef("CSS Typed Object Model API")}} The **`set()`** method of the {{domxref("StylePropertyMap")}} interface changes the CSS declaration with the given property. ## Syntax ```js-nolint set(property, value) ``` ### Parameters - `property` - : An identifier indicating the stylistic feature (e.g. font, width, background color) to change. - `value` - : The value the given property should have. ### Return value None ({{jsxref("undefined")}}). ## Examples This example sets the {{cssxref('padding-top')}} property, with the given value, within the element's [style attribute](/en-US/docs/Web/HTML/Global_attributes/style). ```js // get the button element const buttonEl = document.querySelector("button"); // set padding-top on button style attribute buttonEl.attributeStyleMap.set("padding-top", CSS.px(10)); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/stylepropertymap
data/mdn-content/files/en-us/web/api/stylepropertymap/append/index.md
--- title: "StylePropertyMap: append() method" short-title: append() slug: Web/API/StylePropertyMap/append page-type: web-api-instance-method browser-compat: api.StylePropertyMap.append --- {{APIRef("CSS Typed Object Model API")}} The **`append()`** method of the {{domxref("StylePropertyMap")}} interface adds the passed CSS value to the `StylePropertyMap` with the given property. ## Syntax ```js-nolint append(property, value) ``` ### Parameters - `property` - : An identifier indicating the stylistic feature (e.g. font, width, background color) to add. - `value` - : The value the given property should have. ### Return value None ({{jsxref("undefined")}}). ## Examples This example shows an extra background image value being added to the {{cssxref('background-image')}} property of the element, using {{domxref('HTMLElement.attributeStyleMap')}}. ```js // get the button element const buttonEl = document.querySelector("button"); // append another value to the background-image property set on the attribute buttonEl.attributeStyleMap.append( "background-image", "linear-gradient(180deg, blue, black)", ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/stylepropertymap
data/mdn-content/files/en-us/web/api/stylepropertymap/clear/index.md
--- title: "StylePropertyMap: clear() method" short-title: clear() slug: Web/API/StylePropertyMap/clear page-type: web-api-instance-method browser-compat: api.StylePropertyMap.clear --- {{APIRef("CSS Typed Object Model API")}} The **`clear()`** method of the {{domxref("StylePropertyMap")}} interface removes all declarations in the `StylePropertyMap`. ## Syntax ```js-nolint clear() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example removes all styles within the elements [style attribute](/en-US/docs/Web/HTML/Global_attributes/style). ```js // get the button element const buttonEl = document.querySelector(".example"); // remove all styles from the style attribute buttonEl.attributeStyleMap.clear(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/stylepropertymap
data/mdn-content/files/en-us/web/api/stylepropertymap/delete/index.md
--- title: "StylePropertyMap: delete() method" short-title: delete() slug: Web/API/StylePropertyMap/delete page-type: web-api-instance-method browser-compat: api.StylePropertyMap.delete --- {{APIRef("CSS Typed Object Model API")}} The **`delete()`** method of the {{domxref("StylePropertyMap")}} interface removes the CSS declaration with the given property. ## Syntax ```js-nolint delete(property) ``` ### Parameters - `property` - : An identifier indicating the stylistic feature (e.g. font, width, background color) to remove. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example removes the {{cssxref('background-image')}} property from the element's [style attribute](/en-US/docs/Web/HTML/Global_attributes/style). ```js // get the button element const buttonEl = document.querySelector("button"); // remove background-image from style attribute buttonEl.attributeStyleMap.delete("background-image"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/periodicsyncmanager/index.md
--- title: PeriodicSyncManager slug: Web/API/PeriodicSyncManager page-type: web-api-interface status: - experimental browser-compat: api.PeriodicSyncManager --- {{APIRef("Periodic Background Sync")}}{{SeeCompatTable}} The **`PeriodicSyncManager`** interface of the {{domxref('Web Periodic Background Synchronization API', '', '', 'nocode')}} provides a way to register tasks to be run in a service worker at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests. Access `PeriodicSyncManager` through the {{domxref('ServiceWorkerRegistration.periodicSync')}}. ## Instance properties None. ## Instance methods - {{domxref('PeriodicSyncManager.register()')}} {{Experimental_Inline}} - : Registers a periodic sync request with the browser with the specified tag and options. Returns a {{jsxref('Promise')}} that resolves when the registration completes. - {{domxref('PeriodicSyncManager.getTags()')}} {{Experimental_Inline}} - : Returns a {{jsxref('Promise')}} that resolves with a list of {{jsxref('String','strings')}} representing the tags that are currently registered for periodic syncing. - {{domxref('PeriodicSyncManager.unregister()')}} {{Experimental_Inline}} - : Unregisters the periodic sync request corresponding to the specified tag and returns a {{jsxref('Promise')}} that resolves when unregistration completes. ## Examples The following examples show how to use the interface. ### Requesting a Periodic Background Sync The following asynchronous function registers a periodic background sync at a minimum interval of one day from a browsing context: ```js async function registerPeriodicNewsCheck() { const registration = await navigator.serviceWorker.ready; try { await registration.periodicSync.register("get-latest-news", { minInterval: 24 * 60 * 60 * 1000, }); } catch { console.log("Periodic Sync could not be registered!"); } } ``` ### Verifying a Background Periodic Sync by Tag This code checks to see if a Periodic Background Sync task with a given tag is registered. ```js navigator.serviceWorker.ready.then((registration) => { registration.periodicSync.getTags().then((tags) => { if (tags.includes("get-latest-news")) skipDownloadingLatestNewsOnPageLoad(); }); }); ``` ### Removing a Periodic Background Sync Task The following code removes a Periodic Background Sync task to stop articles syncing in the background. ```js navigator.serviceWorker.ready.then((registration) => { registration.periodicSync.unregister("get-latest-news"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync) - [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)
0
data/mdn-content/files/en-us/web/api/periodicsyncmanager
data/mdn-content/files/en-us/web/api/periodicsyncmanager/register/index.md
--- title: "PeriodicSyncManager: register() method" short-title: register() slug: Web/API/PeriodicSyncManager/register page-type: web-api-instance-method status: - experimental browser-compat: api.PeriodicSyncManager.register --- {{APIRef("Periodic Background Sync")}}{{SeeCompatTable}} The **`register()`** method of the {{domxref("PeriodicSyncManager")}} interface registers a periodic sync request with the browser with the specified tag and options. It returns a {{jsxref('Promise')}} that resolves when the registration completes. ## Syntax ```js-nolint register(tag, options) ``` ### Parameters - `tag` - : A unique {{jsxref('String')}} identifier. - `options` {{optional_inline}} - : An {{jsxref('Object')}} containing the following optional data: - `minInterval` - : The minimum interval time, in milliseconds, at which the periodic sync should occur. ### Return value Returns a {{jsxref("Promise")}} that resolves with {{jsxref('undefined')}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Returned if there is no active {{domxref('ServiceWorker')}} present. - `NotAllowedError` {{domxref("DOMException")}} - : Returned if permission for background periodic sync is not granted. - `InvalidAccessError` {{domxref("DOMException")}} - : Returned if the active window is not the main window (not of `auxiliary` or `top-level` type). ## Examples The following asynchronous function registers a periodic background sync at a minimum interval of one day from a browsing context: ```js async function registerPeriodicNewsCheck() { const registration = await navigator.serviceWorker.ready; try { await registration.periodicSync.register("fetch-news", { minInterval: 24 * 60 * 60 * 1000, }); } catch { console.log("Periodic Sync could not be registered!"); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync) - [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)
0
data/mdn-content/files/en-us/web/api/periodicsyncmanager
data/mdn-content/files/en-us/web/api/periodicsyncmanager/gettags/index.md
--- title: "PeriodicSyncManager: getTags() method" short-title: getTags() slug: Web/API/PeriodicSyncManager/getTags page-type: web-api-instance-method status: - experimental browser-compat: api.PeriodicSyncManager.getTags --- {{APIRef("Periodic Background Sync")}}{{SeeCompatTable}} The **`getTags()`** method of the {{domxref("PeriodicSyncManager")}} interface returns a {{jsxref('Promise')}} that resolves with a list of {{jsxref('String')}} objects representing the tags that are currently registered for periodic syncing. ## Syntax ```js-nolint getTags() ``` ### Parameters None. ### Return value A {{jsxref('Promise')}} which resolves with a list of {{jsxref('String')}} objects representing tags that are currently registered for periodic syncing. ### Exceptions None. ## Examples The following example uses the `getTags()` method to check if a periodic sync task with a given tag is registered. ```js navigator.serviceWorker.ready.then((registration) => { registration.periodicSync.getTags().then((tags) => { if (tags.includes("get-latest-news")) skipDownloadingLatestNewsOnPageLoad(); }); }); ``` `skipDownloadingLatestNewsOnPageLoad()` is a developer defined function. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync) - [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)
0
data/mdn-content/files/en-us/web/api/periodicsyncmanager
data/mdn-content/files/en-us/web/api/periodicsyncmanager/unregister/index.md
--- title: "PeriodicSyncManager: unregister() method" short-title: unregister() slug: Web/API/PeriodicSyncManager/unregister page-type: web-api-instance-method status: - experimental browser-compat: api.PeriodicSyncManager.unregister --- {{APIRef("Periodic Background Sync")}}{{SeeCompatTable}} The **`unregister()`** method of the {{domxref("PeriodicSyncManager")}} interface unregisters the periodic sync request corresponding to the specified tag and returns a {{jsxref('Promise')}} that resolves when unregistration completes. ## Syntax ```js-nolint unregister(tag) ``` ### Parameters - tag - : The unique {{jsxref('String')}} descriptor for the specific background sync. ### Return value Returns a {{jsxref("Promise")}} that resolves with {{jsxref('undefined')}}. ### Exceptions None. ## Examples The following example removes a periodic sync to stop syncing articles in the background. ```js navigator.serviceWorker.ready.then((registration) => { registration.periodicSync.unregister("get-latest-news"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync) - [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/response/index.md
--- title: Response slug: Web/API/Response page-type: web-api-interface browser-compat: api.Response --- {{APIRef("Fetch API")}} The **`Response`** interface of the [Fetch API](/en-US/docs/Web/API/Fetch_API) represents the response to a request. You can create a new `Response` object using the {{domxref("Response.Response", "Response()")}} constructor, but you are more likely to encounter a `Response` object being returned as the result of another API operationβ€”for example, a service worker {{domxref("FetchEvent.respondWith")}}, or a simple {{domxref("fetch()")}}. ## Constructor - {{domxref("Response.Response","Response()")}} - : Creates a new `Response` object. ## Instance properties - {{domxref("Response.body")}} {{ReadOnlyInline}} - : A {{domxref("ReadableStream")}} of the body contents. - {{domxref("Response.bodyUsed")}} {{ReadOnlyInline}} - : Stores a boolean value that declares whether the body has been used in a response yet. - {{domxref("Response.headers")}} {{ReadOnlyInline}} - : The {{domxref("Headers")}} object associated with the response. - {{domxref("Response.ok")}} {{ReadOnlyInline}} - : A boolean indicating whether the response was successful (status in the range `200` – `299`) or not. - {{domxref("Response.redirected")}} {{ReadOnlyInline}} - : Indicates whether or not the response is the result of a redirect (that is, its URL list has more than one entry). - {{domxref("Response.status")}} {{ReadOnlyInline}} - : The status code of the response. (This will be `200` for a success). - {{domxref("Response.statusText")}} {{ReadOnlyInline}} - : The status message corresponding to the status code. (e.g., `OK` for `200`). - {{domxref("Response.type")}} {{ReadOnlyInline}} - : The type of the response (e.g., `basic`, `cors`). - {{domxref("Response.url")}} {{ReadOnlyInline}} - : The URL of the response. ## Static methods - {{domxref("Response.error_static","Response.error()")}} - : Returns a new `Response` object associated with a network error. - {{domxref("Response.redirect_static", "Response.redirect()")}} - : Returns a new response with a different URL. - {{domxref("Response.json_static", "Response.json()")}} - : Returns a new `Response` object for returning the provided JSON encoded data. ## Instance methods - {{domxref("Response.arrayBuffer()")}} - : Returns a promise that resolves with an {{jsxref("ArrayBuffer")}} representation of the response body. - {{domxref("Response.blob()")}} - : Returns a promise that resolves with a {{domxref("Blob")}} representation of the response body. - {{domxref("Response.clone()")}} - : Creates a clone of a `Response` object. - {{domxref("Response.formData()")}} - : Returns a promise that resolves with a {{domxref("FormData")}} representation of the response body. - {{domxref("Response.json()")}} - : Returns a promise that resolves with the result of parsing the response body text as {{jsxref("JSON")}}. - {{domxref("Response.text()")}} - : Returns a promise that resolves with a text representation of the response body. ## Examples ### Fetching an image In our [basic fetch example](https://github.com/mdn/dom-examples/tree/main/fetch/basic-fetch) ([run example live](https://mdn.github.io/dom-examples/fetch/basic-fetch/)) we use a simple `fetch()` call to grab an image and display it in an {{htmlelement("img")}} element. The `fetch()` call returns a promise, which resolves to the `Response` object associated with the resource fetch operation. You'll notice that since we are requesting an image, we need to run {{domxref("Response.blob")}} to give the response its correct MIME type. ```js const image = document.querySelector(".my-image"); fetch("flowers.jpg") .then((response) => response.blob()) .then((blob) => { const objectURL = URL.createObjectURL(blob); image.src = objectURL; }); ``` You can also use the {{domxref("Response.Response", "Response()")}} constructor to create your own custom `Response` object: ```js const response = new Response(); ``` ### A PHP Call Here we call a PHP program file that generates a JSON string, displaying the result as a JSON value. ```js // Function to fetch JSON using PHP const getJSON = async () => { // Generate the Response object const response = await fetch("getJSON.php"); if (response.ok) { // Get JSON value from the response body return response.json(); } throw new Error("*** PHP file not found"); }; // Call the function and output value or error message to console getJSON() .then((result) => console.log(result)) .catch((error) => console.error(error)); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/clone/index.md
--- title: "Response: clone() method" short-title: clone() slug: Web/API/Response/clone page-type: web-api-instance-method browser-compat: api.Response.clone --- {{APIRef("Fetch API")}} The **`clone()`** method of the {{domxref("Response")}} interface creates a clone of a response object, identical in every way, but stored in a different variable. Like the underlying {{domxref("ReadableStream.tee")}} api, the {{domxref("Response.body", "body")}} of a cloned `Response` will signal backpressure at the rate of the _faster_ consumer of the two bodies, and unread data is enqueued internally on the slower consumed `body` without any limit or backpressure. Backpressure refers to the mechanism by which the streaming consumer of data (in this case, the code that reads the body) slows down the producer of data (such as the TCP server) so as not to load large amounts of data in memory that is waiting to be used by the application. If only one cloned branch is consumed, then the entire body will be buffered in memory. Therefore, `clone()` is one way to read a response twice in sequence, but you should not use it to read very large bodies in parallel at different speeds. `clone()` throws a {{jsxref("TypeError")}} if the response body has already been used. In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.) ## Syntax ```js-nolint clone() ``` ### Parameters None. ### Return value A {{domxref("Response")}} object. ## Examples In our [Fetch Response clone example](https://github.com/mdn/dom-examples/blob/main/fetch/fetch-response-clone/index.html) (see [Fetch Response clone live](https://mdn.github.io/dom-examples/fetch/fetch-response-clone/)) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("fetch()")}}. When the fetch resolves successfully, we clone it, extract a blob from both responses using two {{domxref("Response.blob")}} calls, create object URLs out of the blobs using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, and display them in two separate {{htmlelement("img")}} elements. ```js const image1 = document.querySelector(".img1"); const image2 = document.querySelector(".img2"); const myRequest = new Request("flowers.jpg"); fetch(myRequest).then((response) => { const response2 = response.clone(); response.blob().then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); image1.src = objectURL; }); response2.blob().then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); image2.src = objectURL; }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/body/index.md
--- title: "Response: body property" short-title: body slug: Web/API/Response/body page-type: web-api-instance-property browser-compat: api.Response.body --- {{APIRef("Fetch API")}} The **`body`** read-only property of the {{domxref("Response")}} interface is a {{domxref("ReadableStream")}} of the body contents. ## Value A {{domxref("ReadableStream")}}, or else [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) for any `Response` object [constructed](/en-US/docs/Web/API/Response/Response) with a null [`body`](/en-US/docs/Web/API/Response/Response#body) property, or for any actual [HTTP response](/en-US/docs/Web/HTTP/Messages#http_responses) that has no [body](/en-US/docs/Web/HTTP/Messages#body_2). The stream is a [readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams), which supports zero-copy reading using a {{domxref("ReadableStreamBYOBReader")}}. > **Note:** Current browsers don't actually conform to the spec requirement to set the `body` property to `null` for responses with no body (for example, responses to [`HEAD`](/en-US/docs/Web/HTTP/Methods/HEAD) requests, or [`204 No Content`](/en-US/docs/Web/HTTP/Status/204) responses). ## Examples ### Copying an image In our [simple stream pump](https://mdn.github.io/dom-examples/streams/simple-pump/) example we fetch an image, expose the response's stream using `response.body`, create a reader using {{domxref("ReadableStream.getReader()", "ReadableStream.getReader()")}}, then enqueue that stream's chunks into a second, custom readable stream β€” effectively creating an identical copy of the image. ```js const image = document.getElementById("target"); // Fetch the original image fetch("./tortoise.png") // Retrieve its body as ReadableStream .then((response) => response.body) .then((body) => { const reader = body.getReader(); return new ReadableStream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // When no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // Enqueue the next data chunk into our target stream controller.enqueue(value); return pump(); }); } }, }); }) .then((stream) => new Response(stream)) .then((response) => response.blob()) .then((blob) => URL.createObjectURL(blob)) .then((url) => console.log((image.src = url))) .catch((err) => console.error(err)); ``` ### Creating a BYOB reader In this example we construct a {{domxref("ReadableStreamBYOBReader")}} from the body using {{domxref("ReadableStream.getReader()", "ReadableStream.getReader({mode: 'byob'})")}}. We can then use this reader to implement zero copy transfer of the response data. ```js async function getProducts(url) { const response = await fetch(url); const reader = response.body.getReader({ mode: "byob" }); // read the response } getProducts( "https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json", ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Fetch API](/en-US/docs/Web/API/Fetch_API) - [Streams API](/en-US/docs/Web/API/Streams_API) - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/json/index.md
--- title: "Response: json() method" short-title: json() slug: Web/API/Response/json page-type: web-api-instance-method browser-compat: api.Response.json --- {{APIRef("Fetch API")}} The **`json()`** method of the {{DOMxRef("Response")}} interface takes a {{DOMxRef("Response")}} stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as {{JSxRef("JSON")}}. Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object. ## Syntax ```js-nolint json() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves to a JavaScript object. This object could be anything that can be represented by JSON β€” an object, an array, a string, a number… ## Examples In our [fetch JSON example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-json) (run [fetch JSON live](https://mdn.github.io/dom-examples/fetch/fetch-json/)), we create a new request using the {{DOMxRef("Request.Request", "Request()")}} constructor, then use it to fetch a `.json` file. When the fetch is successful, we read and parse the data using `json()`, then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. ```js const myList = document.querySelector("ul"); const myRequest = new Request("products.json"); fetch(myRequest) .then((response) => response.json()) .then((data) => { for (const product of data.products) { const listItem = document.createElement("li"); listItem.appendChild(document.createElement("strong")).textContent = product.Name; listItem.append(` can be found in ${product.Location}. Cost: `); listItem.appendChild(document.createElement("strong")).textContent = `Β£${product.Price}`; myList.appendChild(listItem); } }) .catch(console.error); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [Cross-Origin Resource Sharing (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/blob/index.md
--- title: "Response: blob() method" short-title: blob() slug: Web/API/Response/blob page-type: web-api-instance-method browser-compat: api.Response.blob --- {{APIRef("Fetch API")}} The **`blob()`** method of the {{domxref("Response")}} interface takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}. ## Syntax ```js-nolint blob() ``` ### Parameters None. > **Note:** If the {{domxref("Response")}} has a > {{domxref("Response.type")}} of `"opaque"`, the resulting {{domxref("Blob")}} > will have a {{domxref("Blob.size")}} of `0` and a {{domxref("Blob.type")}} of > empty string `""`, which renders it _useless_ for methods like > {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}. ### Return value A promise that resolves with a {{domxref("Blob")}}. ## Examples In our [fetch request example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-request) (run [fetch request live](https://mdn.github.io/dom-examples/fetch/fetch-request/)), we create a new request using the {{domxref("Request.Request","Request()")}} constructor, then use it to fetch a JPG. When the fetch is successful, we read a {{domxref("Blob")}} out of the response using `blob()`, put it into an object URL using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, and then set that URL as the source of an {{htmlelement("img")}} element to display the image. ```js const myImage = document.querySelector("img"); const myRequest = new Request("flowers.jpg"); fetch(myRequest) .then((response) => response.blob()) .then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/response/index.md
--- title: "Response: Response() constructor" short-title: Response() slug: Web/API/Response/Response page-type: web-api-constructor browser-compat: api.Response.Response --- {{APIRef("Fetch API")}} The **`Response()`** constructor creates a new {{domxref("Response")}} object. ## Syntax ```js-nolint new Response() new Response(body) new Response(body, options) ``` ### Parameters - `body` {{optional_inline}} - : An object defining a body for the response. This can be `null` (which is the default value), or one of: - {{domxref("Blob")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("TypedArray")}} - {{jsxref("DataView")}} - {{domxref("FormData")}} - {{domxref("ReadableStream")}} - {{domxref("URLSearchParams")}} - {{jsxref("String")}} - string literal - `options` {{optional_inline}} - : An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: - `status` - : The status code for the response. The default value is `200`. - `statusText` - : The status message associated with the status code, such as `"OK"`. The default value is `""`. - `headers` - : Any headers you want to add to your response, contained within a {{domxref("Headers")}} object or object literal of {{jsxref("String")}} key/value pairs (see [HTTP headers](/en-US/docs/Web/HTTP/Headers) for a reference). By default this is empty. ## Examples In our [Fetch Response example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-response) (see [Fetch Response live](https://mdn.github.io/dom-examples/fetch/fetch-response/)) we create a new `Response` object using the constructor, passing it a new {{domxref("Blob")}} as a body, and an init object containing a custom `status` and `statusText`: ```js const myBlob = new Blob(); const myOptions = { status: 200, statusText: "SuperSmashingGreat!" }; const myResponse = new Response(myBlob, myOptions); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/arraybuffer/index.md
--- title: "Response: arrayBuffer() method" short-title: arrayBuffer() slug: Web/API/Response/arrayBuffer page-type: web-api-instance-method browser-compat: api.Response.arrayBuffer --- {{APIRef("Fetch API")}} The **`arrayBuffer()`** method of the {{domxref("Response")}} interface takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{jsxref("ArrayBuffer")}}. ## Syntax ```js-nolint arrayBuffer() ``` ### Parameters None. ### Return value A promise that resolves with an {{jsxref("ArrayBuffer")}}. ## Examples ### Playing music In our [fetch array buffer live](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-array-buffer), we have a Play button. When pressed, the `getData()` function is run. Note that before playing full audio file will be downloaded. If you need to play ogg during downloading (stream it) - consider {{domxref("HTMLAudioElement")}}: ```js new Audio("music.ogg").play(); ``` In `getData()` we create a new request using the {{domxref("Request.Request","Request()")}} constructor, then use it to fetch an OGG music track. We also use {{domxref("BaseAudioContext/createBufferSource", "AudioContext.createBufferSource")}} to create an audio buffer source. When the fetch is successful, we read an {{jsxref("ArrayBuffer")}} out of the response using `arrayBuffer()`, decode the audio data using {{domxref("BaseAudioContext/decodeAudioData", "AudioContext.decodeAudioData()")}}, set the decoded data as the audio buffer source's buffer (`source.buffer`), then connect the source up to the {{domxref("BaseAudioContext/destination", "AudioContext.destination")}}. Once `getData()` has finished running, we start the audio source playing with `start(0)`, then disable the play button so it can't be clicked again when it is already playing (this would cause an error.) ```js function getData() { const audioCtx = new AudioContext(); return fetch("viper.ogg") .then((response) => { if (!response.ok) { throw new Error(`HTTP error, status = ${response.status}`); } return response.arrayBuffer(); }) .then((buffer) => audioCtx.decodeAudioData(buffer)) .then((decodedData) => { const source = new AudioBufferSourceNode(); source.buffer = decodedData; source.connect(audioCtx.destination); return source; }); } // wire up buttons to stop and play audio play.onclick = () => { getData().then((source) => { source.start(0); play.setAttribute("disabled", "disabled"); }); }; ``` ### Reading files The {{domxref("Response.Response","Response()")}} constructor accepts {{domxref("File")}}s and {{domxref("Blob")}}s, so it may be used to read a {{domxref("File")}} into other formats. ```js function readFile(file) { return new Response(file).arrayBuffer(); } ``` ```html <input type="file" onchange="readFile(this.files[0])" /> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/bodyused/index.md
--- title: "Response: bodyUsed property" short-title: bodyUsed slug: Web/API/Response/bodyUsed page-type: web-api-instance-property browser-compat: api.Response.bodyUsed --- {{APIRef("Fetch API")}} The **`bodyUsed`** read-only property of the {{domxref("Response")}} interface is a boolean value that indicates whether the body has been read yet. ## Value A boolean value. ## Examples ### Checking `bodyUsed` This example illustrates that reading the body of a response changes the value of `bodyUsed` from `false` to `true`. The example contains an empty image. When the example's JavaScript runs, we fetch an image and assigns the returned promise to a variable `responsePromise`. When the user clicks "Use response", we check whether the response has been used already. If it has, we print a message. If it has not, we read the response body and used it to provide a value for the image's `src` attribute. #### HTML ```html <button id="use">Use response</button> <button id="reset">Reset</button> <br /> <img id="my-image" src="" /> <pre id="log"></pre> ``` #### JavaScript ```js const useResponse = document.querySelector("#use"); const reset = document.querySelector("#reset"); const myImage = document.querySelector("#my-image"); const log = document.querySelector("#log"); const responsePromise = fetch( "https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg", ); useResponse.addEventListener("click", async () => { const response = await responsePromise; if (response.bodyUsed) { log.textContent = "Body has already been used!"; } else { const result = await response.blob(); const objectURL = URL.createObjectURL(result); myImage.src = objectURL; } }); reset.addEventListener("click", () => { document.location.reload(); }); ``` #### Result Initially there is no value for the image. If you click "Use response" once, then `bodyUsed` is `false`, so we read the response and set the image. If you then click "Use response" again, then `bodyUsed` is `true`, and we print the message. Click "Reset" to reload the example, so you can try again. {{ EmbedLiveSample('Examples', '100%', '300px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/status/index.md
--- title: "Response: status property" short-title: status slug: Web/API/Response/status page-type: web-api-instance-property browser-compat: api.Response.status --- {{APIRef("Fetch API")}} The **`status`** read-only property of the {{domxref("Response")}} interface contains the [HTTP status codes](/en-US/docs/Web/HTTP/Status) of the response. For example, `200` for success, `404` if the resource could not be found. ## Value An unsigned short number. This is one of the [HTTP response status codes](/en-US/docs/Web/HTTP/Status). ## Examples In our [Fetch Response example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-response) (see [Fetch Response live](https://mdn.github.io/dom-examples/fetch/fetch-response/)) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("fetch()")}}, extract a blob from the response using {{domxref("Response.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, and display this in an {{htmlelement("img")}}. Note that at the top of the `fetch()` block we log the response `status` value to the console. ```js const myImage = document.querySelector("img"); const myRequest = new Request("flowers.jpg"); fetch(myRequest) .then((response) => { console.log("response.status =", response.status); // response.status = 200 return response.blob(); }) .then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/error_static/index.md
--- title: "Response: error() static method" short-title: error() slug: Web/API/Response/error_static page-type: web-api-static-method browser-compat: api.Response.error_static --- {{APIRef("Fetch API")}} The **`error()`** static method of the {{domxref("Response")}} interface returns a new `Response` object associated with a network error. This is mainly useful when writing service workers: it enables a service worker to send a response from a {{domxref("ServiceWorkerGlobalScope.fetch_event", "fetch")}} event handler that will cause the {{domxref("fetch()")}} call in the main app code to reject the promise. An error response has its {{domxref("Response.type","type")}} set to `error`. ## Syntax ```js-nolint Response.error() ``` ### Parameters None. ### Return value A {{domxref("Response")}} object. ## Examples ### Returning a network error from a service worker Suppose a web app has a service worker, which contains the following `fetch` event handler: ```js // service-worker.js self.addEventListener("fetch", (event) => { const url = new URL(event.request.url); if (url.pathname === "/salamander.jpg") { event.respondWith(Response.error()); } }); ``` With this service worker, all fetch requests from the app will pass through the service worker to the network, except for requests to fetch "salamander.jpg", which will reject. This means that the following main thread code would throw an error, and the `catch` handler will run. ```js // main.js const image = document.querySelector("#image"); try { const response = await fetch("salamander.jpg"); const blob = await response.blob(); const objectURL = URL.createObjectURL(blob); image.src = objectURL; } catch (e) { console.error(e); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/text/index.md
--- title: "Response: text() method" short-title: text() slug: Web/API/Response/text page-type: web-api-instance-method browser-compat: api.Response.text --- {{APIRef("Fetch API")}} The **`text()`** method of the {{domxref("Response")}} interface takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{jsxref("String")}}. The response is _always_ decoded using UTF-8. ## Syntax ```js-nolint text() ``` ### Parameters None. ### Return value A Promise that resolves with a {{jsxref("String")}}. ## Examples In our [fetch text example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-text) (run [fetch text live](https://mdn.github.io/dom-examples/fetch/fetch-text/)), we have an {{htmlelement("article")}} element and three links (stored in the `myLinks` array.) First, we loop through all of these and give each one an `onclick` event handler so that the `getData()` function is run β€” with the link's `data-page` identifier passed to it as an argument β€” when one of the links is clicked. When `getData()` is run, we create a new request using the {{domxref("Request.Request","Request()")}} constructor, then use it to fetch a specific `.txt` file. When the fetch is successful, we read a string out of the response using `text()`, then set the {{domxref("HTMLElement.innerText","innerText")}} of the {{htmlelement("article")}} element equal to the text object. ```js const myArticle = document.querySelector("article"); const myLinks = document.querySelectorAll("ul a"); for (const link of myLinks) { link.onclick = (e) => { e.preventDefault(); const linkData = e.target.getAttribute("data-page"); getData(linkData); }; } function getData(pageId) { console.log(pageId); const myRequest = new Request(`${pageId}.txt`); fetch(myRequest) .then((response) => response.text()) .then((text) => { myArticle.innertext = text; }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/redirect_static/index.md
--- title: "Response: redirect() static method" short-title: redirect() slug: Web/API/Response/redirect_static page-type: web-api-static-method browser-compat: api.Response.redirect_static --- {{APIRef("Fetch API")}} The **`redirect()`** static method of the {{domxref("Response")}} interface returns a `Response` resulting in a redirect to the specified URL. > **Note:** This can be used alongside the [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API). > A controlling service worker could intercept a page's request and redirect it as desired. > This will actually lead to a real redirect if a service worker sends it upstream. ## Syntax ```js-nolint Response.redirect(url) Response.redirect(url, status) ``` ### Parameters - `url` - : The URL that the new response is to originate from. - `status` {{optional_inline}} - : An optional number indicating the status code for the response: one of {{HTTPStatus("301", "301")}}, {{HTTPStatus("302", "302")}}, {{HTTPStatus("303", "303")}}, {{HTTPStatus("307", "307")}}, or {{HTTPStatus("308", "308")}}. If omitted, {{HTTPStatus("302", "302 (Found)")}} is used by default. ### Return value A {{domxref("Response")}} object. ### Exceptions - {{jsxref("RangeError")}} - : The specified status is not a redirect status. - {{jsxref("TypeError")}} - : The specified URL is invalid. ## Examples ```js Response.redirect("https://www.example.com", 302); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/headers/index.md
--- title: "Response: headers property" short-title: headers slug: Web/API/Response/headers page-type: web-api-instance-property browser-compat: api.Response.headers --- {{APIRef("Fetch API")}} The **`headers`** read-only property of the {{domxref("Response")}} interface contains the {{domxref("Headers")}} object associated with the response. ## Value A {{domxref("Headers")}} object. ## Examples In our [Fetch Response example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-response) (see [Fetch Response live](https://mdn.github.io/dom-examples/fetch/fetch-response/)) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("fetch()")}}, extract a blob from the response using {{domxref("Response.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, and display this in an {{htmlelement("img")}}. Note that at the top of the `fetch()` block, we log the response headers to the console. ```js const myImage = document.querySelector("img"); const myRequest = new Request("flowers.jpg"); fetch(myRequest) .then((response) => { console.log("response.headers =", response.headers); return response.blob(); }) .then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/url/index.md
--- title: "Response: url property" short-title: url slug: Web/API/Response/url page-type: web-api-instance-property browser-compat: api.Response.url --- {{APIRef("Fetch API")}} The **`url`** read-only property of the {{domxref("Response")}} interface contains the URL of the response. The value of the `url` property will be the final URL obtained after any redirects. ## Value A string. ## Examples In our [Fetch Response example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-response) (see [Fetch Response live](https://mdn.github.io/dom-examples/fetch/fetch-response/)) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("fetch()")}}, extract a blob from the response using {{domxref("Response.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, and display this in an {{htmlelement("img")}}. Note that at the top of the `fetch()` block we log the response `URL` to the console. ```js const myImage = document.querySelector("img"); const myRequest = new Request("flowers.jpg"); fetch(myRequest) .then((response) => { console.log("response.url =", response.url); // response.url = https://mdn.github.io/dom-examples/fetch/fetch-response/flowers.jpg return response.blob(); }) .then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/type/index.md
--- title: "Response: type property" short-title: type slug: Web/API/Response/type page-type: web-api-instance-property browser-compat: api.Response.type --- {{APIRef("Fetch API")}} The **`type`** read-only property of the {{domxref("Response")}} interface contains the type of the response. It can be one of the following: - `basic`: Normal, same origin response, with all headers exposed except "Set-Cookie". - `cors`: Response was received from a valid cross-origin request. [Certain headers and the body](https://fetch.spec.whatwg.org/#concept-filtered-response-cors) may be accessed. - `error`: Network error. No useful information describing the error is available. The Response's status is 0, headers are empty and immutable. This is the type for a Response obtained from `Response.error()`. - `opaque`: Response for "no-cors" request to cross-origin resource. [Severely restricted](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque). - `opaqueredirect`: The fetch request was made with `redirect: "manual"`. The Response's status is 0, headers are empty, body is null and trailer is empty. > **Note:** An "error" Response never really gets exposed to script: such a response to a {{domxref("fetch()")}} would reject the promise. ## Value A `ResponseType` string indicating the type of the response. ## Examples In our [Fetch Response example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-response) (see [Fetch Response live](https://mdn.github.io/dom-examples/fetch/fetch-response/)) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("fetch()")}}, extract a blob from the response using {{domxref("Response.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, and display this in an {{htmlelement("img")}}. Note that at the top of the `fetch()` block we log the response `type` to the console. ```js const myImage = document.querySelector("img"); const myRequest = new Request("flowers.jpg"); fetch(myRequest) .then((response) => { console.log("response.type =", response.type); // response.type = 'basic' return response.blob(); }) .then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/redirected/index.md
--- title: "Response: redirected property" short-title: redirected slug: Web/API/Response/redirected page-type: web-api-instance-property browser-compat: api.Response.redirected --- {{APIRef("Fetch API")}} The read-only **`redirected`** property of the {{domxref("Response")}} interface indicates whether or not the response is the result of a request you made which was redirected. > **Note:** Relying on redirected to filter out redirects makes it easy for a forged redirect to prevent your content from working as expected. > Instead, you should do the filtering when you call {{domxref("fetch()")}}. > See the example [Disallowing redirects](#disallowing_redirects), which shows this being done. ## Value A boolean value which is `true` if the response indicates that your request was redirected. ## Examples ### Detecting redirects Checking to see if the response comes from a redirected request is as simple as checking this flag on the {{domxref("Response")}} object. In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. Note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under [Disallowing redirects](#disallowing_redirects) below. The {{domxref("Response.url", "url")}} property returns the final URL after redirects. ```js fetch("awesome-picture.jpg") .then((response) => { const elem = document.getElementById("warning-message-box"); elem.textContent = response.redirected ? "Unexpected redirect" : ""; // final url obtained after redirects console.log(response.url); return response.blob(); }) .then((imageBlob) => { const imgObjectURL = URL.createObjectURL(imageBlob); document.getElementById("img-element-id").src = imgObjectURL; }); ``` ### Disallowing redirects Because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to `"error"` in the `init` parameter when calling {{domxref("fetch()")}}, like this: ```js fetch("awesome-picture.jpg", { redirect: "error" }) .then((response) => response.blob()) .then((imageBlob) => { const imgObjectURL = URL.createObjectURL(imageBlob); document.getElementById("img-element-id").src = imgObjectURL; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Fetch API](/en-US/docs/Web/API/Fetch_API) - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/json_static/index.md
--- title: "Response: json() static method" short-title: json() slug: Web/API/Response/json_static page-type: web-api-static-method browser-compat: api.Response.json_static --- {{APIRef("Fetch API")}} The **`json()`** static method of the {{domxref("Response")}} interface returns a `Response` that contains the provided JSON data as body, and a {{HTTPHeader("Content-Type")}} header which is set to `application/json`. The response status, status message, and additional headers can also be set. The method makes it easy to create `Response` objects for returning JSON encoded data. [Service workers](/en-US/docs/Web/API/Service_Worker_API), for example, intercept fetch requests made by a browser, and might use `json()` to construct a `Response` from cached JSON data to return to the main thread. The `json()` method can also be used in server code to return JSON data for [single page applications](/en-US/docs/Glossary/SPA), and any other applications where a JSON response is expected. ## Syntax ```js-nolint Response.json(data) Response.json(data, options) ``` ### Parameters - `data` - : The JSON data to be used as the response body. - `options` {{optional_inline}} - : An options object containing settings for the response, including the status code, status text, and headers. This is the same as the options parameter of the {{domxref("Response.Response", "Response()")}} constructor. - `status` - : The status code for the response, such as `200`. - `statusText` - : The status message associated with the status code. For a status of `200` this might be `OK`. - `headers` - : Any headers you want to add to your response, contained within a {{domxref("Headers")}} object or object literal of {{jsxref("String")}} key/value pairs (see [HTTP headers](/en-US/docs/Web/HTTP/Headers) for a reference). ### Return value A {{domxref("Response")}} object. ### Exceptions - `TypeError` - : Thrown if `data` cannot be converted to a JSON string. This might happen if the data is a JavaScript object that has method, or that has a circular reference, or if the passed object is `undefined`. ## Examples ### Response with JSON data This live example shows how you can create a JSON response object, and logs the newly created object for inspection (the logging code is hidden as it is not relevant). ```html hidden <pre id="log"></pre> ``` ```js hidden const logElement = document.getElementById("log"); function log(text) { logElement.innerText += `${text}\n`; } async function logResponse(response) { const responseText = await jsonResponse.text(); log(`body: ${responseText}`); jsonResponse.headers.forEach((header) => log(`header: ${header}`)); log(`status: ${jsonResponse.status}`); log(`statusText: ${jsonResponse.statusText}`); log(`type: ${jsonResponse.type}`); log(`url: ${jsonResponse.url}`); log(`ok: ${jsonResponse.ok}`); log(`redirected: ${jsonResponse.redirected}`); log(`bodyUsed: ${jsonResponse.bodyUsed}`); } ``` The code below creates a `Response` object with JSON body `{ my: "data" }` and header set to `application/json`. ```js const jsonResponse = Response.json({ my: "data" }); logResponse(jsonResponse); ``` The object has the following properties. Note the body and header are set as expected, and that the default status is set to `200`. {{EmbedLiveSample('Response with JSON data','100%', '170')}} ### Response with JSON data and options This example shows how you can create a JSON response object with `status` and `statusText` options. ```html hidden <pre id="log"></pre> ``` ```js hidden const logElement = document.getElementById("log"); function log(text) { logElement.innerText += `${text}\n`; } async function logResponse(response) { const responseText = await jsonResponse.text(); log(`body: ${responseText}`); jsonResponse.headers.forEach((header) => log(`header: ${header}`)); log(`status: ${jsonResponse.status}`); log(`statusText: ${jsonResponse.statusText}`); log(`type: ${jsonResponse.type}`); log(`url: ${jsonResponse.url}`); log(`ok: ${jsonResponse.ok}`); log(`redirected: ${jsonResponse.redirected}`); log(`bodyUsed: ${jsonResponse.bodyUsed}`); } ``` The code below creates a `Response` object with JSON body `{ some: "data", more: "information" }` and header set to `application/json`. It also sets the status to `307` and sets the appropriate status text ("Temporary Redirect"). ```js const jsonResponse = Response.json( { some: "data", more: "information" }, { status: 307, statusText: "Temporary Redirect" }, ); logResponse(jsonResponse); ``` The object has the following properties, which are set as expected. Note that the `ok` property of the response changed to `false` as the status value is not in the range of 200 to 299. {{EmbedLiveSample('Response with JSON data and options','100%', '170')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Service Worker API](/en-US/docs/Web/API/Service_Worker_API)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/formdata/index.md
--- title: "Response: formData() method" short-title: formData() slug: Web/API/Response/formData page-type: web-api-instance-method browser-compat: api.Response.formData --- {{APIRef("Fetch API")}} The **`formData()`** method of the {{domxref("Response")}} interface takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object. > **Note:** This is mainly relevant to [service workers](/en-US/docs/Web/API/Service_Worker_API). If a user submits > a form and a service worker intercepts the request, you could for example call > `formData()` on it to obtain a key-value map, modify some fields, then send > the form onwards to the server (or use it locally). ## Syntax ```js-nolint formData() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with a {{domxref("FormData")}} object. ## Examples TBD. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/statustext/index.md
--- title: "Response: statusText property" short-title: statusText slug: Web/API/Response/statusText page-type: web-api-instance-property browser-compat: api.Response.statusText --- {{APIRef("Fetch API")}} The **`statusText`** read-only property of the {{domxref("Response")}} interface contains the status message corresponding to the HTTP status code in {{domxref("Response.status")}}. For example, this would be `OK` for a status code `200`, `Continue` for `100`, `Not Found` for `404`. ## Value A {{jsxref("String")}} containing the HTTP status message associated with the response. The default value is "". See [HTTP response status codes](/en-US/docs/Web/HTTP/Status) for a list of codes and their associated status messages. Note that HTTP/2 [does not support](https://fetch.spec.whatwg.org/#concept-response-status-message) status messages. ## Examples In our [Fetch Response example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-response) (see [Fetch Response live](https://mdn.github.io/dom-examples/fetch/fetch-response/)) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("fetch()")}}, extract a blob from the response using {{domxref("Response.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, and display this in an {{htmlelement("img")}}. Note that at the top of the `fetch()` block we log the response `statusText` value to the console. ```js const myImage = document.querySelector("img"); const myRequest = new Request("flowers.jpg"); fetch(myRequest) .then((response) => { console.log("response.statusText =", response.statusText); // response.statusText = "OK" return response.blob(); }) .then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/response
data/mdn-content/files/en-us/web/api/response/ok/index.md
--- title: "Response: ok property" short-title: ok slug: Web/API/Response/ok page-type: web-api-instance-property browser-compat: api.Response.ok --- {{APIRef("Fetch API")}} The **`ok`** read-only property of the {{domxref("Response")}} interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. ## Value A boolean value. ## Examples In our [Fetch Response example](https://github.com/mdn/dom-examples/tree/main/fetch/fetch-response) (see [Fetch Response live](https://mdn.github.io/dom-examples/fetch/fetch-response/)) we create a new {{domxref("Request")}} object using the {{domxref("Request.Request","Request()")}} constructor, passing it a JPG path. We then fetch this request using {{domxref("fetch()")}}, extract a blob from the response using {{domxref("Response.blob")}}, create an object URL out of it using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}, and display this in an {{htmlelement("img")}}. > **Note:** at the top of the `fetch()` block we log the response `ok` value to the console. ```js const myImage = document.querySelector("img"); const myRequest = new Request("flowers.jpg"); fetch(myRequest).then((response) => { console.log(response.ok); // returns true if the response returned successfully response.blob().then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) - [HTTP access control (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svggelement/index.md
--- title: SVGGElement slug: Web/API/SVGGElement page-type: web-api-interface browser-compat: api.SVGGElement --- {{APIRef("SVG")}} The **`SVGGElement`** interface corresponds to the {{SVGElement("g")}} element. {{InheritanceDiagram}} ## Instance properties _This interface doesn't implement any specific properties, but inherits properties from its parent interface, {{domxref("SVGGraphicsElement")}}._ ## Instance methods _This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGGraphicsElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/paymentmanager/index.md
--- title: PaymentManager slug: Web/API/PaymentManager page-type: web-api-interface status: - experimental browser-compat: api.PaymentManager --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`PaymentManager`** interface of the {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} is used to manage various aspects of payment app functionality. It is accessed via the {{domxref("ServiceWorkerRegistration.paymentManager")}} property. {{InheritanceDiagram}} ## Instance properties - {{domxref("PaymentManager.userHint", "userHint")}} {{Experimental_Inline}} - : Provides a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI. ## Instance methods - {{domxref("PaymentManager.enableDelegations", "enableDelegations()")}} {{Experimental_Inline}} - : Delegates responsibility for providing various parts of the required payment information to the payment app rather than collecting it from the browser (for example, via autofill). ## Examples ```js navigator.serviceWorker.register("serviceworker.js").then((registration) => { registration.paymentManager.userHint = "Card number should be 16 digits"; registration.paymentManager .enableDelegations(["shippingAddress", "payerName"]) .then(() => { // ... }); // ... }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} - [Web-based payment apps overview](https://web.dev/articles/web-based-payment-apps-overview) - [Setting up a payment method](https://web.dev/articles/setting-up-a-payment-method) - [Life of a payment transaction](https://web.dev/articles/life-of-a-payment-transaction) - [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API) - [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
0
data/mdn-content/files/en-us/web/api/paymentmanager
data/mdn-content/files/en-us/web/api/paymentmanager/enabledelegations/index.md
--- title: "PaymentManager: enableDelegations() method" short-title: enableDelegations() slug: Web/API/PaymentManager/enableDelegations page-type: web-api-instance-method status: - experimental browser-compat: api.PaymentManager.enableDelegations --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`enableDelegations()`** method of the {{domxref("PaymentManager")}} interface delegates responsibility for providing various parts of the required payment information to the payment app rather than collecting it from the browser (for example, via autofill). For example, if the `requestShipping` option is set to `true` in the options object when invoking the {{domxref("PaymentRequest.PaymentRequest", "PaymentRequest()")}} constructor, a shipping address will be returned. - If `enableDelegations()` was used to delegate `shippingAddress`, that address will come from the payment app. - If not, it will come from the browser autofill. ## Syntax ```js-nolint enableDelegations(delegations) ``` ### Parameters - `delegations` {{optional_inline}} - : An array containing one or more enumerated values that specify the payment information you want to delegate to the payment app. Possible values can be: - `payerEmail` - : The payment app will provide the payer's email whenever it is needed. - `payerName` - : The payment app will provide the payer's name whenever it is needed. - `payerPhone` - : The payment app will provide the payer's phone number whenever it is needed. - `shippingAddress` - : The payment app will provide the shipping address whenever it is needed. ### Return value A {{jsxref("Promise")}} that resolves with a value of `undefined`. ## Examples ```js navigator.serviceWorker.register("serviceworker.js").then((registration) => { registration.paymentManager.userHint = "Card number should be 16 digits"; registration.paymentManager .enableDelegations(["shippingAddress", "payerName"]) .then(() => { // ... }); // ... }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} - [Web-based payment apps overview](https://web.dev/articles/web-based-payment-apps-overview) - [Setting up a payment method](https://web.dev/articles/setting-up-a-payment-method) - [Life of a payment transaction](https://web.dev/articles/life-of-a-payment-transaction) - [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API) - [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
0
data/mdn-content/files/en-us/web/api/paymentmanager
data/mdn-content/files/en-us/web/api/paymentmanager/userhint/index.md
--- title: "PaymentManager: userHint property" short-title: userHint slug: Web/API/PaymentManager/userHint page-type: web-api-instance-property status: - experimental browser-compat: api.PaymentManager.userHint --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`userHint`** property of the {{domxref("PaymentManager")}} interface provides a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI. ## Value A string. ## Examples ```js navigator.serviceWorker.register("serviceworker.js").then((registration) => { registration.paymentManager.userHint = "Card number should be 16 digits"; registration.paymentManager .enableDelegations(["shippingAddress", "payerName"]) .then(() => { // ... }); // ... }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} - [Web-based payment apps overview](https://web.dev/articles/web-based-payment-apps-overview) - [Setting up a payment method](https://web.dev/articles/setting-up-a-payment-method) - [Life of a payment transaction](https://web.dev/articles/life-of-a-payment-transaction) - [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API) - [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/sourcebufferlist/index.md
--- title: SourceBufferList slug: Web/API/SourceBufferList page-type: web-api-interface browser-compat: api.SourceBufferList --- {{APIRef("Media Source Extensions")}} The **`SourceBufferList`** interface represents a simple container list for multiple {{domxref("SourceBuffer")}} objects. The source buffer list containing the `SourceBuffer`s appended to a particular `MediaSource` can be retrieved using the {{domxref("MediaSource.sourceBuffers")}} property. The individual source buffers can be accessed using the [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation) `[]`. {{InheritanceDiagram}} ## Instance properties - {{domxref("SourceBufferList.length")}} {{ReadOnlyInline}} - : Returns the number of {{domxref("SourceBuffer")}} objects in the list. ## Instance methods _Inherits methods from its parent interface, {{domxref("EventTarget")}}._ ## Events - {{domxref("SourceBufferList.addsourcebuffer_event", "addsourcebuffer")}} - : Fired when a {{domxref("SourceBuffer")}} is added to the list. - {{domxref("SourceBufferList.removesourcebuffer_event", "removesourcebuffer")}} - : Fired when a {{domxref("SourceBuffer")}} is removed from the list. ## Examples This example shows how to access the active source buffers of the {{domxref("MediaSource")}} connected to an already playing {{domxref("HTMLVideoElement")}}. ```js // Video is an already playing video using a MediaSource srcObject const video = document.querySelector("video"); const mediaSource = video.srcObject; const sourceBufferList = mediaSource.activeSourceBuffers; for (const sourceBuffer of sourceBufferList) { // Do something with each SourceBuffer, such as call abort() sourceBuffer.abort(); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBuffer")}}
0
data/mdn-content/files/en-us/web/api/sourcebufferlist
data/mdn-content/files/en-us/web/api/sourcebufferlist/length/index.md
--- title: "SourceBufferList: length property" short-title: length slug: Web/API/SourceBufferList/length page-type: web-api-instance-property browser-compat: api.SourceBufferList.length --- {{APIRef("Media Source Extensions")}} The **`length`** read-only property of the {{domxref("SourceBufferList")}} interface returns the number of {{domxref("SourceBuffer")}} objects in the list. ## Value An unsigned long number. ## Examples TBD ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBuffer")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/background_fetch_api/index.md
--- title: Background Fetch API slug: Web/API/Background_Fetch_API page-type: web-api-overview status: - experimental browser-compat: - api.BackgroundFetchManager - api.BackgroundFetchRegistration - api.BackgroundFetchRecord spec-urls: https://wicg.github.io/background-fetch/ --- {{DefaultAPISidebar("Background Fetch API")}} {{SeeCompatTable}} The **Background Fetch API** provides a method for managing downloads that may take a significant amount of time such as movies, audio files, and software. ## Concepts and Usage When a web application requires the user to download large files, this often presents a problem in that the user needs to stay connected to the page for the download to complete. If they lose connectivity, close the tab or navigate away from the page the download stops. The {{domxref("Background Synchronization API", "", "", "nocode")}} provides a way for service workers to defer processing until a user is connected; however it can't be used for long running tasks such as downloading a large file. Background Sync requires that the service worker stays alive until the fetch is completed, and to conserve battery life and to prevent unwanted tasks happening in the background the browser will at some point terminate the task. The Background Fetch API solves this problem. It creates a way for a web developer to tell the browser to perform some fetches in the background, for example when the user clicks a button to download a video file. The browser then performs the fetches in a user-visible way, displaying progress to the user and giving them a method to cancel the download. Once the download is complete the browser then opens the service worker, at which point your application can do something with the response if required. The Background Fetch API will enable the fetch to happen if the user starts the process while offline. Once they are connected it will begin. If the user goes off line, the process pauses until the user is on again. ## Interfaces - {{domxref("BackgroundFetchManager")}} {{Experimental_Inline}} - : A map where the keys are background fetch IDs and the values are {{domxref("BackgroundFetchRegistration")}} objects. - {{domxref("BackgroundFetchRegistration")}} {{Experimental_Inline}} - : Represents a Background Fetch. - {{domxref("BackgroundFetchRecord")}} {{Experimental_Inline}} - : Represents an individual fetch request and response. - {{domxref("BackgroundFetchEvent")}} {{Experimental_Inline}} - : The event type for the {{domxref("ServiceWorkerGlobalScope.backgroundfetchabort_event", "backgroundfetchabort")}} and {{domxref("ServiceWorkerGlobalScope.backgroundfetchclick_event", "backgroundfetchclick")}} event - {{domxref("BackgroundFetchUpdateUIEvent")}} {{Experimental_Inline}} - : The event type for the {{domxref("ServiceWorkerGlobalScope.backgroundfetchsuccess_event", "backgroundfetchsuccess")}} and {{domxref("ServiceWorkerGlobalScope.backgroundfetchfail_event", "backgroundfetchfail")}} event ### Extensions to other interfaces - {{domxref("ServiceWorkerRegistration.backgroundFetch")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to a {{domxref("BackgroundFetchManager")}} object, which manages background fetch operations. - {{domxref("ServiceWorkerGlobalScope/backgroundfetchabort_event", "backgroundfetchabort")}} event {{Experimental_Inline}} - : Fired when a background fetch operation has been canceled by the user or the app. - {{domxref("ServiceWorkerGlobalScope/backgroundfetchclick_event", "backgroundfetchclick")}} event {{Experimental_Inline}} - : Fired when the user has clicked on the UI for a background fetch operation. - {{domxref("ServiceWorkerGlobalScope/backgroundfetchfail_event", "backgroundfetchfail")}} event {{Experimental_Inline}} - : Fired when at least one of the requests in a background fetch operation has failed. - {{domxref("ServiceWorkerGlobalScope/backgroundfetchsuccess_event", "backgroundfetchsuccess")}} event {{Experimental_Inline}} - : Fired when all of the requests in a background fetch operation have succeeded. ## Examples Before using Background Fetch, check for browser support. ```js if (!("BackgroundFetchManager" in self)) { // Provide fallback downloading. } ``` Using Background Fetch requires a registered service worker. Then call `backgroundFetch.fetch()` to perform a fetch. This returns a promise that resolves with a {{domxref("BackgroundFetchRegistration")}}. A background fetch may fetch a number of files. In our example the fetch requests an MP3 and a JPEG. This enables a package of files that the user sees as one item (for example a podcast and artwork) to be downloaded at once. ```js navigator.serviceWorker.ready.then(async (swReg) => { const bgFetch = await swReg.backgroundFetch.fetch( "my-fetch", ["/ep-5.mp3", "ep-5-artwork.jpg"], { title: "Episode 5: Interesting things.", icons: [ { sizes: "300x300", src: "/ep-5-icon.png", type: "image/png", }, ], downloadTotal: 60 * 1024 * 1024, }, ); }); ``` You can find a demo application which implements Background Fetch [here](https://glitch.com/edit/#!/bgfetch-http203?path=public%2Fclient.js%3A191%3A45). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Introducing Background Fetch](https://developer.chrome.com/blog/background-fetch/) - [Background Fetch - HTTP 203](https://www.youtube.com/watch?v=cElAoxhQz6w)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfontelement/index.md
--- title: SVGFontElement slug: Web/API/SVGFontElement page-type: web-api-interface status: - deprecated browser-compat: api.SVGFontElement --- {{APIRef("SVG")}}{{deprecated_header}} The **`SVGFontElement`** interface corresponds to the {{SVGElement("font")}} elements. Object-oriented access to the attributes of the {{SVGElement("font")}} element via the SVG DOM is not possible. {{InheritanceDiagram}} ## Instance properties _This interface has no properties but inherits properties from its parent, {{domxref("SVGElement")}}._ ## Instance methods _This interface has no methods but inherits methods from its parent, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("font")}} SVG Element
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/virtualkeyboard_api/index.md
--- title: VirtualKeyboard API slug: Web/API/VirtualKeyboard_API page-type: web-api-overview status: - experimental browser-compat: api.VirtualKeyboard --- {{SeeCompatTable}}{{DefaultAPISidebar("VirtualKeyboard API")}}{{securecontext_header}} The VirtualKeyboard API provides developers control over the layout of their applications when the on-screen virtual keyboard appears and disappears on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available. Web browsers usually deal with virtual keyboards on their own, by adjusting the viewport height and scrolling to input fields when focused. The figure below illustrates the difference in viewport height and scroll position on a web page when the device has its on-screen virtual keyboard hidden, and when it is shown. ![Two devices, one without a virtual keyboard, showing that the webpage can use most of the device's vertical space, and one with a virtual keyboard, showing that the webpage can only be displayed in the remaining space](viewport-height.png) More complex applications or specific devices such as multi-screen mobile phones may require more control of the layout when the virtual keyboard appears. The figure below shows what happens on a dual-screen device when the virtual keyboard appears on just one of the two screens. The viewport becomes smaller on both screens to accommodate for the virtual keyboard, leaving wasted space on the screen where the virtual keyboard is not displayed. ![A dual-screen device, with its virtual keyboard displayed on one screen, showing that the webpage can only use the vertical space that remains after the keyboard was displayed, even if that leaves empty space on the other screen](dual-screen.png) The VirtualKeyboard API can be used to opt out of the way the browser automatically handles the virtual keyboard, and take full control of it instead. With the VirtualKeyboard API, the keyboard still appears and disappears as necessary when form controls are focused, but the viewport does not change, and you can use JavaScript and CSS to adapt your layout. ## Concept The VirtualKeyboard API consists of three parts: - The {{domxref("VirtualKeyboard")}} interface, accessed through {{domxref('navigator.virtualKeyboard')}}, is used to opt out of the automatic virtual keyboard behavior, show or hide the virtual keyboard programmatically, as well as get the current position and size of the virtual keyboard. - The `keyboard-inset-*` CSS environment variables provide information about the virtual keyboard's position and size. - The [`virtualkeyboardpolicy`](/en-US/docs/Web/HTML/Global_attributes/virtualkeyboardpolicy) attribute specifies whether the virtual keyboard should appear on `contenteditable` elements. ### Opt out of the automatic virtual keyboard behavior To opt out of the automatic virtual keyboard behavior of the browser, use `navigator.virtualKeyboard.overlaysContent = true`. The browser will no longer automatically resize the viewport to make space for the virtual keyboard, which will overlay your content instead. ### Detect the virtual keyboard geometry using JavaScript Once you've opted out of the default browser behavior, you can get the current geometry of the virtual keyboard using `navigator.virtualKeyboard.boundingRect`, and adapt the layout as appropriate using CSS and JavaScript. In addition, you can listen to geometry changes, such as when the keyboard is shown or hidden, by using the `geometrychange` event. This is useful for positioning important UI elements in the area that's not covered by the virtual keyboard. The code snippet below uses the `geometrychange` event to detect when the virtual keyboard geometry changes; it then accesses the `boundingRect` property to query the size and position of the virtual keyboard: ```js if ("virtualKeyboard" in navigator) { navigator.virtualKeyboard.overlaysContent = true; navigator.virtualKeyboard.addEventListener("geometrychange", (event) => { const { x, y, width, height } = event.target.boundingRect; }); } ``` ### Detect the virtual keyboard geometry using CSS environment variables The VirtualKeyboard API also exposes the following {{cssxref("env", "CSS environment variables", "", "nocode")}}: `keyboard-inset-top`, `keyboard-inset-right`, `keyboard-inset-bottom`, `keyboard-inset-left`, `keyboard-inset-width`, and `keyboard-inset-height`. The `keyboard-inset-*` CSS environment variables are useful to adapt your layout to the virtual keyboard appearance using CSS. They define a rectangle by its top, right, bottom, and left insets from the edge of the viewport. The `width` and `height` variables are also available if needed. The code snippet below uses the `keyboard-inset-height` CSS variable to reserve space for the virtual keyboard to appear below the list of messages and input field in a chat-like application. When the virtual keyboard is hidden, the `env()` function returns `0px` and the `keyboard` grid area is hidden. The messages and input elements can occupy the full height of the viewport. When the virtual keyboard appears, the `keyboard` grid area gets the height of the virtual keyboard. ```html <style> body { display: grid; margin: 0; height: 100vh; grid-template: "messages" 1fr "input" auto "keyboard" env(keyboard-inset-height, 0px); } </style> <ul id="messages"></ul> <input type="text" /> <script> if ("virtualKeyboard" in navigator) { navigator.virtualKeyboard.overlaysContent = true; } </script> ``` ### Control the virtual keyboard on `contenteditable` elements By default, elements using the [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) attribute also trigger the virtual keyboard when tapped or clicked. In certain situations, it may be desirable to prevent this behavior and instead show the virtual keyboard after a different event. Set the [`virtualkeyboardpolicy`](/en-US/docs/Web/HTML/Global_attributes/virtualkeyboardpolicy) attribute to `manual` to prevent the default handling of the virtual keyboard in the browser, and instead handle it yourself by using the {{domxref("VirtualKeyboard")}} interface's `show()` and `hide()` methods. The code snippet below shows how to use the `virtualkeyboardpolicy` attribute and the `navigator.virtualKeyboard.show()` method to show the virtual keyboard on double-click instead: ```html <div contenteditable virtualkeyboardpolicy="manual" id="editor"></div> <script> if ("virtualKeyboard" in navigator) { navigator.virtualKeyboard.overlaysContent = true; const editor = document.getElementById("editor"); editor.addEventListener("dblclick", () => { navigator.virtualKeyboard.show(); }); } </script> ``` ## Interfaces - {{domxref('VirtualKeyboard')}} {{experimental_inline}} - : Provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. ## Extensions to other interfaces - {{domxref("Navigator.virtualKeyboard")}} {{ReadOnlyInline}} {{experimental_inline}} - : Returns a reference to the {{DOMxRef("VirtualKeyboard")}} API, to take control of the on-screen virtual keyboard. - {{domxref("HTMLElement.virtualkeyboardpolicy")}} {{experimental_inline}} - : A string indicating whether to use the browser's default policy for showing the virtual keyboard when the element is focused, or to handle showing the virtual keyboard manually. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Full control with the VirtualKeyboard API](https://developer.chrome.com/docs/web-platform/virtual-keyboard/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/readablestream/index.md
--- title: ReadableStream slug: Web/API/ReadableStream page-type: web-api-interface browser-compat: api.ReadableStream --- {{APIRef("Streams")}} The `ReadableStream` interface of the [Streams API](/en-US/docs/Web/API/Streams_API) represents a readable stream of byte data. The [Fetch API](/en-US/docs/Web/API/Fetch_API) offers a concrete instance of a `ReadableStream` through the {{domxref("Response.body", "body")}} property of a {{domxref("Response")}} object. `ReadableStream` is a [transferable object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects). ## Constructor - {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} - : Creates and returns a readable stream object from the given handlers. ## Instance properties - {{domxref("ReadableStream.locked")}} {{ReadOnlyInline}} - : Returns a boolean indicating whether or not the readable stream is locked to a reader. ## Static methods - {{domxref("ReadableStream/from_static", "ReadableStream.from()")}} {{Experimental_Inline}} - : Returns `ReadableStream` from a provided iterable or async iterable object, such as an array, a set, an async generator, and so on. ## Instance methods - {{domxref("ReadableStream.cancel()")}} - : Returns a {{jsxref("Promise")}} that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied `reason` argument will be given to the underlying source, which may or may not use it. - {{domxref("ReadableStream.getReader()")}} - : Creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. - {{domxref("ReadableStream.pipeThrough()")}} - : Provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. - {{domxref("ReadableStream.pipeTo()")}} - : Pipes the current ReadableStream to a given {{domxref("WritableStream")}} and returns a {{jsxref("Promise")}} that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - {{domxref("ReadableStream.tee()")}} - : The `tee` method [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) this readable stream, returning a two-element array containing the two resulting branches as new `ReadableStream` instances. Each of those streams receives the same incoming data. ## Async iteration `ReadableStream` implements the [async iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). This enables asynchronous iteration over the chunks in a stream using the [`for await...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) syntax: ```js const stream = new ReadableStream(getSomeSource()); for await (const chunk of stream) { // Do something with each 'chunk' } ``` The async iterator consumes the stream until it runs out of data or otherwise terminates. The loop can also exit early due to a `break`, `throw`, or `return` statement. While iterating, the stream is locked to prevent other consumers from acquiring a reader (attempting to iterate over a stream that is already locked will throw a `TypeError`). This lock is released when the loop exits. By default, exiting the loop will also cancel the stream, so that it can no longer be used. To continue to use a stream after exiting the loop, pass `{ preventCancel: true }` to the stream's `values()` method: ```js for await (const chunk of stream.values({ preventCancel: true })) { // Do something with 'chunk' break; } // Acquire a reader for the stream and continue reading ... ``` ## Examples ### Fetch stream In the following example, an artificial {{domxref("Response")}} is created to stream HTML fragments fetched from another resource to the browser. It demonstrates the usage of a `ReadableStream` in combination with a {{jsxref("Uint8Array")}}. ```js fetch("https://www.example.org") .then((response) => response.body) .then((rb) => { const reader = rb.getReader(); return new ReadableStream({ start(controller) { // The following function handles each data chunk function push() { // "done" is a Boolean and value a "Uint8Array" reader.read().then(({ done, value }) => { // If there is no more data to read if (done) { console.log("done", done); controller.close(); return; } // Get the data and send it to the browser via the controller controller.enqueue(value); // Check chunks by logging to the console console.log(done, value); push(); }); } push(); }, }); }) .then((stream) => // Respond with our stream new Response(stream, { headers: { "Content-Type": "text/html" } }).text(), ) .then((result) => { // Do things with result console.log(result); }); ``` ### Convert an iterator or async iterator to a stream The {{domxref("ReadableStream/from_static", "from()")}} static method can convert an iterator, such as an {{jsxref("Array")}} or {{jsxref("Map")}}, or an [(async) iterator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) to a readable stream: ```js const myReadableStream = ReadableStream.from(iteratorOrAsyncIterator); ``` On browsers that don't support the `from()` method you can instead create your own [custom readable stream](/en-US/docs/Web/API/Streams_API/Using_readable_streams#creating_your_own_custom_readable_stream) to achieve the same result: ```js function iteratorToStream(iterator) { return new ReadableStream({ async pull(controller) { const { value, done } = await iterator.next(); if (done) { controller.close(); } else { controller.enqueue(value); } }, }); } ``` ### Async iteration of a stream using for await...of This example shows how you can process the `fetch()` response using a [`for await...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) loop to iterate through the arriving chunks. ```js const response = await fetch("https://www.example.org"); let total = 0; // Iterate response.body (a ReadableStream) asynchronously for await (const chunk of response.body) { // Do something with each chunk // Here we just accumulate the size of the response. total += chunk.length; } // Do something with the total console.log(total); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Streams API concepts](/en-US/docs/Web/API/Streams_API) - [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams) - [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams) - [WHATWG Stream Visualizer](https://whatwg-stream-visualizer.glitch.me/), for a basic visualization of readable, writable, and transform streams. - [Web-streams-polyfill](https://github.com/MattiasBuelens/web-streams-polyfill) or [sd-streams](https://github.com/stardazed/sd-streams) - polyfills
0
data/mdn-content/files/en-us/web/api/readablestream
data/mdn-content/files/en-us/web/api/readablestream/from_static/index.md
--- title: "ReadableStream: from() static method" short-title: from() slug: Web/API/ReadableStream/from_static page-type: web-api-static-method status: - experimental browser-compat: api.ReadableStream.from_static --- {{APIRef("Streams")}}{{SeeCompatTable}} The **`ReadableStream.from()`** static method returns a {{domxref("ReadableStream")}} from a provided iterable or async iterable object. The method can be used to wrap iterable and async iterable objects as readable streams, including arrays, sets, arrays of promises, async generators, `ReadableStreams`, Node.js `readable` streams, and so on. ## Syntax ```js-nolint ReadableStream.from(anyIterable) ``` ### Parameters - `anyIterable` - : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or [async iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) object. ### Return value A {{domxref("ReadableStream")}}. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the passed parameter is not an iterable or async iterable (does not define the `@@iterator` or `@@asyncIterator` method). Also thrown if, during iteration, the result of the next step is not an object or is a promise that does not resolve to an object. ## Examples ### Convert an async iterator to a ReadableStream This live example demonstrates how you can convert an async iterable to a `ReadableStream`, and then how this stream might be consumed. #### HTML The HTML is consists of single `<pre>` element, which is used for logging. ```html <pre id="log"></pre> ``` #### JavaScript The example code creates a `log()` function to write to the log HTML element. ```js const logElement = document.getElementById("log"); function log(text) { logElement.innerText += `${text}\n`; } ``` It then checks if the static method is supported, and if not, logs the result. ```js if (!ReadableStream.from) { log("ReadableStream.from() is not supported"); } ``` The async iterable is an anonymous generator function that yields the values of 1, 2 and 3 when it is called three times. This is passed to `ReadableStream.from()` to create the `ReadableStream`. ```js // Define an asynchronous iterator const asyncIterator = (async function* () { yield 1; yield 2; yield 3; })(); // Create ReadableStream from iterator const myReadableStream = ReadableStream.from(asyncIterator); ``` [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams) demonstrates several ways to consume a stream. The code below uses a `for ...await` loop, as this method is the simplest. Each iteration of the loop logs the current chunk from the stream. ```js consumeStream(myReadableStream); // Iterate a ReadableStream asynchronously async function consumeStream(readableStream) { for await (const chunk of myReadableStream) { // Do something with each chunk // Here we just log the values log(`chunk: ${chunk}`); } } ``` #### Result The output of consuming the stream is shown below (if `ReadableStream.from()` is supported). {{EmbedLiveSample("Convert an async iterator to a ReadableStream","100%", "80")}} ### Convert an Array to a ReadableStream This example demonstrates how you can convert an `Array` to a `ReadableStream`. ```html hidden <pre id="log"></pre> ``` ```js hidden const logElement = document.getElementById("log"); function log(text) { logElement.innerText += `${text}\n`; } if (!ReadableStream.from) { log("ReadableStream.from() is not supported"); } ``` #### JavaScript The iterable is just an array of strings that is passed to `ReadableStream.from()` to create the `ReadableStream`. ```js // An Array of vegetable names const vegetables = ["Carrot", "Broccoli", "Tomato", "Spinach"]; // Create ReadableStream from the Array const myReadableStream = ReadableStream.from(vegetables); ``` ```js hidden consumeStream(myReadableStream); // Iterate a ReadableStream asynchronously async function consumeStream(readableStream) { for await (const chunk of myReadableStream) { // Do something with each chunk // Here we just log the values log(`chunk: ${chunk}`); } } ``` We use the same approach as in the previous example log and to consume the stream, so that is not shown here. #### Result The output is shown below. {{EmbedLiveSample("Convert an Array to a ReadableStream","100%", "100")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ReadableStream")}} - [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
0
data/mdn-content/files/en-us/web/api/readablestream
data/mdn-content/files/en-us/web/api/readablestream/pipeto/index.md
--- title: "ReadableStream: pipeTo() method" short-title: pipeTo() slug: Web/API/ReadableStream/pipeTo page-type: web-api-instance-method browser-compat: api.ReadableStream.pipeTo --- {{APIRef("Streams")}} The **`pipeTo()`** method of the {{domxref("ReadableStream")}} interface pipes the current `ReadableStream` to a given {{domxref("WritableStream")}} and returns a {{jsxref("Promise")}} that fulfills when the piping process completes successfully, or rejects if any errors were encountered. Piping a stream will generally [lock](/en-US/docs/Web/API/ReadableStream/locked) it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js-nolint pipeTo(destination) pipeTo(destination, options) ``` ### Parameters - `destination` - : A {{domxref("WritableStream")}} that acts as the final destination for the {{domxref("ReadableStream")}}. - `options` {{optional_inline}} - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, the source `ReadableStream` closing will no longer cause the destination `WritableStream` to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. In this case the method will return a promise rejected with the source's error, or with any error that occurs during canceling the source. In addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. In this case the method will return a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - `signal` - : If set to an [`AbortSignal`](/en-US/docs/Web/API/AbortSignal) object, ongoing pipe operations can then be aborted via the corresponding [`AbortController`](/en-US/docs/Web/API/AbortController). ### Return value A {{jsxref("Promise")}} that resolves when the piping process has completed. ### Exceptions - {{jsxref("TypeError")}} - : The `writableStream` and/or `readableStream` objects are not a writable stream/readable stream, or one or both of the streams are locked. ## Examples ```js // Fetch the original image fetch("png-logo.png") // Retrieve its body as ReadableStream .then((response) => response.body) .then((body) => body.pipeThrough(new PNGTransformStream())) .then((rs) => rs.pipeTo(new FinalDestinationStream())); ``` The same example, but using {{jsxref("Operators/await", "await")}}: ```js (async () => { // Fetch the original image const response = await fetch("png-logo.png"); // Retrieve its body as ReadableStream response.body .pipeThrough(new PNGTransformStream()) .pipeTo(new FinalDestinationStream()); })(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor - [Pipe chains](/en-US/docs/Web/API/Streams_API/Using_readable_streams#pipe_chains)
0
data/mdn-content/files/en-us/web/api/readablestream
data/mdn-content/files/en-us/web/api/readablestream/locked/index.md
--- title: "ReadableStream: locked property" short-title: locked slug: Web/API/ReadableStream/locked page-type: web-api-instance-property browser-compat: api.ReadableStream.locked --- {{APIRef("Streams")}} The **`locked`** read-only property of the {{domxref("ReadableStream")}} interface returns whether or not the readable stream is locked to a reader. A readable stream can have at most one active reader at a time, and is locked to that reader until it is released. A reader might be obtained using [`ReadableStream.getReader()`](/en-US/docs/Web/API/ReadableStream/getReader) and released using the reader's `releaseLock()` method. ## Value A {{Glossary("boolean")}} value indicating whether or not the readable stream is locked. ## Examples ```js const stream = new ReadableStream({ // ... }); const reader = stream.getReader(); stream.locked; // should return true, as the stream has been locked to a reader ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor - [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
0
data/mdn-content/files/en-us/web/api/readablestream
data/mdn-content/files/en-us/web/api/readablestream/readablestream/index.md
--- title: "ReadableStream: ReadableStream() constructor" short-title: ReadableStream() slug: Web/API/ReadableStream/ReadableStream page-type: web-api-constructor browser-compat: api.ReadableStream.ReadableStream --- {{APIRef("Streams")}} The **`ReadableStream()`** constructor creates and returns a readable stream object from the given handlers. Note that while all parameters are technically optional, omitting the `underlyingSource` will result in a stream that has no source, and that can't be read from (readers return a promise that will never be resolved). ## Syntax ```js-nolint new ReadableStream() new ReadableStream(underlyingSource) new ReadableStream(underlyingSource, queuingStrategy) ``` ### Parameters - `underlyingSource` {{optional_inline}} - : An object containing methods and properties that define how the constructed stream instance will behave. `underlyingSource` can contain the following: - `start` (controller) {{optional_inline}} - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream functionality. If this process is to be done asynchronously, it can return a promise to signal success or failure. The `controller` parameter passed to this method is a {{domxref("ReadableStreamDefaultController")}} or a {{domxref("ReadableByteStreamController")}}, depending on the value of the `type` property. This can be used by the developer to control the stream during set up. - `pull` (controller) {{optional_inline}} - : This method, also defined by the developer, will be called repeatedly when the stream's internal queue of chunks is not full, up until it reaches its high water mark. If `pull()` returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. The `controller` parameter passed to this method is a {{domxref("ReadableStreamDefaultController")}} or a {{domxref("ReadableByteStreamController")}}, depending on the value of the `type` property. This can be used by the developer to control the stream as more chunks are fetched. This function will not be called until `start()` successfully completes. Additionally, it will only be called repeatedly if it enqueues at least one chunk or fulfills a BYOB request; a no-op `pull()` implementation will not be continually called. - `cancel` (reason) {{optional_inline}} - : This method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if {{domxref("ReadableStream.cancel()")}} is called). The contents should do whatever is necessary to release access to the stream source. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was cancelled. - `type` {{optional_inline}} - : This property controls what type of readable stream is being dealt with. If it is included with a value set to `"bytes"`, the passed controller object will be a {{domxref("ReadableByteStreamController")}} capable of handling a BYOB (bring your own buffer)/byte stream. If it is not included, the passed controller will be a {{domxref("ReadableStreamDefaultController")}}. - `autoAllocateChunkSize` {{optional_inline}} - : For byte streams, the developer can set the `autoAllocateChunkSize` with a positive integer value to turn on the stream's auto-allocation feature. With this is set, the stream implementation will automatically allocate a view buffer of the specified size in {{domxref("ReadableByteStreamController.byobRequest")}} when required. This must be set to enable zero-copy transfers to be used with a default {{domxref("ReadableStreamDefaultReader")}}. If not set, a default reader will still stream data, but {{domxref("ReadableByteStreamController.byobRequest")}} will always be `null` and transfers to the consumer must be via the stream's internal queues. - `queuingStrategy` {{optional_inline}} - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer β€” this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` β€” this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > {{domxref("ByteLengthQueuingStrategy")}} or {{domxref("CountQueuingStrategy")}} > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of > 1\. ### Return value An instance of the {{domxref("ReadableStream")}} object. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if the supplied type value is neither `"bytes"` nor `undefined`. ## Examples In the following simple example, a custom `ReadableStream` is created using a constructor (see our [Simple random stream example](https://mdn.github.io/dom-examples/streams/simple-random-stream/) for the full code). The `start()` function generates a random string of text every second and enqueues it into the stream. A `cancel()` function is also provided to stop the generation if {{domxref("ReadableStream.cancel()")}} is called for any reason. When a button is pressed, the generation is stopped, the stream is closed using {{domxref("ReadableStreamDefaultController.close()")}}, and another function is run, which reads the data back out of the stream. ```js let interval; const stream = new ReadableStream({ start(controller) { interval = setInterval(() => { let string = randomChars(); // Add the string to the stream controller.enqueue(string); // show it on the screen let listItem = document.createElement("li"); listItem.textContent = string; list1.appendChild(listItem); }, 1000); button.addEventListener("click", () => { clearInterval(interval); fetchStream(); controller.close(); }); }, pull(controller) { // We don't really need a pull in this example }, cancel() { // This is called if the reader cancels, // so we should stop generating strings clearInterval(interval); }, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ReadableStream")}} - {{domxref("ReadableByteStreamController")}} - {{domxref("ReadableStreamDefaultController")}} - [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams)
0
data/mdn-content/files/en-us/web/api/readablestream
data/mdn-content/files/en-us/web/api/readablestream/pipethrough/index.md
--- title: "ReadableStream: pipeThrough() method" short-title: pipeThrough() slug: Web/API/ReadableStream/pipeThrough page-type: web-api-instance-method browser-compat: api.ReadableStream.pipeThrough --- {{APIRef("Streams")}} The **`pipeThrough()`** method of the {{domxref("ReadableStream")}} interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. Piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. ## Syntax ```js-nolint pipeThrough(transformStream) pipeThrough(transformStream, options) ``` ### Parameters - `transformStream` - : A {{domxref("TransformStream")}} (or an object with the structure `{writable, readable}`) consisting of a readable stream and a writable stream working together to transform some data from one form to another. Data written to the `writable` stream can be read in some transformed state by the `readable` stream. For example, a {{domxref("TextDecoder")}}, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. - `options` {{optional_inline}} - : The options that should be used when piping to the `writable` stream. Available options are: - `preventClose` - : If this is set to `true`, closing the source `ReadableStream` will no longer cause the destination `WritableStream` to be closed. - `preventAbort` - : If this is set to `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. - `preventCancel` - : If this is set to `true`, errors in the destination `WritableStream` will no longer cancel the source `ReadableStream`. - `signal` - : If set to an [`AbortSignal`](/en-US/docs/Web/API/AbortSignal) object, ongoing pipe operations can then be aborted via the corresponding [`AbortController`](/en-US/docs/Web/API/AbortController). ### Return value The `readable` side of the `transformStream`. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the `writable` and/or `readable` property of `transformStream` are undefined. ## Examples In the following example (see [Unpack chunks of a PNG](https://mdn.github.io/dom-examples/streams/png-transform-stream/) for the full code running live, and [png-transform-stream](https://github.com/mdn/dom-examples/tree/main/streams/png-transform-stream) for the source code), an image is fetched and its body retrieved as a {{domxref("ReadableStream")}}. Next, we log the contents of the readable stream, use `pipeThrough()` to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. ```js // Fetch the original image fetch("png-logo.png") // Retrieve its body as ReadableStream .then((response) => response.body) .then((rs) => logReadableStream("Fetch Response Stream", rs)) // Create a gray-scaled PNG stream out of the original .then((body) => body.pipeThrough(new PNGTransformStream())) .then((rs) => logReadableStream("PNG Chunk Stream", rs)); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor - [Pipe chains](/en-US/docs/Web/API/Streams_API/Using_readable_streams#pipe_chains)
0
data/mdn-content/files/en-us/web/api/readablestream
data/mdn-content/files/en-us/web/api/readablestream/getreader/index.md
--- title: "ReadableStream: getReader() method" short-title: getReader() slug: Web/API/ReadableStream/getReader page-type: web-api-instance-method browser-compat: api.ReadableStream.getReader --- {{APIRef("Streams")}} The **`getReader()`** method of the {{domxref("ReadableStream")}} interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. ## Syntax ```js-nolint getReader() getReader(options) ``` ### Parameters - `options` {{optional_inline}} - : An object containing the following properties: - `mode` {{optional_inline}} - : An property that specifies the type of reader to create. Values can be: - `"byob"`, which results in a {{domxref("ReadableStreamBYOBReader")}} being created that can read readable byte streams (streams that support zero-copy transfer from an underlying byte source to the reader when internal stream buffers are empty). - `undefined` (or not specified at all β€” this is the default), which results in a {{domxref("ReadableStreamDefaultReader")}} being created that can read individual chunks from a stream. ### Return value A {{domxref("ReadableStreamDefaultReader")}} or {{domxref("ReadableStreamBYOBReader")}} object instance, depending on the `mode` value. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if the provided mode value is not `"byob"` or `undefined`. - {{jsxref("TypeError")}} - : Thrown if the stream you are trying to create a reader for is already locked, or not a {{domxref("ReadableStream")}}. This is also thrown if a BYOB reader is requested and the stream controller is not a {{domxref("ReadableByteStreamController")}} (the stream was not [constructed](/en-US/docs/Web/API/ReadableStream/ReadableStream) as an underlying source with [`type="bytes"`](/en-US/docs/Web/API/ReadableStream/ReadableStream#type)). ## Examples In the following simple example, a previously-created custom `ReadableStream` is read using a {{domxref("ReadableStreamDefaultReader")}} created using `getReader()`. (see our [Simple random stream example](https://mdn.github.io/dom-examples/streams/simple-random-stream/) for the full code). Each chunk is read sequentially and output to the UI, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI. ```js function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = value; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement("li"); listItem.textContent = `Received ${charsReceived} characters so far. Current chunk = ${chunk}`; list2.appendChild(listItem); result += chunk; // Read some more, and call this function again return reader.read().then(processText); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor - {{domxref("ReadableStreamDefaultReader")}} - {{domxref("ReadableStreamBYOBReader")}} - [Using readable streams](/en-US/docs/Web/API/Streams_API/Using_readable_streams) - [Using readable byte stream](/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams)
0