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/audiolistener
data/mdn-content/files/en-us/web/api/audiolistener/upy/index.md
--- title: "AudioListener: upY property" short-title: upY slug: Web/API/AudioListener/upY page-type: web-api-instance-property browser-compat: api.AudioListener.upY --- {{ APIRef("Web Audio API") }} The `upY` read-only property of the {{ domxref("AudioListener") }} interface is an {{domxref("AudioParam")}} representing the y value of the direction vector defining the up direction the listener is pointing in. > **Note:** The parameter is _a-rate_ when used with a {{domxref("PannerNode")}} whose {{domxref("PannerNode.panningModel", "PannerNode")}} is set to equalpower, or _k-rate_ otherwise. ## Value An {{domxref("AudioParam")}}. Its default value is 1, and it can range between positive and negative infinity. ## Examples See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code. ## 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/audiolistener
data/mdn-content/files/en-us/web/api/audiolistener/positionx/index.md
--- title: "AudioListener: positionX property" short-title: positionX slug: Web/API/AudioListener/positionX page-type: web-api-instance-property browser-compat: api.AudioListener.positionX --- {{ APIRef("Web Audio API") }} The `positionX` read-only property of the {{ domxref("AudioListener") }} interface is an {{domxref("AudioParam")}} representing the x position of the listener in 3D cartesian space. > **Note:** The parameter is _a-rate_ when used with a {{domxref("PannerNode")}} whose {{domxref("PannerNode.panningModel", "PannerNode")}} is set to equalpower, or _k-rate_ otherwise. ## Value An {{domxref("AudioParam")}}. Its default value is 0, and it can range between positive and negative infinity. ## Examples See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code. ## 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/audiolistener
data/mdn-content/files/en-us/web/api/audiolistener/positiony/index.md
--- title: "AudioListener: positionY property" short-title: positionY slug: Web/API/AudioListener/positionY page-type: web-api-instance-property browser-compat: api.AudioListener.positionY --- {{ APIRef("Web Audio API") }} The `positionY` read-only property of the {{ domxref("AudioListener") }} interface is an {{domxref("AudioParam")}} representing the y position of the listener in 3D cartesian space. > **Note:** The parameter is _a-rate_ when used with a {{domxref("PannerNode")}} whose {{domxref("PannerNode.panningModel", "PannerNode")}} is set to equalpower, or _k-rate_ otherwise. ## Value An {{domxref("AudioParam")}}. Its default value is 0, and it can range between positive and negative infinity. ## Examples See [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples) for example code. ## 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/audiolistener
data/mdn-content/files/en-us/web/api/audiolistener/upx/index.md
--- title: "AudioListener: upX property" short-title: upX slug: Web/API/AudioListener/upX page-type: web-api-instance-property browser-compat: api.AudioListener.upX --- {{ APIRef("Web Audio API") }} The `upX` read-only property of the {{ domxref("AudioListener") }} interface is an {{domxref("AudioParam")}} representing the x value of the direction vector defining the up direction the listener is pointing in. > **Note:** The parameter is _a-rate_ when used with a {{domxref("PannerNode")}} whose {{domxref("PannerNode.panningModel", "PannerNode")}} is set to equalpower, or _k-rate_ otherwise. ## Value An {{domxref("AudioParam")}}. Its default value is 0, and it can range between positive and negative infinity. ## Examples For more detailed example code see [`BaseAudioContext.createPanner()`](/en-US/docs/Web/API/BaseAudioContext/createPanner#examples). ## 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
data/mdn-content/files/en-us/web/api/xmlhttprequestupload/index.md
--- title: XMLHttpRequestUpload slug: Web/API/XMLHttpRequestUpload page-type: web-api-interface browser-compat: api.XMLHttpRequestUpload --- {{APIRef("XMLHttpRequest API")}} The **`XMLHttpRequestUpload`** interface represents the upload process for a specific {{domxref("XMLHttpRequest")}}. It is an _opaque_ object that represents the underlying, browser-dependent, upload process. It is an {{domxref("XMLHttpRequestEventTarget")}} and can be obtained by calling {{domxref("XMLHttpRequest.upload")}}. {{AvailableInWorkers("notservice")}} {{InheritanceDiagram}} ## Instance properties _This interface has no specific property, but inherits the properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}._ ## Instance methods _This interface has no specific method, but inherits the methods of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}._ ## Events - {{domxref("XMLHttpRequestUpload/abort_event", "abort")}} - : Fired when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}. Also available via the `onabort` event handler property. - {{domxref("XMLHttpRequestUpload/error_event", "error")}} - : Fired when the request encountered an error. Also available via the `onerror` event handler property. - {{domxref("XMLHttpRequestUpload/load_event", "load")}} - : Fired when a request transaction completes successfully. Also available via the `onload` event handler property. - {{domxref("XMLHttpRequestUpload/loadend_event", "loadend")}} - : Fired when a request has completed, whether successfully (after {{domxref("XMLHttpRequest/load_event", "load")}}) or unsuccessfully (after {{domxref("XMLHttpRequestUpload/abort_event", "abort")}} or {{domxref("XMLHttpRequest/error_event", "error")}}). Also available via the `onloadend` event handler property. - {{domxref("XMLHttpRequestUpload/loadstart_event", "loadstart")}} - : Fired when a request has started to load data. Also available via the `onloadstart` event handler property. - {{domxref("XMLHttpRequestUpload/progress_event", "progress")}} - : Fired periodically when a request receives more data. Also available via the `onprogress` event handler property. - {{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}} - : Fired when progress is terminated due to preset time expiring. Also available via the `ontimeout` event handler property. ## Examples ### Uploading a file with a timeout This allows you to upload a file to a server; it displays a progress bar while the upload is happening as well as a message with the progress and the results, success or failure. An abort button allows to stop an upload. #### HTML ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>XMLHttpRequestUpload test</title> <link rel="stylesheet" href="xhrupload_test.css" /> <script src="xhrupload_test.js"></script> </head> <body> <main> <h1>Upload a file</h1> <p> <label for="file">File to upload</label><input type="file" id="file" /> </p> <p> <progress /> </p> <p> <output></output> </p> <p> <button disabled id="abort">Abort</button> </p> </main> </body> </html> ``` #### CSS ```css body { background-color: lightblue; } main { margin: 50px auto; text-align: center; } #file { display: none; } label[for="file"] { background-color: lightgrey; padding: 10px 10px; } progress { display: none; } progress.visible { display: inline; } ``` #### JavaScript ```js addEventListener("DOMContentLoaded", () => { const fileInput = document.getElementById("file"); const progressBar = document.querySelector("progress"); const log = document.querySelector("output"); const abortButton = document.getElementById("abort"); fileInput.addEventListener("change", () => { const xhr = new XMLHttpRequest(); xhr.timeout = 2000; // 2 seconds // Link abort button abortButton.addEventListener( "click", () => { xhr.abort(); }, { once: true }, ); // When the upload starts, we display the progress bar xhr.upload.addEventListener("loadstart", (event) => { progressBar.classList.add("visible"); progressBar.value = 0; progressBar.max = event.total; log.textContent = "Uploading (0%)…"; abortButton.disabled = false; }); // Each time a progress event is received, we update the bar xhr.upload.addEventListener("progress", (event) => { progressBar.value = event.loaded; log.textContent = `Uploading (${( (event.loaded / event.total) * 100 ).toFixed(2)}%)…`; }); // When the upload is finished, we hide the progress bar. xhr.upload.addEventListener("loadend", (event) => { progressBar.classList.remove("visible"); if (event.loaded !== 0) { log.textContent = "Upload finished."; } abortButton.disabled = true; }); // In case of an error, an abort, or a timeout, we hide the progress bar // Note that these events can be listened to on the xhr object too function errorAction(event) { progressBar.classList.remove("visible"); log.textContent = `Upload failed: ${event.type}`; } xhr.upload.addEventListener("error", errorAction); xhr.upload.addEventListener("abort", errorAction); xhr.upload.addEventListener("timeout", errorAction); // Build the payload const fileData = new FormData(); fileData.append("file", fileInput.files[0]); // Theoretically, event listeners could be set after the open() call // but browsers are buggy here xhr.open("POST", "upload_test.php", true); // Note that the event listener must be set before sending (as it is a preflighted request) xhr.send(fileData); }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XMLHttpRequest")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequestupload
data/mdn-content/files/en-us/web/api/xmlhttprequestupload/abort_event/index.md
--- title: "XMLHttpRequestUpload: abort event" short-title: abort slug: Web/API/XMLHttpRequestUpload/abort_event page-type: web-api-event browser-compat: api.XMLHttpRequestUpload.abort_event --- {{APIRef("XMLHttpRequest API")}} The `abort` event is fired at {{domxref("XMLHttpRequestUpload")}} when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("abort", (event) => {}); onabort = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead. ## Examples ### Using the `abort` event You can use the `abort` event to stop the upload before it finishes. For a complete code example that uploads a file and displays a progress bar, see the main {{domxref("XMLHttpRequestUpload")}} page. ```js // In case of an abort we hide the progress bar // Note that this event can be listened to on the xhr object too function errorAction(event) { progressBar.classList.remove("visible"); log.textContent = `Upload failed: ${event.type}`; } xhr.upload.addEventListener("abort", errorAction); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequestUpload/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequestUpload/load_event", "load")}}, {{domxref("XMLHttpRequestUpload/progress_event", "progress")}}, {{domxref("XMLHttpRequestUpload/error_event", "error")}}, {{domxref("XMLHttpRequestUpload/loadend_event", "loadend")}}, {{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}} - {{domxref("XMLHttpRequestUpload")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequestupload
data/mdn-content/files/en-us/web/api/xmlhttprequestupload/progress_event/index.md
--- title: "XMLHttpRequestUpload: progress event" short-title: progress slug: Web/API/XMLHttpRequestUpload/progress_event page-type: web-api-event browser-compat: api.XMLHttpRequestUpload.progress_event --- {{APIRef("XMLHttpRequest API")}} The **`progress`** event is fired periodically when a request receives more data. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("progress", (event) => {}); onprogress = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead. ## Examples ## Using the `progress` event You can use the `progress` event to get info about the progress of a lengthy upload. For a complete code example that uploads a file and displays a progress bar, see the main {{domxref("XMLHttpRequestUpload")}} page. ```js // Each time a progress event is received we update the progress bar // and the progress message xhr.upload.addEventListener("progress", (event) => { progressBar.value = event.loaded; // Update the progress bar log.textContent = `Uploading (${((event.loaded / event.total) * 100).toFixed( 2, )}%)…`; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequestUpload/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequestUpload/load_event", "load")}}, {{domxref("XMLHttpRequestUpload/error_event", "error")}}, {{domxref("XMLHttpRequestUpload/loadend_event", "loadend")}}, {{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}}, {{domxref("XMLHttpRequestUpload/abort_event", "abort")}} - [Monitoring progress](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest#monitoring_progress) - {{domxref("XMLHttpRequestUpload")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequestupload
data/mdn-content/files/en-us/web/api/xmlhttprequestupload/loadstart_event/index.md
--- title: "XMLHttpRequestUpload: loadstart event" short-title: loadstart slug: Web/API/XMLHttpRequestUpload/loadstart_event page-type: web-api-event browser-compat: api.XMLHttpRequestUpload.loadstart_event --- {{APIRef("XMLHttpRequest API")}} The **`loadstart`** event is fired when a request has started to load data. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("loadstart", (event) => {}); onloadstart = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead. ## Examples ## Using the `loadstart` event You can use the `loadstart` event to detect the beginning of an upload. For a complete code example that uploads a file and displays a progress bar, see the main {{domxref("XMLHttpRequestUpload")}} page. ```js // When the upload starts, we display the progress bar xhr.upload.addEventListener("loadstart", (event) => { progressBar.classList.add("visible"); progressBar.value = 0; progressBar.max = event.total; log.textContent = "Uploading (0%)…"; abortButton.disabled = false; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequestUpload/load_event", "load")}}, {{domxref("XMLHttpRequestUpload/progress_event", "progress")}}, {{domxref("XMLHttpRequestUpload/error_event", "error")}}, {{domxref("XMLHttpRequestUpload/loadend_event", "loadend")}}, {{domxref("XMLHttpRequestUpload/abort_event", "abort")}}, {{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}} - {{domxref("XMLHttpRequestUpload")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequestupload
data/mdn-content/files/en-us/web/api/xmlhttprequestupload/loadend_event/index.md
--- title: "XMLHttpRequestUpload: loadend event" short-title: loadend slug: Web/API/XMLHttpRequestUpload/loadend_event page-type: web-api-event browser-compat: api.XMLHttpRequestUpload.loadend_event --- {{APIRef("XMLHttpRequest API")}} The **`loadend`** event is fired when a request has completed, whether successfully (after {{domxref("XMLHttpRequestUpload/load_event", "load")}}) or unsuccessfully (after {{domxref("XMLHttpRequestUpload/abort_event", "abort")}} or {{domxref("XMLHttpRequestUpload/error_event", "error")}}). The `loadend` event is also sent when the request has been interrupted (by a {{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}}, an {{domxref("XMLHttpRequestUpload/abort_event", "abort")}}, or an {{domxref("XMLHttpRequestUpload/error_event", "error")}}). In such cases, both the `loaded` and `total` value of the event will be 0. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("loadend", (event) => {}); onloadend = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead. ## Examples ## Using the `loadend` event You can use the `loadend` event to detect the (successful or not) termination of an upload. For a complete code example that uploads a file and displays a progress bar, see the main {{domxref("XMLHttpRequestUpload")}} page. ```js // When the upload is finished, we hide the progress bar. xhr.upload.addEventListener("loadend", (event) => { progressBar.classList.remove("visible"); if (event.loaded !== 0) { // Successful termination log.textContent = "Upload finished."; } abortButton.disabled = true; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequestUpload/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequestUpload/progress_event", "progress")}}, {{domxref("XMLHttpRequestUpload/error_event", "error")}}, {{domxref("XMLHttpRequestUpload/load_event", "load")}}, {{domxref("XMLHttpRequestUpload/abort_event", "abort")}}, {{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}} - {{domxref("XMLHttpRequestUpload")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequestupload
data/mdn-content/files/en-us/web/api/xmlhttprequestupload/timeout_event/index.md
--- title: "XMLHttpRequestUpload: timeout event" short-title: timeout slug: Web/API/XMLHttpRequestUpload/timeout_event page-type: web-api-event browser-compat: api.XMLHttpRequestUpload.timeout_event --- {{APIRef("XMLHttpRequest API")}} The **`timeout`** event is fired when progression is terminated due to preset time expiring. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("timeout", (event) => {}); ontimeout = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead. ## Examples ### Using the `timeout` event You can use the `timeout` event to detect an upload that stopped because it was too slow. For a complete code example that uploads a file and displays a progress bar, see the main {{domxref("XMLHttpRequestUpload")}} page. The timeout is set on the {{domxref("XMLHttpRequest")}} object using the {{domxref("XMLHttpRequest.timeout")}} property. ```js // In case of an timeout we hide the progress bar // Note that this event can be listened to on the xhr object too function errorAction(event) { progressBar.classList.remove("visible"); log.textContent = `Upload failed: ${event.type}`; } xhr.upload.addEventListener("timeout", errorAction); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequestUpload/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequestUpload/load_event", "load")}}, {{domxref("XMLHttpRequestUpload/progress_event", "progress")}}, {{domxref("XMLHttpRequestUpload/error_event", "error")}}, {{domxref("XMLHttpRequestUpload/loadend_event", "loadend")}}, {{domxref("XMLHttpRequestUpload/abort_event", "abort")}} - {{domxref("XMLHttpRequestUpload")}} - {{domxref("XMLHttpRequest.timeout")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequestupload
data/mdn-content/files/en-us/web/api/xmlhttprequestupload/load_event/index.md
--- title: "XMLHttpRequestUpload: load event" short-title: load slug: Web/API/XMLHttpRequestUpload/load_event page-type: web-api-event browser-compat: api.XMLHttpRequest.load_event --- {{APIRef("XMLHttpRequest API")}} The `load` event is fired when an {{domxref("XMLHttpRequestUpload")}} transaction completes successfully. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("load", (event) => {}); onload = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead. ### Examples ## Using the `load` event You can use the `load` event to detect the successful termination of an upload. For a complete code example that uploads a file and displays a progress bar, see the main {{domxref("XMLHttpRequestUpload")}} page. ```js // When the upload is finished, we hide the progress bar. xhr.upload.addEventListener("load", (event) => { progressBar.classList.remove("visible"); log.textContent = "Upload finished."; abortButton.disabled = true; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequestUpload/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequestUpload/progress_event", "progress")}}, {{domxref("XMLHttpRequestUpload/error_event", "error")}}, {{domxref("XMLHttpRequestUpload/loadend_event", "loadend")}}, {{domxref("XMLHttpRequestUpload/abort_event", "abort")}}, {{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}} - {{domxref("XMLHttpRequestUpload")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequestupload
data/mdn-content/files/en-us/web/api/xmlhttprequestupload/error_event/index.md
--- title: "XMLHttpRequestUpload: error event" short-title: error slug: Web/API/XMLHttpRequestUpload/error_event page-type: web-api-event browser-compat: api.XMLHttpRequestUpload.error_event --- {{APIRef("XMLHttpRequest API")}} The `error` event is fired when the request encountered an error. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("error", (event) => {}); onerror = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead. ## Examples ### Using the `error` event You can use the `error` event to detect a problem with the upload. For a complete code example that uploads a file and displays a progress bar, see the main {{domxref("XMLHttpRequestUpload")}} page. ```js // In case of an error we hide the progress bar // Note that this event can be listened to on the xhr object too function errorAction(event) { progressBar.classList.remove("visible"); log.textContent = `Upload failed: ${event.type}`; } xhr.upload.addEventListener("error", errorAction); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequestUpload/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequestUpload/load_event", "load")}}, {{domxref("XMLHttpRequestUpload/progress_event", "progress")}}, {{domxref("XMLHttpRequestUpload/abort_event", "abort")}}, {{domxref("XMLHttpRequestUpload/loadend_event", "loadend")}}, {{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}} - {{domxref("XMLHttpRequestUpload")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/audioparam/index.md
--- title: AudioParam slug: Web/API/AudioParam page-type: web-api-interface browser-compat: api.AudioParam --- {{APIRef("Web Audio API")}} The Web Audio API's `AudioParam` interface represents an audio-related parameter, usually a parameter of an {{domxref("AudioNode")}} (such as {{ domxref("GainNode.gain") }}). An `AudioParam` can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern. Each `AudioParam` has a list of events, initially empty, that define when and how values change. When this list is not empty, changes using the `AudioParam.value` attributes are ignored. This list of events allows us to schedule changes that have to happen at very precise times, using arbitrary timeline-based automation curves. The time used is the one defined in {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}. ## AudioParam types There are two `AudioParam` kinds: _a-rate_ and _k-rate_ parameters. Each {{domxref("AudioNode")}} defines which of its parameters are _a-rate_ or _k-rate_ in the spec. ### a-rate An _a-rate_ `AudioParam` takes the current audio parameter value for each [sample frame](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#audio_buffers_frames_samples_and_channels) of the audio signal. ### k-rate A _k-rate_ `AudioParam` uses the same initial audio parameter value for the whole block processed; that is, 128 sample frames. In other words, the same value applies to every frame in the audio as it's processed by the node. ## Instance properties - {{domxref("AudioParam.defaultValue")}} {{ReadOnlyInline}} - : Represents the initial value of the attribute as defined by the specific {{domxref("AudioNode")}} creating the `AudioParam`. - {{domxref("AudioParam.maxValue")}} {{ReadOnlyInline}} - : Represents the maximum possible value for the parameter's nominal (effective) range. - {{domxref("AudioParam.minValue")}} {{ReadOnlyInline}} - : Represents the minimum possible value for the parameter's nominal (effective) range. - {{domxref("AudioParam.value")}} - : Represents the parameter's current value as of the current time; initially set to the value of {{domxref("AudioParam.defaultValue", "defaultValue")}}. ## Instance methods - {{domxref("AudioParam.setValueAtTime()")}} - : Schedules an instant change to the value of the `AudioParam` at a precise time, as measured against {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}. The new value is given by the `value` parameter. - {{domxref("AudioParam.linearRampToValueAtTime()")}} - : Schedules a gradual linear change in the value of the `AudioParam`. The change starts at the time specified for the _previous_ event, follows a linear ramp to the new value given in the `value` parameter, and reaches the new value at the time given in the `endTime` parameter. - {{domxref("AudioParam.exponentialRampToValueAtTime()")}} - : Schedules a gradual exponential change in the value of the `AudioParam`. The change starts at the time specified for the _previous_ event, follows an exponential ramp to the new value given in the `value` parameter, and reaches the new value at the time given in the `endTime` parameter. - {{domxref("AudioParam.setTargetAtTime()")}} - : Schedules the start of a change to the value of the `AudioParam`. The change starts at the time specified in `startTime` and exponentially moves towards the value given by the `target` parameter. The exponential decay rate is defined by the `timeConstant` parameter, which is a time measured in seconds. - {{domxref("AudioParam.setValueCurveAtTime()")}} - : Schedules the values of the `AudioParam` to follow a set of values, defined by an array of floating-point numbers scaled to fit into the given interval, starting at a given start time and spanning a given duration of time. - {{domxref("AudioParam.cancelScheduledValues()")}} - : Cancels all scheduled future changes to the `AudioParam`. - {{domxref("AudioParam.cancelAndHoldAtTime()")}} - : Cancels all scheduled future changes to the `AudioParam` but holds its value at a given time until further changes are made using other methods. ## Examples First, a basic example showing a {{domxref("GainNode")}} having its `gain` value set. `gain` is an example of an _a-rate_ `AudioParam`, as the value can potentially be set differently for each sample frame of the audio. ```js const audioCtx = new AudioContext(); const gainNode = audioCtx.createGain(); gainNode.gain.value = 0; ``` Next, an example showing a {{ domxref("DynamicsCompressorNode") }} having some param values manipulated. These are examples of _k-rate_ `AudioParam` types, as the values are set for the entire audio block at once. ```js const compressor = audioCtx.createDynamicsCompressor(); compressor.threshold.setValueAtTime(-50, audioCtx.currentTime); compressor.knee.setValueAtTime(40, audioCtx.currentTime); compressor.ratio.setValueAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); ``` ## 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/audioparam
data/mdn-content/files/en-us/web/api/audioparam/cancelscheduledvalues/index.md
--- title: "AudioParam: cancelScheduledValues() method" short-title: cancelScheduledValues() slug: Web/API/AudioParam/cancelScheduledValues page-type: web-api-instance-method browser-compat: api.AudioParam.cancelScheduledValues --- {{ APIRef("Web Audio API") }} The `cancelScheduledValues()` method of the {{ domxref("AudioParam") }} Interface cancels all scheduled future changes to the `AudioParam`. ## Syntax ```js-nolint cancelScheduledValues(startTime) ``` ### Parameters - `startTime` - : A double representing the time (in seconds) after the {{ domxref("AudioContext") }} was first created after which all scheduled changes will be cancelled. ### Return value A reference to this `AudioParam` object. In some older implementations this method returns {{jsxref('undefined')}}. ## Examples ```js const gainNode = audioCtx.createGain(); gainNode.gain.setValueCurveAtTime(waveArray, audioCtx.currentTime, 2); //'gain' is the AudioParam gainNode.gain.cancelScheduledValues(audioCtx.currentTime); ``` ## 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/audioparam
data/mdn-content/files/en-us/web/api/audioparam/settargetattime/index.md
--- title: "AudioParam: setTargetAtTime() method" short-title: setTargetAtTime() slug: Web/API/AudioParam/setTargetAtTime page-type: web-api-instance-method browser-compat: api.AudioParam.setTargetAtTime --- {{ APIRef("Web Audio API") }} The `setTargetAtTime()` method of the {{domxref("AudioParam")}} interface schedules the start of a gradual change to the `AudioParam` value. This is useful for decay or release portions of ADSR envelopes. ## Syntax ```js-nolint setTargetAtTime(target, startTime, timeConstant) ``` ### Parameters - `target` - : The value the parameter will start to transition towards at the given start time. - `startTime` - : The time that the exponential transition will begin, in the same time coordinate system as {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}. If it is less than or equal to `AudioContext.currentTime`, the parameter will start changing immediately. - `timeConstant` - : The time-constant value, given in seconds, of an exponential approach to the target value. The larger this value is, the slower the transition will be. ### Return value A reference to this `AudioParam` object. Some older browser implementations of this interface return {{jsxref('undefined')}}. ## Description The change starts at the time specified in `startTime` and exponentially moves towards the value given by the `target` parameter. The decay rate as defined by the `timeConstant` parameter is exponential; therefore the value will never reach `target` completely, but after each timestep of length `timeConstant`, the value will have approached `target` by another <math> <semantics><mrow><mn>1</mn> <mo>-</mo> <msup><mi>e</mi> <mrow><mo>-</mo> <mn>1</mn> </mrow></msup><mo>≈</mo> <mn>63.2</mn> <mtext>%</mtext> </mrow><annotation encoding="TeX">1 - e^{-1} \approx 63.2%</annotation> </semantics></math>. For the complete formula (which uses a first-order linear continuous time-invariant system), check the [Web Audio specification](https://webaudio.github.io/web-audio-api/#dom-audioparam-settargetattime). If you absolutely need to reach the target value by a specific time, you can use {{domxref("AudioParam.exponentialRampToValueAtTime()")}}. However, for mathematical reasons, that method does not work if the current value or the target value is `0`. ### Choosing a good `timeConstant` As mentioned above, the value changes exponentially, with each `timeConstant` bringing you another 63.2% toward the target value. You don't have to worry about reaching the target value; once you are close enough, any further changes will be imperceptible to a human listener. Depending on your use case, getting 95% toward the target value may already be enough; in that case, you could set `timeConstant` to one third of the desired duration. For more details, check the following table on how the value changes from 0% to 100% as the time progresses. | Time since `startTime` | Value | | ---------------------- | --------------------------------- | | `0 * timeConstant` | 0% | | `0.5 * timeConstant` | 39.3% | | `1 * timeConstant` | 63.2% | | `2 * timeConstant` | 86.5% | | `3 * timeConstant` | 95.0% | | `4 * timeConstant` | 98.2% | | `5 * timeConstant` | 99.3% | | `n * timeConstant` | <math><semantics><mrow><mn>1</mn> | <math><semantics><mrow><mn>1</mn> <mo>-</mo> <msup><mi>e</mi> <mrow><mo>-</mo> <mi>n</mi> </mrow></msup></mrow><annotation encoding="TeX">1 - e^{-n}</annotation></semantics></math> ## Examples In this example, we have a media source with two control buttons (see the [webaudio-examples repo](https://github.com/mdn/webaudio-examples/blob/main/audio-param/index.html) for the source code, or [view the example live](https://mdn.github.io/webaudio-examples/audio-param/).) When these buttons are pressed, `setTargetAtTime()` is used to fade the gain value up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeConstant. ```js // create audio context const audioCtx = new AudioContext(); // set basic variables for example const myAudio = document.querySelector("audio"); const atTimePlus = document.querySelector(".at-time-plus"); const atTimeMinus = document.querySelector(".at-time-minus"); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it const source = audioCtx.createMediaElementSource(myAudio); // Create a gain node and set it's gain value to 0.5 const gainNode = audioCtx.createGain(); gainNode.gain.value = 0.5; let currGain = gainNode.gain.value; // connect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination source.connect(gainNode); gainNode.connect(audioCtx.destination); // set buttons to do something onclick atTimePlus.onclick = () => { currGain = 1.0; gainNode.gain.setTargetAtTime(1.0, audioCtx.currentTime + 1, 0.5); }; atTimeMinus.onclick = () => { currGain = 0; gainNode.gain.setTargetAtTime(0, audioCtx.currentTime + 1, 0.5); }; ``` ## 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/audioparam
data/mdn-content/files/en-us/web/api/audioparam/minvalue/index.md
--- title: "AudioParam: minValue property" short-title: minValue slug: Web/API/AudioParam/minValue page-type: web-api-instance-property browser-compat: api.AudioParam.minValue --- {{APIRef("Web Audio API")}} The **`minValue`** read-only property of the {{domxref("AudioParam")}} interface represents the minimum possible value for the parameter's nominal (effective) range. ## Value A floating-point {{jsxref("Number")}} indicating the minimum value permitted for the parameter's nominal range. The default value of `minValue` is the minimum negative single-precision floating-point value (-340,282,346,638,528,859,811,704,183,484,516,925,440). ## Examples ```js const audioCtx = new AudioContext(); const gainNode = audioCtx.createGain(); console.log(gainNode.gain.minValue); // -3.4028234663852886e38 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("AudioParam.maxValue")}}
0
data/mdn-content/files/en-us/web/api/audioparam
data/mdn-content/files/en-us/web/api/audioparam/cancelandholdattime/index.md
--- title: "AudioParam: cancelAndHoldAtTime() method" short-title: cancelAndHoldAtTime() slug: Web/API/AudioParam/cancelAndHoldAtTime page-type: web-api-instance-method browser-compat: api.AudioParam.cancelAndHoldAtTime --- {{APIRef("Web Audio API")}} The **`cancelAndHoldAtTime()`** method of the {{domxref("AudioParam")}} interface cancels all scheduled future changes to the `AudioParam` but holds its value at a given time until further changes are made using other methods. ## Syntax ```js-nolint cancelAndHoldAtTime(cancelTime) ``` ### Parameters - `cancelTime` - : A double representing the time (in seconds) after the [`AudioContext`](/en-US/docs/Web/API/AudioContext) was first created after which all scheduled changes will be cancelled. ### Return value A reference to the {{domxref("AudioParam")}} it was called on. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audioparam
data/mdn-content/files/en-us/web/api/audioparam/value/index.md
--- title: "AudioParam: value property" short-title: value slug: Web/API/AudioParam/value page-type: web-api-instance-property browser-compat: api.AudioParam.value --- {{APIRef("Web Audio API")}} The [Web Audio API's](/en-US/docs/Web/API/Web_Audio_API) {{domxref("AudioParam")}} interface property **`value`** gets or sets the value of this {{domxref("AudioParam")}} at the current time. Initially, the value is set to {{domxref("AudioParam.defaultValue")}}. Setting `value` has the same effect as calling {{domxref("AudioParam.setValueAtTime")}} with the time returned by the `AudioContext`'s {{domxref("BaseAudioContext/currentTime", "currentTime")}} property. ## Value A floating-point {{jsxref("Number")}} indicating the parameter's value as of the current time. This value will be between the values specified by the {{domxref("AudioParam.minValue", "minValue")}} and {{domxref("AudioParam.maxValue", "maxValue")}} properties. ## Usage notes ### Value precision and variation The data type used internally to store `value` is a single-precision (32-bit) floating point number, while JavaScript uses 64-bit double-precision floating point numbers. As a result, the value you read from the `value` property may not always exactly equal what you set it to. Consider this example: ```js const source = new AudioBufferSourceNode(/* … */); const rate = 5.3; source.playbackRate.value = rate; console.log(source.playbackRate.value === rate); ``` The log output will be `false`, because the playback rate parameter, `rate`, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863. One solution is to use the {{jsxref("Math.fround()")}} method, which returns the single-precision value equivalent to the 64-bit JavaScript value specified—when setting `value`, like this: ```js const source = new AudioBufferSourceNode(/* … */); const rate = Math.fround(5.3); source.playbackRate.value = rate; console.log(source.playbackRate.value === rate); ``` In this case, the log output will be `true`. ### Value of a property which is changing over time The `value` of an `AudioParam` can either be fixed or can vary over time. This is reflected by the `value` getter, which returns the value of the parameter as of the audio rendering engine's most recent **render quantum**, or moment at which audio buffers are processed and updated. In addition to processing audio buffers, each render quantum updates the `value` of each `AudioParam` as needed given the current time and any established time-based parameter value changes. Upon first creating the parameter, its value is set to its default value, given by {{domxref("AudioParam.defaultValue")}}. This is the parameter's value at a time of 0.0 seconds, and will remain the parameter's value until the first render quantum in which the value is altered. During each render quantum, the browser does the following things related to managing the value of a parameter: - If the `value` setter has been used, the parameter's value is changed to the value given. - If the current time equals or exceeds the time specified by a previous call to {{domxref("AudioParam.setValueAtTime", "setValueAtTime()")}}, the `value` is changed to the value passed into `setValueAtTime()`. - If any graduated or ramped value changing methods have been called and the current time is within the time range over which the graduated change should occur, the value is updated based on the appropriate algorithm. These ramped or graduated value-changing methods include {{domxref("AudioParam.linearRampToValueAtTime", "linearRampToValueAtTime()")}}, {{domxref("AudioParam.setTargetAtTime", "setTargetAtTime()")}}, and {{domxref("AudioParam.setValueCurveAtTime", "setValueCurveAtTime()")}}. Thus, the `value` of a parameter is maintained to accurately reflect the state of the parameter over time. ## Examples This example instantly changes the volume of a {{domxref("GainNode")}} to 40%. ```js const audioCtx = new AudioContext(); const gainNode = audioCtx.createGain(); gainNode.gain.value = 0.4; // which is identical to: gainNode.gain.setValueAtTime(0.4, audioCtx.currentTime); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} When changing the gain value of a {{domxref("GainNode")}}, Google Chrome prior to version 64 (January 2018) would perform a smooth interpolation to prevent dezippering. Starting with version 64, the value is changed instantly to bring it in line with the Web Audio spec. See [Chrome Platform Status](https://chromestatus.com/feature/5287995770929152) for details. ## 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/audioparam
data/mdn-content/files/en-us/web/api/audioparam/defaultvalue/index.md
--- title: "AudioParam: defaultValue property" short-title: defaultValue slug: Web/API/AudioParam/defaultValue page-type: web-api-instance-property browser-compat: api.AudioParam.defaultValue --- {{APIRef("Web Audio API")}} The **`defaultValue`** read-only property of the {{ domxref("AudioParam") }} interface represents the initial value of the attributes as defined by the specific {{domxref("AudioNode")}} creating the `AudioParam`. ## Value A floating-point {{jsxref("Number")}}. ## Examples ```js const audioCtx = new AudioContext(); const gainNode = audioCtx.createGain(); const defaultVal = gainNode.gain.defaultValue; console.log(defaultVal); // 1 console.log(defaultVal === gainNode.gain.value); // true ``` ## 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/audioparam
data/mdn-content/files/en-us/web/api/audioparam/exponentialramptovalueattime/index.md
--- title: "AudioParam: exponentialRampToValueAtTime() method" short-title: exponentialRampToValueAtTime() slug: Web/API/AudioParam/exponentialRampToValueAtTime page-type: web-api-instance-method browser-compat: api.AudioParam.exponentialRampToValueAtTime --- {{ APIRef("Web Audio API") }} The **`exponentialRampToValueAtTime()`** method of the {{ domxref("AudioParam") }} Interface schedules a gradual exponential change in the value of the {{domxref("AudioParam")}}. The change starts at the time specified for the _previous_ event, follows an exponential ramp to the new value given in the `value` parameter, and reaches the new value at the time given in the `endTime` parameter. > **Note:** Exponential ramps are considered more useful when changing > frequencies or playback rates than linear ramps because of the way the human ear > works. ## Syntax ```js-nolint exponentialRampToValueAtTime(value, endTime) ``` ### Parameters - `value` - : A floating point number representing the value the `AudioParam` will ramp to by the given time. - `endTime` - : A double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop. ### Return value A reference to this `AudioParam` object. In some browsers older implementations of this interface return {{jsxref('undefined')}}. ## Examples In this example, we have a media source with two control buttons (see the [audio-param repo](https://github.com/mdn/webaudio-examples/tree/main/audio-param) for the source code, or [view the example live](https://mdn.github.io/webaudio-examples/audio-param/).) When these buttons are pressed, `exponentialRampToValueAtTime()` is used to fade the gain value up to 1.0, and down to 0, respectively. This is pretty useful for fade in/fade out effects: ```js // create audio context const audioCtx = new AudioContext(); // set basic variables for example const myAudio = document.querySelector("audio"); const expRampPlus = document.querySelector(".exp-ramp-plus"); const expRampMinus = document.querySelector(".exp-ramp-minus"); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it const source = audioCtx.createMediaElementSource(myAudio); // Create a gain node and set its gain value to 0.5 const gainNode = audioCtx.createGain(); // connect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination gainNode.gain.setValueAtTime(0, audioCtx.currentTime); source.connect(gainNode); gainNode.connect(audioCtx.destination); // set buttons to do something onclick expRampPlus.onclick = () => { gainNode.gain.exponentialRampToValueAtTime(1.0, audioCtx.currentTime + 2); }; expRampMinus.onclick = () => { gainNode.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 2); }; ``` > **Note:** A value of 0.01 was used for the value to ramp down to in the > last function rather than 0, as an _invalid or illegal string_ error is thrown > if 0 is used — the value needs to be positive. ## 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/audioparam
data/mdn-content/files/en-us/web/api/audioparam/setvalueattime/index.md
--- title: "AudioParam: setValueAtTime() method" short-title: setValueAtTime() slug: Web/API/AudioParam/setValueAtTime page-type: web-api-instance-method browser-compat: api.AudioParam.setValueAtTime --- {{ APIRef("Web Audio API") }} The `setValueAtTime()` method of the {{domxref("AudioParam")}} interface schedules an instant change to the `AudioParam` value at a precise time, as measured against {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}. The new value is given in the value parameter. ## Syntax ```js-nolint setValueAtTime(value, startTime) ``` ### Parameters - `value` - : A floating point number representing the value the AudioParam will change to at the given time. - `startTime` - : A double representing the time (in seconds) after the {{domxref("AudioContext")}} was first created that the change in value will happen. If the time is less than {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}, the change happens immediately. A {{jsxref("TypeError")}} is thrown if this value is negative. ### Return value A reference to this `AudioParam` object. In some browsers older implementations of this interface return {{jsxref('undefined')}}. ## Examples This simple example features a media element source with two control buttons (see our [webaudio-examples repo](https://github.com/mdn/webaudio-examples/blob/main/audio-param/index.html) for the source code, or [view the example live](https://mdn.github.io/webaudio-examples/audio-param/)). When the buttons are pressed, the `currGain` variable is incremented/decremented by 0.25, then the `setValueAtTime()` method is used to set the gain value equal to `currGain`, one second from now (`audioCtx.currentTime + 1`.) ```js // create audio context const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext(); // set basic variables for example const myAudio = document.querySelector("audio"); const pre = document.querySelector("pre"); const myScript = document.querySelector("script"); pre.innerHTML = myScript.innerHTML; const targetAtTimePlus = document.querySelector(".set-target-at-time-plus"); const targetAtTimeMinus = document.querySelector(".set-target-at-time-minus"); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it const source = audioCtx.createMediaElementSource(myAudio); // Create a gain node and set it's gain value to 0.5 const gainNode = audioCtx.createGain(); gainNode.gain.value = 0.5; let currGain = gainNode.gain.value; // connect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination source.connect(gainNode); gainNode.connect(audioCtx.destination); // set buttons to do something onclick targetAtTimePlus.onclick = () => { currGain += 0.25; gainNode.gain.setValueAtTime(currGain, audioCtx.currentTime + 1); }; targetAtTimeMinus.onclick = () => { currGain -= 0.25; gainNode.gain.setValueAtTime(currGain, audioCtx.currentTime + 1); }; ``` ## 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/audioparam
data/mdn-content/files/en-us/web/api/audioparam/linearramptovalueattime/index.md
--- title: "AudioParam: linearRampToValueAtTime() method" short-title: linearRampToValueAtTime() slug: Web/API/AudioParam/linearRampToValueAtTime page-type: web-api-instance-method browser-compat: api.AudioParam.linearRampToValueAtTime --- {{ APIRef("Web Audio API") }} The `linearRampToValueAtTime()` method of the {{ domxref("AudioParam") }} Interface schedules a gradual linear change in the value of the `AudioParam`. The change starts at the time specified for the _previous_ event, follows a linear ramp to the new value given in the `value` parameter, and reaches the new value at the time given in the `endTime` parameter. ## Syntax ```js-nolint linearRampToValueAtTime(value, endTime) ``` ### Parameters - `value` - : A floating point number representing the value the `AudioParam` will ramp to by the given time. - `endTime` - : A double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop. ### Return value A reference to this `AudioParam` object. In some browsers older implementations of this interface return {{jsxref('undefined')}}. ## Examples In this example, we have a media source with two control buttons (see the [audio-param repo](https://github.com/mdn/webaudio-examples/tree/main/audio-param) for the source code, or [view the example live](https://mdn.github.io/webaudio-examples/audio-param/).) When these buttons are pressed, `linearRampToValueAtTime()` is used to fade the gain value up to 1.0, and down to 0, respectively. This is pretty useful for fade in/fade out effects, although {{ domxref("AudioParam.exponentialRampToValueAtTime()") }} is often said to be a bit more natural. ```js // create audio context const audioCtx = new AudioContext(); // set basic variables for example const myAudio = document.querySelector("audio"); const linearRampPlus = document.querySelector(".linear-ramp-plus"); const linearRampMinus = document.querySelector(".linear-ramp-minus"); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it const source = audioCtx.createMediaElementSource(myAudio); // Create a gain node and set it's gain value to 0.5 const gainNode = audioCtx.createGain(); // connect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination gainNode.gain.setValueAtTime(0, audioCtx.currentTime); source.connect(gainNode); gainNode.connect(audioCtx.destination); // set buttons to do something onclick linearRampPlus.onclick = () => { gainNode.gain.linearRampToValueAtTime(1.0, audioCtx.currentTime + 2); }; linearRampMinus.onclick = () => { gainNode.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 2); }; ``` ## 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/audioparam
data/mdn-content/files/en-us/web/api/audioparam/maxvalue/index.md
--- title: "AudioParam: maxValue property" short-title: maxValue slug: Web/API/AudioParam/maxValue page-type: web-api-instance-property browser-compat: api.AudioParam.maxValue --- {{APIRef("Web Audio API")}} The **`maxValue`** read-only property of the {{domxref("AudioParam")}} interface represents the maximum possible value for the parameter's nominal (effective) range. ## Value A floating-point {{jsxref("Number")}} indicating the maximum value permitted for the parameter's nominal range. The default value of `maxValue` is the maximum positive single-precision floating-point value (+340,282,346,638,528,859,811,704,183,484,516,925,440). ## Examples ```js const audioCtx = new AudioContext(); const gainNode = audioCtx.createGain(); console.log(gainNode.gain.maxValue); // 3.4028234663852886e38 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("AudioParam.minValue")}}
0
data/mdn-content/files/en-us/web/api/audioparam
data/mdn-content/files/en-us/web/api/audioparam/setvaluecurveattime/index.md
--- title: "AudioParam: setValueCurveAtTime() method" short-title: setValueCurveAtTime() slug: Web/API/AudioParam/setValueCurveAtTime page-type: web-api-instance-method browser-compat: api.AudioParam.setValueCurveAtTime --- {{APIRef("Web Audio API")}} The **`setValueCurveAtTime()`** method of the {{domxref("AudioParam")}} interface schedules the parameter's value to change following a curve defined by a list of values. The curve is a linear interpolation between the sequence of values defined in an array of floating-point values, which are scaled to fit into the given interval starting at `startTime` and a specific duration. ## Syntax ```js-nolint setValueCurveAtTime(values, startTime, duration) ``` ### Parameters - `values` - : An array of floating-point numbers representing the value curve the {{domxref("AudioParam")}} will change through along the specified `duration`. Every value in the array must be a finite number; if any value is `NaN`, `Infinity`, or `-Infinity`, a {{jsxref("TypeError")}} exception is thrown. - `startTime` - : A double representing the time (in seconds) after the {{ domxref("AudioContext") }} was first created that the change in value will happen. If this value is lower than {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}, it is clamped to `currentTime`. - `duration` - : A double representing the total time (in seconds) over which the parameter's `value` will change following the specified curve. The specified values are spaced equally along this duration. ### Return value A reference to this `AudioParam` object. Some older browser implementations of this interface return `undefined`. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the specified array of `values` has fewer than 2 items in it. - {{jsxref("RangeError")}} - : Thrown if the specified `startTime` is either negative or a non-finite value, or `duration` is not a finite, strictly positive number. - {{jsxref("TypeError")}} - : Thrown if one or more of the values in the `values` array is non-finite. Non-finite values are `NaN`, `Infinity`, and `-Infinity`. ## Usage notes When the parameter's value finishes following the curve, its value is guaranteed to match the last value in the set of values specified in the `values` parameter. > **Note:** Some early implementations of the Web Audio API did not ensure > this to be the case, causing unexpected results. ## Examples In this example, we have a media source with a single button (see the [webaudio-examples repo](https://github.com/mdn/webaudio-examples/blob/main/audio-param/index.html) for the source code, or [view the example live](https://mdn.github.io/webaudio-examples/audio-param/).) When this button is pressed, `setValueCurveAtTime()` is used to change the gain value between the values contained in the waveArray array: ```js // create audio context const audioCtx = new AudioContext(); // set basic variables for example const myAudio = document.querySelector("audio"); const valueCurve = document.querySelector(".value-curve"); // Create a MediaElementAudioSourceNode // Feed the HTMLMediaElement into it const source = audioCtx.createMediaElementSource(myAudio); // Create a gain node and set it's gain value to 0.5 const gainNode = audioCtx.createGain(); gainNode.gain.value = 0.5; const currGain = gainNode.gain.value; // connect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination source.connect(gainNode); gainNode.connect(audioCtx.destination); // set button to do something onclick const waveArray = new Float32Array(9); waveArray[0] = 0.5; waveArray[1] = 1; waveArray[2] = 0.5; waveArray[3] = 0; waveArray[4] = 0.5; waveArray[5] = 1; waveArray[6] = 0.5; waveArray[7] = 0; waveArray[8] = 0.5; valueCurve.onclick = () => { gainNode.gain.setValueCurveAtTime(waveArray, audioCtx.currentTime, 2); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} Versions before Chrome 46 use nearest neighbor instead of linear interpolation. ## 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
data/mdn-content/files/en-us/web/api/audiodecoder/index.md
--- title: AudioDecoder slug: Web/API/AudioDecoder page-type: web-api-interface status: - experimental browser-compat: api.AudioDecoder --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`AudioDecoder`** interface of the {{domxref('WebCodecs API','','',' ')}} decodes chunks of audio. {{InheritanceDiagram}} ## Constructor - {{domxref("AudioDecoder.AudioDecoder", "AudioDecoder()")}} {{Experimental_Inline}} - : Creates a new `AudioDecoder` object. ## Instance properties _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("AudioDecoder.decodeQueueSize")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : An integer representing the number of decode queue requests. - {{domxref("AudioDecoder.state")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Represents the state of the underlying codec and whether it is configured for decoding. ### Events - {{domxref("AudioDecoder.dequeue_event", "dequeue")}} {{Experimental_Inline}} - : Fires to signal a decrease in {{domxref("AudioDecoder.decodeQueueSize")}}. ## Static methods - {{domxref("AudioDecoder/isConfigSupported_static", "AudioDecoder.isConfigSupported()")}} {{Experimental_Inline}} - : Returns a promise indicating whether the provided `AudioDecoderConfig` is supported. ## Instance methods _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("AudioDecoder.configure()")}} {{Experimental_Inline}} - : Enqueues a control message to configure the audio decoder for decoding chunks. - {{domxref("AudioDecoder.decode()")}} {{Experimental_Inline}} - : Enqueues a control message to decode a given chunk of audio. - {{domxref("AudioDecoder.flush()")}} {{Experimental_Inline}} - : Returns a promise that resolves once all pending messages in the queue have been completed. - {{domxref("AudioDecoder.reset()")}} {{Experimental_Inline}} - : Resets all states including configuration, control messages in the control message queue, and all pending callbacks. - {{domxref("AudioDecoder.close()")}} {{Experimental_Inline}} - : Ends all pending work and releases system resources. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/configure/index.md
--- title: "AudioDecoder: configure() method" short-title: configure() slug: Web/API/AudioDecoder/configure page-type: web-api-instance-method status: - experimental browser-compat: api.AudioDecoder.configure --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`configure()`** method of the {{domxref("AudioDecoder")}} interface enqueues a control message to configure the audio decoder for decoding chunks. ## Syntax ```js-nolint configure(config) ``` ### Parameters - `config` - : A dictionary object containing the following members: - `codec` - : A string containing a [valid codec string](https://www.w3.org/TR/webcodecs-codec-registry/#audio-codec-registry). See ["codecs" parameter](/en-US/docs/Web/Media/Formats/codecs_parameter#codec_options_by_container) for details on codec string construction. - `sampleRate` - : An integer representing the number of frame samples per second. - `numberOfChannels` - : An integer representing the number of audio channels. - `description` {{optional_inline}} - : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}} containing a sequence of codec specific bytes, commonly known as extradata. > **Note:** The registrations in the [WebCodecs Codec Registry](https://www.w3.org/TR/webcodecs-codec-registry/#audio-codec-registry) link to a specification detailing whether and how to populate the optional `description` member. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the provided `config` is invalid. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("AudioDecoder.state","state")}} is `"closed"`. - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the provided `config` is valid but the user agent cannot provide a codec that can decode this profile. ## Examples The following example configures the `audioDecoder` with the `opus` codec. ```js audioDecoder.configure({ codec: "opus", sampleRate: 44100, numberOfChannels: 2, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/decodequeuesize/index.md
--- title: "AudioDecoder: decodeQueueSize property" short-title: decodeQueueSize slug: Web/API/AudioDecoder/decodeQueueSize page-type: web-api-instance-property status: - experimental browser-compat: api.AudioDecoder.decodeQueueSize --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`decodeQueueSize`** read-only property of the {{domxref("AudioDecoder")}} interface returns the number of pending decode requests in the queue. ## Value An integer containing the number of requests. ## Examples The following example prints the size of the queue to the console. ```js console.log(AudioDecoder.decodeQueueSize); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/dequeue_event/index.md
--- title: "AudioDecoder: dequeue event" short-title: dequeue slug: Web/API/AudioDecoder/dequeue_event page-type: web-api-event status: - experimental browser-compat: api.AudioDecoder.dequeue_event --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`dequeue`** event of the {{domxref("AudioDecoder")}} interface fires to signal a decrease in {{domxref("AudioDecoder.decodeQueueSize")}}. This eliminates the need for developers to use a {{domxref("setTimeout()")}} poll to determine when the queue has decreased, and more work should be queued up. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("dequeue", (event) => {}); ondequeue = (event) => {}; ``` ## Example ```js audioDecoder.addEventListener("dequeue", (event) => { // Queue up more decoding work }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/audiodecoder/index.md
--- title: "AudioDecoder: AudioDecoder() constructor" short-title: AudioDecoder() slug: Web/API/AudioDecoder/AudioDecoder page-type: web-api-constructor status: - experimental browser-compat: api.AudioDecoder.AudioDecoder --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`AudioDecoder()`** constructor creates a new {{domxref("AudioDecoder")}} object with the provided `init.output` callback assigned as the output callback, the provided `init.error` callback as the error callback, and the {{domxref("AudioDecoder.state")}} set to `"unconfigured"`. ## Syntax ```js-nolint new AudioDecoder(init) ``` ### Parameters - `init` - : A dictionary object containing two required callbacks. - `output` - : A callback which is passed a single argument of an {{domxref("AudioData")}} object. - `error` - : A callback which is passed a single argument of the error that has been thrown. ## Examples In the following example an `AudioDecoder` is created with the two required callback functions, one to deal with the decoded chunk and the other to handle errors. ```js const audioDecoder = new AudioDecoder({ output: processAudio, error: onEncoderError, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/flush/index.md
--- title: "AudioDecoder: flush() method" short-title: flush() slug: Web/API/AudioDecoder/flush page-type: web-api-instance-method status: - experimental browser-compat: api.AudioDecoder.flush --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`flush()`** method of the {{domxref("AudioDecoder")}} interface returns a Promise that resolves once all pending messages in the queue have been completed. ## Syntax ```js-nolint flush() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with undefined. ### Exceptions If an error occurs, the promise will resolve with one of the following exceptions: - `InvalidStateError` {{domxref("DOMException")}} - : Returned if the Promise is rejected because the {{domxref("AudioDecoder.state","state")}} is not `configured`. ## Examples The following example flushes the `AudioDecoder`. ```js await audioDecoder.flush(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/decode/index.md
--- title: "AudioDecoder: decode() method" short-title: decode() slug: Web/API/AudioDecoder/decode page-type: web-api-instance-method status: - experimental browser-compat: api.AudioDecoder.decode --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`decode()`** method of the {{domxref("AudioDecoder")}} interface enqueues a control message to decode a given chunk of audio. ## Syntax ```js-nolint decode(chunk) ``` ### Parameters - `chunk` - : An {{domxref("EncodedAudioChunk")}} object representing a chunk of encoded audio. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("AudioDecoder.state","state")}} is not `"configured"`. - `DataError` {{domxref("DOMException")}} - : Thrown if the `chunk` is unable to be decoded due to relying on other frames for decoding. ## Examples ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/isconfigsupported_static/index.md
--- title: "AudioDecoder: isConfigSupported() static method" short-title: isConfigSupported() slug: Web/API/AudioDecoder/isConfigSupported_static page-type: web-api-static-method status: - experimental browser-compat: api.AudioDecoder.isConfigSupported_static --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}}{{SeeCompatTable}} The **`isConfigSupported()`** static method of the {{domxref("AudioDecoder")}} interface checks if the given config is supported (that is, if {{domxref("AudioDecoder")}} objects can be successfully configured with the given config). ## Syntax ```js-nolint AudioDecoder.isConfigSupported(config) ``` ### Parameters - `config` - : The dictionary object accepted by {{domxref("AudioDecoder.configure")}} ### Return value A {{jsxref("Promise")}} that resolves with an object containing the following members: - `supported` - : A boolean value which is `true` if the given config is supported by the decoder. - `config` - : A copy of the given config with all the fields recognized by the decoder. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the provided `config` is invalid; that is, if doesn't have required values (such as an empty `codec` field) or has invalid values (such as a negative `sampleRate`). ## Examples The following example tests if the browser supports several audio codecs. ```js const codecs = ["mp4a.40.2", "mp3", "alaw", "ulaw"]; const configs = []; for (const codec of codecs) { configs.push({ codec, sampleRate: 48000, numberOfChannels: 1, not_supported_field: 123, }); } for (const config of configs) { const support = await AudioDecoder.isConfigSupported(config); console.log( `AudioDecoder's config ${JSON.stringify(support.config)} support: ${ support.supported }`, ); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/state/index.md
--- title: "AudioDecoder: state property" short-title: state slug: Web/API/AudioDecoder/state page-type: web-api-instance-property status: - experimental browser-compat: api.AudioDecoder.state --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`state`** read-only property of the {{domxref("AudioDecoder")}} interface returns the current state of the underlying codec. ## Value A string containing one of the following values: - `"unconfigured"` - : The codec is not configured for decoding. - `"configured"` - : The codec has a valid configuration and is ready. - `"closed"` - : The codec is no longer usable and system resources have been released. ## Examples The following example prints the state of the `AudioDecoder` to the console. ```js console.log(AudioDecoder.state); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/reset/index.md
--- title: "AudioDecoder: reset() method" short-title: reset() slug: Web/API/AudioDecoder/reset page-type: web-api-instance-method status: - experimental browser-compat: api.AudioDecoder.reset --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`reset()`** method of the {{domxref("AudioDecoder")}} interface resets all states including configuration, control messages in the control message queue, and all pending callbacks. ## Syntax ```js-nolint reset() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example resets the `AudioDecoder`. ```js AudioDecoder.reset(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/audiodecoder
data/mdn-content/files/en-us/web/api/audiodecoder/close/index.md
--- title: "AudioDecoder: close() method" short-title: close() slug: Web/API/AudioDecoder/close page-type: web-api-instance-method status: - experimental browser-compat: api.AudioDecoder.close --- {{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`close()`** method of the {{domxref("AudioDecoder")}} interface ends all pending work and releases system resources. ## Syntax ```js-nolint close() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example closes the `AudioDecoder`. ```js AudioDecoder.close(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/submitevent/index.md
--- title: SubmitEvent slug: Web/API/SubmitEvent page-type: web-api-interface browser-compat: api.SubmitEvent --- {{APIRef("HTML DOM")}} The **`SubmitEvent`** interface defines the object used to represent an {{Glossary("HTML")}} form's {{domxref("HTMLFormElement.submit_event", "submit")}} event. This event is fired at the {{HTMLElement("form")}} when the form's submit action is invoked. {{InheritanceDiagram}} ## Constructor - {{domxref("SubmitEvent.SubmitEvent", "SubmitEvent()")}} - : Creates and returns a new `SubmitEvent` object whose {{domxref("Event.type", "type")}} and other options are configured as specified. Note that currently the only valid `type` for a `SubmitEvent` is `submit`. ## Instance properties _In addition to the properties listed below, this interface inherits the properties of its parent interface, {{domxref("Event")}}._ - {{domxref("SubmitEvent.submitter", "submitter")}} {{ReadOnlyInline}} - : An {{domxref("HTMLElement")}} object which identifies the button or other element which was invoked to trigger the form being submitted. ## Instance methods _While `SubmitEvent` offers no methods of its own, it inherits any specified by its parent interface, {{domxref("Event")}}._ ## Examples In this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. Each of the submit elements' {{domxref("Element.id", "id")}} is used to identify which payment processor the button corresponds to. ```js let form = document.querySelector("form"); form.addEventListener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processOrder(form, handler); } else { showAlertMessage( "An unknown or unaccepted payment type was selected. Please try again.", "OK", ); } }); ``` The handler ID is obtained by using the `submit` event's {{domxref("SubmitEvent.submitter", "submitter")}} property to get the submit button, from which we then get the ID. With that in hand, we can call a `processOrder()` function to handle the order, passing along the form and the handler ID. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/submitevent
data/mdn-content/files/en-us/web/api/submitevent/submitevent/index.md
--- title: "SubmitEvent: SubmitEvent() constructor" short-title: SubmitEvent() slug: Web/API/SubmitEvent/SubmitEvent page-type: web-api-constructor browser-compat: api.SubmitEvent.SubmitEvent --- {{APIRef("HTML DOM")}} The **`SubmitEvent()`** constructor creates and returns a new {{domxref("SubmitEvent")}} object, which is used to represent a {{domxref("HTMLFormElement.submit_event", "submit")}} event fired at an {{Glossary("HTML")}} [form](/en-US/docs/Learn/Forms). ## Syntax ```js-nolint new SubmitEvent(type) new SubmitEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers always set it to `submit`. - `options` {{optional_inline}} - : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties: - `submitter` {{optional_inline}} - : An {{domxref('HTMLElement')}} object that is the submit button that triggered the form submission. ### Return value A {{domxref("SubmitEvent")}} object configured using the given inputs. ## Examples This code snippet locates a form in the current document, and then an HTML {{HTMLElement("button")}} within the form with the class `submit` on it. Next, a new {{domxref("SubmitEvent")}} is created, configured with its {{domxref("SubmitEvent.submitter", "submitter")}} set to the identified button (or `null` if the button wasn't found). Then the event is sent to the form, telling the form that it's been submitted by the button. ```js const form = document.querySelector("form"); const formTrigger = form.querySelector("button.submit"); const submitEvent = new SubmitEvent("submit", { submitter: formTrigger }); form.dispatchEvent(submitEvent); ``` This is a somewhat contrived example, as you can do nearly all of this much more easily, but this gives you deep control over the process that can be useful. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/submitevent
data/mdn-content/files/en-us/web/api/submitevent/submitter/index.md
--- title: "SubmitEvent: submitter property" short-title: submitter slug: Web/API/SubmitEvent/submitter page-type: web-api-instance-property browser-compat: api.SubmitEvent.submitter --- {{APIRef("HTML DOM")}} The read-only **`submitter`** property found on the {{domxref("SubmitEvent")}} interface specifies the submit button or other element that was invoked to cause the form to be submitted. ## Value An element, indicating the element that sent the {{domxref("HTMLFormElement.submit_event", "submit")}} event to the form. While this is often an {{HTMLElement("input")}} element whose [`type`](/en-US/docs/Web/HTML/Element/input#type) is `submit` or a {{HTMLElement("button")}} element whose [`type`](/en-US/docs/Web/HTML/Element/input#type) is `submit`, it could be some other element which has initiated a submission process. If the submission was not triggered by a button of some kind, the value of `submitter` is `null`. ## Examples See [`SubmitEvent`](/en-US/docs/Web/API/SubmitEvent#examples) for example code. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrboundedreferencespace/index.md
--- title: XRBoundedReferenceSpace slug: Web/API/XRBoundedReferenceSpace page-type: web-api-interface status: - experimental browser-compat: api.XRBoundedReferenceSpace --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}}{{SeeCompatTable}} The [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API)'s **`XRBoundedReferenceSpace`** interface describes a virtual world [reference space](/en-US/docs/Web/API/WebXR_Device_API/Geometry) which has preset boundaries. This extends {{domxref("XRReferenceSpace")}}, which describes an essentially unrestricted space around the viewer's position. These bounds are defined using an array of points, each of which defines a vertex in a polygon inside which the user is allowed to move. This is typically used when the XR system is capable of tracking the user's physical movement within a limited distance of their starting position. The specified bounds may, in fact, describe the shape and size of the room the user is located in, in order to let the WebXR site or application prevent the user from colliding with the walls or other obstacles in the real world. At a minimum, the boundaries indicate the area in which the XR device is capable of tracking the user's movement. See the article [Using bounded reference spaces](/en-US/docs/Web/API/WebXR_Device_API/Bounded_reference_spaces) for details on how bounded spaces work and why they're useful. {{InheritanceDiagram}} ## Instance properties _In addition to the properties of {{domxref("XRReferenceSpace")}}, `XRBoundedReferenceSpace` includes the following:_ - {{domxref("XRBoundedReferenceSpace.boundsGeometry", "boundsGeometry")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : An array of {{domxref("DOMPointReadOnly")}} objects, each of which defines a vertex in the polygon defining the boundaries within which the user will be required to remain. These vertices _must_ be sorted such that they move _clockwise_ around the viewer's position. ## Instance methods _`XRBoundedReferenceSpace` inherits the methods of its parent interface, {{domxref("XRReferenceSpace")}}. It has no further methods._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) - [Geometry and reference spaces in WebXR](/en-US/docs/Web/API/WebXR_Device_API/Geometry) - [Viewpoints and viewers: simulating cameras in WebXR](/en-US/docs/Web/API/WebXR_Device_API/Cameras)
0
data/mdn-content/files/en-us/web/api/xrboundedreferencespace
data/mdn-content/files/en-us/web/api/xrboundedreferencespace/boundsgeometry/index.md
--- title: "XRBoundedReferenceSpace: boundsGeometry property" short-title: boundsGeometry slug: Web/API/XRBoundedReferenceSpace/boundsGeometry page-type: web-api-instance-property status: - experimental browser-compat: api.XRBoundedReferenceSpace.boundsGeometry --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The read-only {{domxref("XRBoundedReferenceSpace")}} property **`boundsGeometry`** is an array of {{domxref("DOMPointReadOnly")}} objects which specifies the points making up a polygon inside which the viewer is allowed to move. Each point is treated as a two-dimensional point, and must be located at ground level (that is, its `y` coordinate must be 0). This boundary is typically configured by the user, using the software that controls their XR hardware. This may be done by walking the border of the space they wish to use, or by drawing the shape of their room using their XR input device. Theoretically, a more advanced system might use sensors or other detection methods to determine the bounds of a dedicated XR room (notice how we carefully don't call it a holodeck?). ## Value The `boundsGeometry` property is an array of {{domxref("DOMPointReadOnly")}} objects, each of which defines one vertex in a polygon inside which the viewer is required to remain. Each point must be at floor level, with its `y` coordinate's value set to 0. Additionally, the value of `w` is always 1 in every point in the array. Additionally, the points _must_ be listed in clockwise order. Each entry in `boundsGeometry` is equal to an entry in the list of native bounds geometry points for the room, premultiplied by the inverse of the origin offset. In other words, the bounds are the physical limitations of the available space, shifted so that the reference space's bounds points are all defined relative to the `XRBoundedReferenceSpace`'s effective origin. ## Usage notes Bounded reference spaces always have their origin located at ground level, where `y` is 0. As a general rule, with the origin for `x` and `z` located in or near the center of the space, and with the orientation set facing in a logical forward direction, as appropriate for the underlying platform or XR hardware. In order to reduce the risk of the room boundaries being used for [fingerprinting](/en-US/docs/Glossary/Fingerprinting) purposes, each point in the `boundsGeometry` array may be rounded or adjusted by some amount. The specification recommends that browsers shift the points to the nearest 5 centimeters (while avoiding going outside the physical limitations of the hardware). ### Boundary size `XRBoundedReferenceSpace` is not intended to be used for very large bounded areas. Instead, it's meant to be used for one-room spaces with no more than around 15 meters of available movement space in any direction from the native origin. That said, the bounds extend upward indefinitely, since the bounds are defined in only two dimensions. If you need to create a multi-room space, or a space which is very large or needs to have varying floor levels, you should instead use an unbounded {{domxref("XRReferenceSpace")}} and enforce the bounds on your own, as appropriate. ### Boundary shape The shape defined by `boundsGeometry` may be as simple as a square or as complex as is needed, potentially including concave and/or convex sections. However, you can't represent spaces with uneven floor levels using `XRBoundedReferenceSpace`. The ground is _always_ at `y` = 0. It's important that your content not be designed to require the user to exit the bounds specified by `boundsGeometry`. However, if the user's surroundings permit them to move in such a way as to exit the defined bounds, your content must be able to gracefully handle the situation, which is not considered an error condition. Although some samples render a mesh or other shape to display the bounds to the user, in a real-world application, you shouldn't do this. The browser, however, should provide appropriate warnings to the user about any risks (such as the risk that they might run into a physical wall if they keep moving). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrreferencespace/index.md
--- title: XRReferenceSpace slug: Web/API/XRReferenceSpace page-type: web-api-interface browser-compat: api.XRReferenceSpace --- {{APIRef("WebXR Device API")}}{{secureContext_header}} The WebXR Device API's **`XRReferenceSpace`** interface describes the coordinate system for a specific tracked entity or object within the virtual world using a specified tracking behavior. The tracking behavior is defined by the selected [reference space type](#reference_space_types). It expands upon the base class, {{domxref("XRSpace")}}, by adding support for several different tracking behaviors as well as to request a new reference space which describes the offset transform between the tracked object and another location in the world. All reference spaces—with the sole exception being bounded reference spaces—are described using the `XRReferenceSpace` type. Bounded spaces are implemented as {{domxref("XRBoundedReferenceSpace")}} objects. These are special spaces which let you establish a perimeter within which it's "safe" for the viewer to move. For XR systems that allow the user to physically move around, such as those that track movement with a real-world camera, this boundary establishes the edges of the area the user is able to move around in, whether due to physical obstacles or due to limitations of the XR hardware. See the article [Using bounded reference spaces to protect the viewer](/en-US/docs/Web/API/WebXR_Device_API/Bounded_reference_spaces) for more on using boundaries to keep the user from colliding with obstacles both physical and virtual. {{InheritanceDiagram}} ## Instance properties _`XRReferenceSpace` inherits the properties of {{domxref("EventTarget")}} but defines no additional properties._ ## Instance methods _`XRReferenceSpace` also inherits methods from {{domxref("EventTarget")}} in addition to the following methods._ - {{domxref("XRReferenceSpace.getOffsetReferenceSpace", "getOffsetReferenceSpace()")}} - : Creates and returns a new reference space object as the same type as the one on which you call the method (so, either `XRReferenceSpace` or {{domxref("XRBoundedReferenceSpace")}}). The new reference space can be used to transform a coordinate from the reference space of the object on which the method is called into a different coordinate space. This is useful for positioning objects while rendering, and to perform the needed transforms when changing the viewer's position and/or orientation in 3D space. ## Events - {{domxref("XRReferenceSpace.reset_event", "reset")}} - : The `reset` event is sent to an `XRReferenceSpace` object when the browser detects a discontinuity between the tracked object's origin and the user's environment or location. This can happen, for example, after the user recalibrates their XR device, or if the device automatically adjusts its origin after losing and regaining tracking. ## Reference space types The types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. - `bounded-floor` - : An {{domxref("XRBoundedReferenceSpace")}} similar to the `local` type, except the user is not expected to move outside a predetermined boundary, given by the {{domxref("XRBoundedReferenceSpace.boundsGeometry", "boundsGeometry")}} in the returned object. - `local` - : An `XRReferenceSpace` tracking space whose native origin is located near the viewer's position at the time the session was created. The exact position depends on the underlying platform and implementation. The user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. For devices with six degrees of freedom (6DoF) tracking, the `local` reference space tries to keep the origin stable relative to the environment. - `local-floor` - : An `XRReferenceSpace` similar to the `local` type, except the starting position is placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. If that floor level isn't known, the {{Glossary("user agent")}} will estimate the floor level. If the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid [fingerprinting](/en-US/docs/Glossary/Fingerprinting) (likely to the nearest centimeter). - `unbounded` - : An `XRReferenceSpace` tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. The viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need. - `viewer` - : An `XRReferenceSpace` tracking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of {{domxref("XRSession")}}, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. Otherwise, typically, one of the other reference space types will be used more often. ## Usage notes ### Creating an XRReferenceSpace There are two situations in which you need to obtain an `XRReferenceSpace`. The first is when you set up your scene and need to obtain a reference space to represent the user's viewpoint on the world for the duration of the {{domxref("XRSession")}}. To do that, call the {{domxref("XRSession")}} method {{domxref("XRSession.requestReferenceSpace", "requestReferenceSpace()")}}, specifying the reference space type you wish to obtain. ```js xrSession.requestReferenceSpace("local").then((refSpace) => { xrReferenceSpace = refSpace; // … }); ``` The other situation in which you may need to acquire a new reference space is if you need to move the origin to a new position; this is commonly done, for example, when your project allows the user to move through the environment using input devices such as the keyboard, mouse, touchpad, or game controls that are not connected through the XR device. Since the origin will typically be the user's location in the space, you need to change the origin to reflect their movement and any orientation changes they make. To move or rotate the user's view of the world, you need to change the `XRReferenceSpace` used to represent that viewpoint. However, `XRReferenceSpace` is immutable, so you need to instead create a new reference space representing the changed viewpoint. This is easily done using the {{domxref("XRReferenceSpace.getOffsetReferenceSpace", "getOffsetReferenceSpace()")}} method. ```js let offsetTransform = new XRRigidTransform( { x: 2, y: 0, z: 1 }, { x: 0, y: 0, z: 0, w: 1 }, ); xrReferenceSpace = xrReferenceSpace.getOffsetReferenceSpace(offsetTransform); ``` This replaces the `XRReferenceSpace` with a new one whose origin and orientation are adjusted to place the new origin at (2, 0, 1) relative to the current origin and rotated given a unit {{Glossary("quaternion")}} that orients the space to put the viewer facing straight up relative to the previous world orientation. ### Geometry The native origin of any `XRReferenceSpace` is always configured so that +X is considered to be to the right, +Y is upward, and +Z is "backward" or toward the user. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Fundamentals of WebXR](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals) - [Geometry and reference spaces in WebXR](/en-US/docs/Web/API/WebXR_Device_API/Geometry) - [Viewpoints and viewers: Simulating cameras in WebXR](/en-US/docs/Web/API/WebXR_Device_API/Cameras) - [Matrix math for the web](/en-US/docs/Web/API/WebGL_API/Matrix_math_for_the_web) - [Movement, orientation, and motion](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion) - [Using bounded reference spaces to protect the user](/en-US/docs/Web/API/WebXR_Device_API/Bounded_reference_spaces)
0
data/mdn-content/files/en-us/web/api/xrreferencespace
data/mdn-content/files/en-us/web/api/xrreferencespace/getoffsetreferencespace/index.md
--- title: "XRReferenceSpace: getOffsetReferenceSpace() method" short-title: getOffsetReferenceSpace() slug: Web/API/XRReferenceSpace/getOffsetReferenceSpace page-type: web-api-instance-method browser-compat: api.XRReferenceSpace.getOffsetReferenceSpace --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The {{domxref("XRReferenceSpace")}} interface's **`getOffsetReferenceSpace()`** method returns a new reference space object which describes the relative difference in position between the object on which the method is called and a given point in 3D space. The object returned by `getOffsetReferenceSpace()` is an {{domxref("XRReferenceSpace")}} if called on an `XRReferenceSpace`, or an {{domxref("XRBoundedReferenceSpace")}} if called on an object of that type. In other words, when you have an object in 3D space and need to position another object relative to that one, you can call `getOffsetReferenceSpace()`, passing into it the position and orientation you want the second object to have _relative to the position and orientation of the object on which you call `getOffsetReferenceSpace()`_. Then, when drawing the scene, you can use the offset reference space to not only position objects relative to one another, but to apply the needed transforms to render objects properly based upon the viewer's position. This is demonstrated in the example [Implementing rotation based on non-XR inputs](#implementing_rotation_based_on_non-xr_inputs), which demonstrates a way to use this method to let the user use their mouse to pitch and yaw their viewing angle. ## Syntax ```js-nolint getOffsetReferenceSpace(originOffset) ``` ### Parameters - `originOffset` - : An {{domxref("XRRigidTransform")}} specifying the offset to the origin of the new reference space. These values are added to the position and orientation of the current reference space and then the result is used as the position and orientation of the newly created {{domxref("XRReferenceSpace")}}. ### Return value A new {{domxref("XRReferenceSpace")}} object describing a reference space with the same native origin as the reference space on which the method was called, but with an origin offset indicating the distance from the object to the point given by `originOffset`. If the object on which you call this method is an {{domxref("XRBoundedReferenceSpace")}}, the returned object is one as well. The {{domxref("XRBoundedReferenceSpace.boundsGeometry", "boundsGeometry")}} of the new reference space is set to the original object's `boundsGeometry` with each of its points multiplied by the inverse of `originOffset`. ## Examples Below are some examples showing how to use `getOffsetReferenceSpace()`. ### Teleporting or setting the position of the viewer Upon first creating a scene, you may need to set the user's position within the 3D world. You can do that using `getOffsetReferenceSpace()`. ```js xrSession.requestReferenceSpace("local").then((refSpace) => { xrReferenceSpace = refSpace; xrReferenceSpace = xrReferenceSpace.getOffsetReferenceSpace( new XRRigidTransform(startPosition, { x: 0, y: 0, z: 1.0, w: 1.0 }), ); xrSession.requestAnimationFrame(drawFrame); }); ``` In this code, we obtain a local reference space, then use `getOffsetReferenceSpace()` to create a new space whose origin is adjusted to a position given by `startPosition` and whose orientation is looking directly along the Z axis. Then the first animation frame is requested using {{domxref("XRSession")}}'s {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}}. ### Implementing rotation based on non-XR inputs The input controls supported directly by WebXR are all dedicated VR or AR input devices. In order to use mouse, keyboard, or other input devices to move or otherwise transform objects in the 3D space—or to allow the user to move through the space—you'll need to write some code to read the inputs and move perform the movements. This is another good use case for `getOffsetReferenceSpace()`. In this example, we'll show code that lets the user look around by right-clicking and moving the mouse to change the viewing angle. First, we add an event handler for {{domxref("Element.mousemove_event", "mousemove")}} events, which calls our code to perform the rotation if the right mouse button is down. Note also that we set {{domxref("Element.oncontextmenu", "oncontextmenu")}} up to be ignored by calling {{domxref("Event.preventDefault", "preventDefault()")}} on those events. This prevents the right-clicks from causing the context menu from appearing in the browser. ```js canvas.oncontextmenu = (event) => { event.preventDefault(); }; canvas.addEventListener("mousemove", (event) => { if (event.buttons & 2) { rotateViewBy(event.movementX, event.movementY); } }); ``` Next, the `rotateViewBy()` function, which updates the mouse look direction's yaw and pitch based on the mouse delta values from the `mousemove` event. The pitch is restricted so that you can't look beyond straight up and straight down. Each time this is called, the new offsets are used to update the current values of `mousePitch` and `mouseYaw`. ```js let mouseYaw = 0.0; let mousePitch = 0.0; const inverseOrientation = quat.create(); const MOUSE_SPEED = 0.003; function rotateViewBy(dx, dy) { mouseYaw += dx * MOUSE_SPEED; mousePitch += dy * MOUSE_SPEED; if (mousePitch < -Math.PI * 0.5) { mousePitch = -Math.PI * 0.5; } else if (mousePitch > Math.PI * 0.5) { mousePitch = Math.PI * 0.5; } } ``` Finally, we need code that actually applies the computed yaw and pitch to the viewer's orientation. This function, `applyMouseMovement()`, handles that: ```js function applyMouseMovement(refSpace) { if (!mouseYaw && !mousePitch) { return refSpace; } quat.identity(inverseOrientation); quat.rotateX(inverseOrientation, inverseOrientation, -mousePitch); quat.rotateY(inverseOrientation, inverseOrientation, -mouseYaw); let newTransform = new XRRigidTransform( { x: 0, y: 0, z: 0 }, { x: inverseOrientation[0], y: inverseOrientation[1], z: inverseOrientation[2], w: inverseOrientation[3], }, ); return refSpace.getOffsetReferenceSpace(newTransform); } ``` This function creates an inverse orientation matrix—used to orient the viewer—from the current pitch and yaw values, then uses that matrix as the source of the orientation when calling {{domxref("XRRigidTransform.XRRigidTransform", "new XRRigidTransform()")}}. The new {{domxref("XRRigidTransform")}}'s reference space is then fetched and returned to the caller. This new reference space is one in which the viewer's position is unchanged, but their orientation has been altered based on the pitch and yaw values generated from the accumulated mouse inputs. `applyMouseMovement()` should be called when drawing a frame, immediately before fetching the viewer's pose using {{domxref("XRFrame.getViewerPose", "getViewerPose()")}}, and the rendering should be performed in this reference space. You can see code similar to this in use in our broader WebXR tutorial article called [Movement, orientation, and motion](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion). In particular, check out the section called [Starting up the WebXR session](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion#starting_up_the_webxr_session). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrreferencespace
data/mdn-content/files/en-us/web/api/xrreferencespace/reset_event/index.md
--- title: "XRReferenceSpace: reset event" short-title: reset slug: Web/API/XRReferenceSpace/reset_event page-type: web-api-event browser-compat: api.XRReferenceSpace.reset_event --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The **`reset`** event is sent to an {{domxref("XRReferenceSpace")}} object when a discontinuity is detected in either the native origin or the effective origin, causing a jump in the position or orientation of objects oriented using the reference space. This is common when the user calibrates or recalibrates an XR device, or if the device automatically changes its origin after losing tracking of the user, then re-gaining it. In the case of {{domxref("XRBoundedReferenceSpace")}} objects, the `reset` event can also be fired when the {{domxref("XRBoundedReferenceSpace.boundsGeometry", "boundsGeometry")}} changes. In either case, the event is sent before any WebXR animation frames which make use of the new origin are executed. This event is not cancelable. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("reset", (event) => {}); onreset = (event) => {}; ``` ## Event type An {{domxref("XRReferenceSpaceEvent")}}. Inherits from {{domxref("Event")}}. ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("XRReferenceSpaceEvent.referenceSpace", "referenceSpace")}} {{ReadOnlyInline}} - : An {{domxref("XRReferenceSpace")}} indicating the reference space that generated the event. - {{domxref("XRReferenceSpaceEvent.transform", "transform")}} {{ReadOnlyInline}} - : An {{domxref("XRRigidTransform")}} object indicating the position and orientation of the specified `referenceSpace` object's native origin after the event, defined relative to the coordinate system before the event. ## Description The `reset` event indicates that the coordinate system has been reset or reconfigured by changing the reference space's origin, moving and rotating it as indicated by the event's {{domxref("XRReferenceSpaceEvent.transform", "transform")}} property. The event is sent before any animation frame callbacks are executed to render the pending frame, to ensure that those callbacks have the updated coordinate system available. There are a number of reasons why a reset might occur. Most common among them are the following: - The user has manually reset the coordinate system, such as by requesting that the headset recalibrate itself to ensure that the facing direction and hand controllers are synchronized with the user's actual position and facing. This is primarily an issue for `local` or `local-floor` reference spaces. - For a `bounded-floor` reference space, the coordinate system can be reset if the user exits the boundaries of the reference space and enters a new one (such as by crossing from one level to another in a game, where each level is its own map with its own coordinate system). - The tracking system has temporarily lost the user, then regained them, but not until after they had moved enough to leave the immediate vicinity of the last-known position. Primarily an issue for `unbounded` reference spaces. - The user is in an `unbounded` reference space and has moved far enough from the starting position (the reference space's origin) that floating-point or other forms of error or drift are problematic. The coordinate system is thus reset with its new origin at or near the user's current position. - The WebXR infrastructure or hardware drivers detected that the device had temporarily lost tracking, causing the hardware and software to be out of sync on position and orientation. > **Note:** A `reset` event will _not_ occur if the reference space is able to regain tracking of its previous origin, since that means the origin has not been forced to be relocated. This event is only fired when the origin has to be relocated to recover from the tracking loss. ### Manual resets If you've spent any time using a VR headset, you've had times when you've started it up and although you're facing straight ahead, the headset thinks you're looking at the sky or the floor; or times when you point the hand controller straight forward, but it thinks you're pointing it up and to the right somewhere. When that happens, you typically hold down a button somewhere and it causes the world to resynchronize to the device's current orientation. That works by sending a `reset` event to the reference space or reference spaces that are based on the headset's orientation. ### Handling discontinuities You can handle jumps in the viewer's position by watching the Boolean {{domxref("XRPose")}} property {{domxref("XRPose.emulatedPosition", "emulatedPosition")}}. If a jump in the viewer's position coincides with `emulatedPosition` toggling from `true` to `false`, the viewer has regained tracking, and that their new position represents a correction from the previously emulated values. This is typically the desired behavior if your site or app doesn't simulate motion through the space by expressly changing the position and/or orientation of the viewer (rather than the user's physical movements being used by the XR device to introduce movement). However, if that kind of "teleportation" is being used, you actually want to avoid jumping the user's position after tracking recovery, this can introduce additional and potentially jarring jumping. Instead of allowing this to happen, you can integrate the `emulatedPosition` into the teleportation offset calculated prior to calling {{domxref("XRReferenceSpace.getOffsetReferenceSpace", "getOffsetReferenceSpace()")}} to create a new reference space whose updated effective origin is adjusted by the distance the viewer's position jumped since the previous frame. This way, the user's position only changes once rather than twice. ### The effect of discontinuity size The `reset` event won't be fired when the discontinuity is small enough that the device is able to regain tracking within the same tracking area. Nor will be fired at an unbounded reference space as it makes small adjustments to its native origin over time to maintain the space's stability in the vicinity of the user; only large discontinuities will trigger a reset. ## Examples To add a handler for the `reset` event, you can use either of two approaches. First, you can use the {{domxref("EventTarget.addEventListener", "addEventListener()")}} method: ```js viewerRefSpace.addEventListener("reset", (event) => { /* perform reset related tasks */ }); ``` The second option is to set the `XRReferenceSpace` object's `onreset` event handler property: ```js viewerRefSpace.onreset = (event) => { /* perform reset related tasks */ }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/timeranges/index.md
--- title: TimeRanges slug: Web/API/TimeRanges page-type: web-api-interface browser-compat: api.TimeRanges --- {{APIRef("DOM")}} When loading a media resource for use by an {{HTMLElement("audio")}} or {{HTMLElement("video")}} element, the **`TimeRanges`** interface is used for representing the time ranges of the media resource that have been buffered, the time ranges that have been played, and the time ranges that are seekable. A `TimeRanges` object includes one or more ranges of time, each specified by a starting time offset and an ending time offset. You reference each time range by using the `start()` and `end()` methods, passing the index number of the time range you want to retrieve. ## Normalized TimeRanges objects Several members of {{domxref("HTMLMediaElement")}} objects return a **normalized TimeRanges object** — which [the spec describes](https://html.spec.whatwg.org/multipage/media.html#normalised-timeranges-object) as having the following characteristics: _The ranges in such an object are ordered, don't overlap, and don't touch (adjacent ranges are folded into one bigger range). A range can be empty (referencing just a single moment in time)._ ## Instance properties - {{domxref("TimeRanges.length")}} {{ReadOnlyInline}} - : Returns an `unsigned long` representing the number of time ranges represented by the time range object. ## Instance methods - {{domxref("TimeRanges.start()")}} - : Returns the time for the start of the range with the specified index. - {{domxref("TimeRanges.end()")}} - : Returns the time for the end of the specified range. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/timeranges
data/mdn-content/files/en-us/web/api/timeranges/length/index.md
--- title: "TimeRanges: length property" short-title: length slug: Web/API/TimeRanges/length page-type: web-api-instance-property browser-compat: api.TimeRanges.length --- {{APIRef("DOM")}} The **`TimeRanges.length`** read-only property returns the number of ranges in the object. ## Value A number. ## Examples Given a video element with the ID "myVideo": ```js const v = document.getElementById("myVideo"); const buf = v.buffered; const numRanges = buf.length; if (buf.length === 1) { // Only one range if (buf.start(0) === 0 && buf.end(0) === v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } ``` This example looks at the time ranges and looks to see if the entire video has been loaded. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/timeranges
data/mdn-content/files/en-us/web/api/timeranges/start/index.md
--- title: "TimeRanges: start() method" short-title: start() slug: Web/API/TimeRanges/start page-type: web-api-instance-method browser-compat: api.TimeRanges.start --- {{APIRef("DOM")}} The **`start()`** method of the {{domxref("TimeRanges")}} interface returns the time offset at which a specified time range begins. ## Syntax ```js-nolint start(index) ``` ### Parameters - `index` - : The range number to return the starting time for. ### Return value A number. ### Exceptions - `IndexSizeError` {{domxref("DOMException")}} - : Thrown if the specified index doesn't correspond to an existing range. ## Examples Given a video element with the ID "myVideo": ```js const v = document.getElementById("myVideo"); const buf = v.buffered; const numRanges = buf.length; if (buf.length === 1) { // only one range if (buf.start(0) === 0 && buf.end(0) === v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } ``` This example looks at the time ranges and looks to see if the entire video has been loaded. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/timeranges
data/mdn-content/files/en-us/web/api/timeranges/end/index.md
--- title: "TimeRanges: end() method" short-title: end() slug: Web/API/TimeRanges/end page-type: web-api-instance-method browser-compat: api.TimeRanges.end --- {{APIRef("DOM")}} The **`end()`** method of the {{domxref("TimeRanges")}} interface returns the time offset at which a specified time range ends. ## Syntax ```js-nolint end(index) ``` ### Parameters - `index` - : The range number to return the ending time for. ### Return value A number. ### Exceptions - `IndexSizeError` {{domxref("DOMException")}} - : Thrown if the specified index doesn't correspond to an existing range. ## Examples Given a video element with the ID `"myVideo"`: ```js const v = document.getElementById("myVideo"); const buf = v.buffered; const numRanges = buf.length; if (buf.length === 1) { // only one range if (buf.start(0) === 0 && buf.end(0) === v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } ``` This example looks at the time ranges and looks to see if the entire video has been loaded. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlhtmlelement/index.md
--- title: HTMLHtmlElement slug: Web/API/HTMLHtmlElement page-type: web-api-interface browser-compat: api.HTMLHtmlElement --- {{ APIRef("HTML DOM") }} The **`HTMLHtmlElement`** interface serves as the root node for a given HTML document. This object inherits the properties and methods described in the {{domxref("HTMLElement")}} interface. You can retrieve the `HTMLHtmlElement` object for a given document by reading the value of the {{domxref("document.documentElement")}} property. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLHtmlElement.version")}} {{deprecated_inline}} - : A string representing the version of the HTML Document Type Definition (DTD) that governs this document. This property should not be used any more as it is non-conforming. Omit it. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML element implementing this interface: {{HTMLElement("html")}}.
0
data/mdn-content/files/en-us/web/api/htmlhtmlelement
data/mdn-content/files/en-us/web/api/htmlhtmlelement/version/index.md
--- title: "HTMLHtmlElement: version property" short-title: version slug: Web/API/HTMLHtmlElement/version page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLHtmlElement.version --- {{ APIRef("HTML DOM") }} {{deprecated_header}} > **Note:** This property has been declared as deprecated by the W3C technical recommendation for HTML 4.01 in favor of use of the DTD for obtaining version information for a document. Returns version information about the document type definition (DTD) of a document. While this property is recognized by Mozilla, the return value for this property is always an empty string. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtcrtpscripttransform/index.md
--- title: RTCRtpScriptTransform slug: Web/API/RTCRtpScriptTransform page-type: web-api-interface browser-compat: api.RTCRtpScriptTransform --- {{APIRef("WebRTC")}} The **`RTCRtpScriptTransform`** interface of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) is used to insert a [WebRTC Encoded Transform](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms) (a {{domxref("TransformStream")}} running in a worker thread) into the WebRTC sender and receiver pipelines. ## Constructor - {{DOMxRef("RTCRtpScriptTransform.RTCRtpScriptTransform", "RTCRtpScriptTransform()")}} - : Creates a new instance of the `RTCRtpScriptTransform` object. ## Instance properties None. ## Instance methods None. ## Description **`RTCRtpScriptTransform`** instances are constructed with a {{domxref("Worker")}}, in which the transform stream code will run, along with an (optional) `options` object and array of [transferrable object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) that will be passed to the worker. They are then added into incoming and outgoing RTC pipelines by assigning them to {{domxref("RTCRtpReceiver.transform")}} and {{domxref("RTCRtpSender.transform")}}, respectively. On construction of this object, and whenever an encoded frame arrives, the {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event is fired on the worker global object. The event's `transformer` property is a {{DOMxRef("RTCRtpScriptTransformer")}}, the worker-side counterpart to the main-thread `RTCRtpScriptTransform`. This has `readable` ({{domxref("ReadableStream")}}) and `writable` ({{domxref("WritableStream")}}) properties that have been shared from the main thread `RTCRtpScriptTransform` — where they are not public. If the corresponding `RTCRtpScriptTransform` is used with an `RTCRtpReceiver`, then the `readable` queues incoming encoded audio or video frames from the packetizer. If it is used with `RTCRtpSender` then `readable` contains frames coming from a codec. The worker thread {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event handler defines a [pipe chain](/en-US/docs/Web/API/Streams_API/Concepts#pipe_chains). This pipes encoded frames from `event.transformer.readable`, through a {{DOMxRef("TransformStream")}} which defines the transformation function, through to `event.transformer.writable`. The `event.transformer` also has the `options` object passed from the `RTCRtpScriptTransform` constructor (if defined) that can be used to determine the source of the event, and hence the specific {{DOMxRef("TransformStream")}} to add to the chain. ## Examples Note that these examples show how `RTCRtpScriptTransform` is defined and used. Worker thread transform code is covered as part of the more complete example in [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms). ### Adding a transform for outgoing frames This example shows how you might stream video from a user's webcam over WebRTC, adding a WebRTC encoded transform to modify the outgoing streams. The code assumes that there is an {{domxref("RTCPeerConnection")}} called `peerConnection` that is already connected to a remote peer. First we gets a {{domxref("MediaStreamTrack")}}, using {{domxref("MediaDevices/getUserMedia", "getUserMedia()")}} to get a video {{domxref("MediaStream")}} from a media device, and then the {{domxref("MediaStream.getTracks()")}} method to get the first {{domxref("MediaStreamTrack")}} in the stream. The track is added to the peer connection using {{domxref("RTCPeerConnection/addTrack()", "addTrack()")}} and sent. The `addTrack()` method returns the {{domxref("RTCRtpSender")}} that is being used to send the track. ```js // Get Video stream and MediaTrack const stream = await navigator.mediaDevices.getUserMedia({ video: true }); const [track] = stream.getTracks(); const videoSender = peerConnection.addTrack(track, stream); ``` An `RTCRtpScriptTransform` is then constructed taking a worker script, which defines the transform, and an optional object that can be used to pass arbitrary messages to the worker (in this case we've used a `name` property with value "senderTransform" to tell the worker that this transform will be added to the outbound stream). We then add the transform to the sender by assigning it to the {{domxref("RTCRtpSender.transform")}} property. ```js // Create a worker containing a TransformStream const worker = new Worker("worker.js"); videoSender.transform = new RTCRtpScriptTransform(worker, { name: "senderTransform", }); ``` Note that you can add the transform at any time. However by adding it immediately after calling `addTrack()` the transform will get the first encoded frame that is sent. ### Adding a transform for incoming frames This example shows how you add a WebRTC encoded transform to modify an incoming stream. The code assumes that there is an {{domxref("RTCPeerConnection")}} called `peerConnection` that is already connected to a remote peer. First we add an `RTCPeerConnection` [`track` event](/en-US/docs/Web/API/RTCPeerConnection/track_event) handler to catch the event when a new track is streamed. Within the handler we construct an `RTCRtpScriptTransform` and add it to `event.receiver.transform` (`event.receiver` is a {{domxref("RTCRtpReceiver")}}). As in the previous example, the constructor takes an object with `name` property: but here we use `receiverTransform` as the value to tell the worker that frames are incoming from the packetizer. ```js peerConnection.ontrack = (event) => { const worker = new Worker("worker.js"); event.receiver.transform = new RTCRtpScriptTransform(worker, { name: "receiverTransform", }); received_video.srcObject = event.streams[0]; }; ``` Note again that you can add the transform stream at any time. However by adding it in the `track` event handler ensures that the transform stream will get the first encoded frame for the track. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms) - {{domxref("TransformStream")}} - {{domxref("RTCRtpScriptTransformer")}}
0
data/mdn-content/files/en-us/web/api/rtcrtpscripttransform
data/mdn-content/files/en-us/web/api/rtcrtpscripttransform/rtcrtpscripttransform/index.md
--- title: "RTCRtpScriptTransform: RTCRtpScriptTransform() constructor" short-title: RTCRtpScriptTransform() slug: Web/API/RTCRtpScriptTransform/RTCRtpScriptTransform page-type: web-api-constructor browser-compat: api.RTCRtpScriptTransform.RTCRtpScriptTransform --- {{APIRef("WebRTC")}} The **`RTCRtpScriptTransform()`** constructor creates a new {{domxref("RTCRtpScriptTransform")}} object. Constructing the `RTCRtpScriptTransform` creates a counterpart {{domxref("RTCRtpScriptTransformer")}} in the specified worker, along with passed options (if any). Objects in the third parameter to the constructor are transferred. The {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event is then fired at the worker global object. Worker code can use the `event.transformer` property to get the counterpart {{domxref("RTCRtpScriptTransformer")}}, and `event.transformer.options` is used to get the options. Note that the options are primarily used to inform the worker whether the transformer is processing incoming or outgoing frames, so that it can apply an appropriate transform. ## Syntax ```js-nolint new RTCRtpScriptTransform(worker) new RTCRtpScriptTransform(worker, options) new RTCRtpScriptTransform(worker, options, transfer) ``` ### Parameters - `worker` - : A {{domxref("Worker")}}, which will define code for one or more WebRTC transform streams. - `options` {{optional_inline}} - : An arbitrary object that will be made available in the worker. This is most commonly used to inform the worker whether it injected into the WebRTC sender or receiver pipeline, and hence which transform should be applied. However it may also be used to send any other object, such as a {{domxref("MessagePort")}} for communicating dynamically with the transformer. - `transfer` {{optional_inline}} - : An optional [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) that will be transferred to the worker. After transfer, these objects are unusable in the main thread. ### Exceptions - `DataCloneError` {{domxref("DOMException")}} - : Thrown if an object in `transfer` cannot be transferred. ## Examples The first example below shows construction of a {{domxref("RTCRtpScriptTransform")}} that is then assigned to a {{domxref("RTCRtpSender.transform")}}. The constructor takes an optional object with the property `name` and `senderTransform`. The worker can use this option to understand when it is transforming encoded frames from the encoder (rather than incoming frames from the packetizer). ```js // Create a worker containing a TransformStream const worker = new Worker("worker.js"); videoSender.transform = new RTCRtpScriptTransform(worker, { name: "senderTransform", }); ``` Any property name and value can be used in the options, as long as they can be serialized (and [transferred](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) if specified in the last constructor parameter). The code below transfers the second port of a {{domxref("MessageChannel")}} to the worker, which we might do in order to dynamically update transform code with (say) a new encryption key. ```js // Create a worker containing a TransformStream const worker = new Worker("worker.js"); const channel = new MessageChannel(); const transform = new RTCRtpScriptTransform( worker, { purpose: "encrypt", port: channel.port2 }, [channel.port2], ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms) - {{domxref("RTCRtpSender.transform")}} - {{domxref("RTCRtpReceiver.transform")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssprimitivevalue/index.md
--- title: CSSPrimitiveValue slug: Web/API/CSSPrimitiveValue page-type: web-api-interface status: - deprecated browser-compat: api.CSSPrimitiveValue --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`CSSPrimitiveValue`** interface derives from the {{DOMxRef("CSSValue")}} interface and represents the current computed value of a CSS property. > **Note:** This interface was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. This interface represents a single CSS value. It may be used to determine the value of a specific style property currently set in a block or to set a specific style property explicitly within the block. An instance of this interface might be obtained from the {{DOMxRef("CSSStyleDeclaration.getPropertyCSSValue()", "getPropertyCSSValue()")}} method of the {{DOMxRef("CSSStyleDeclaration")}} interface. A `CSSPrimitiveValue` object only occurs in a context of a CSS property. Conversions are allowed between absolute values (from millimeters to centimeters, from degrees to radians, and so on) but not between relative values. (For example, a pixel value cannot be converted to a centimeter value.) Percentage values can't be converted since they are relative to the parent value (or another property value). There is one exception for color percentage values: since a color percentage value is relative to the range 0-255, a color percentage value can be converted to a number (see also the {{DOMxRef("RGBColor")}} interface). {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{DOMxRef("CSSValue")}}_. - {{DOMxRef("CSSPrimitiveValue.primitiveType")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : An `unsigned short` representing the type of the value. Possible values are: | Constant | Description | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CSS_ATTR` | The value is an {{CSSxRef("attr", "attr()")}} function. The value can be obtained by using the `getStringValue()` method. | | `CSS_CM` | The value is a {{CSSxRef("&lt;length&gt;")}} in centimeters. The value can be obtained by using the `getFloatValue()` method. | | `CSS_COUNTER` | The value is a [counter or counters](/en-US/docs/Web/CSS/CSS_counter_styles/Using_CSS_counters) function. The value can be obtained by using the `getCounterValue()` method. | | `CSS_DEG` | The value is an {{CSSxRef("&lt;angle&gt;")}} in degrees. The value can be obtained by using the `getFloatValue()` method. | | `CSS_DIMENSION` | The value is a {{CSSxRef("&lt;number&gt;")}} with an unknown dimension. The value can be obtained by using the `getFloatValue()` method. | | `CSS_EMS` | The value is a {{CSSxRef("&lt;length&gt;")}} in em units. The value can be obtained by using the `getFloatValue()` method. | | `CSS_EXS` | The value is a {{CSSxRef("&lt;length&gt;")}} in ex units. The value can be obtained by using the `getFloatValue()` method. | | `CSS_GRAD` | The value is an {{CSSxRef("&lt;angle&gt;")}} in grads. The value can be obtained by using the `getFloatValue()` method. | | `CSS_HZ` | The value is a {{CSSxRef("&lt;frequency&gt;")}} in Hertz. The value can be obtained by using the getFloatValue method. | | `CSS_IDENT` | The value is an identifier. The value can be obtained by using the `getStringValue()` method. | | `CSS_IN` | The value is a {{CSSxRef("&lt;length&gt;")}} in inches. The value can be obtained by using the `getFloatValue()` method. | | `CSS_KHZ` | The value is a {{CSSxRef("&lt;frequency&gt;")}} in Kilohertz. The value can be obtained by using the `getFloatValue()` method. | | `CSS_MM` | The value is a {{CSSxRef("&lt;length&gt;")}} in millimeters. The value can be obtained by using the `getFloatValue()` method. | | `CSS_MS` | The value is a {{CSSxRef("&lt;time&gt;")}} in milliseconds. The value can be obtained by using the `getFloatValue()` method. | | `CSS_NUMBER` | The value is a simple {{CSSxRef("&lt;number&gt;")}}. The value can be obtained by using the `getFloatValue()` method. | | `CSS_PC` | The value is a {{CSSxRef("&lt;length&gt;")}} in picas. The value can be obtained by using the `getFloatValue()` method. | | `CSS_PERCENTAGE` | The value is a {{CSSxRef("&lt;percentage&gt;")}}. The value can be obtained by using the `getFloatValue()` method. | | `CSS_PT` | The value is a {{CSSxRef("&lt;length&gt;")}} in points. The value can be obtained by using the `getFloatValue()` method. | | `CSS_PX` | The value is a {{CSSxRef("&lt;length&gt;")}} in pixels. The value can be obtained by using the `getFloatValue()` method. | | `CSS_RAD` | The value is an {{CSSxRef("&lt;angle&gt;")}} in radians. The value can be obtained by using the `getFloatValue()` method. | | `CSS_RECT` | The value is a {{CSSxRef("shape", "rect()", "#Syntax")}} function. The value can be obtained by using the `getRectValue()` method. | | `CSS_RGBCOLOR` | The value is an {{CSSxRef("&lt;color&gt;")}}. The value can be obtained by using the `getRGBColorValue()` method. | | `CSS_S` | The value is a {{CSSxRef("&lt;time&gt;")}} in seconds. The value can be obtained by using the `getFloatValue()` method. | | `CSS_STRING` | The value is a {{CSSxRef("&lt;string&gt;")}}. The value can be obtained by using the `getStringValue()` method. | | `CSS_UNKNOWN` | The value is not a recognized CSS2 value. The value can only be obtained by using the {{DOMxRef("CSSValue.cssText", "cssText")}} attribute. | | `CSS_URI` | The value is a {{CSSxRef("url", "url()")}}. The value can be obtained by using the `getStringValue()` method. | ## Instance methods - {{DOMxRef("CSSPrimitiveValue.getCounterValue()")}} {{Deprecated_Inline}} - : This method is used to get the [counter](/en-US/docs/Web/CSS/CSS_counter_styles/Using_CSS_counters) value. If this CSS value doesn't contain a counter value, a {{DOMxRef("DOMException")}} is raised. Modification to the corresponding style property can be achieved using the {{DOMxRef("Counter")}} interface. - {{DOMxRef("CSSPrimitiveValue.getFloatValue()")}} {{Deprecated_Inline}} - : This method is used to get a float value in a specified unit. If this CSS value doesn't contain a float value or can't be converted into the specified unit, a {{DOMxRef("DOMException")}} is raised. - {{DOMxRef("CSSPrimitiveValue.getRGBColorValue()")}} {{Deprecated_Inline}} - : This method is used to get the RGB color. If this CSS value doesn't contain a RGB color value, a {{DOMxRef("DOMException")}} is raised. Modification to the corresponding style property can be achieved using the {{DOMxRef("RGBColor")}} interface. - {{DOMxRef("CSSPrimitiveValue.getRectValue()")}} {{Deprecated_Inline}} - : This method is used to get the Rect value. If this CSS value doesn't contain a rect value, a {{DOMxRef("DOMException")}} is raised. Modification to the corresponding style property can be achieved using the {{DOMxRef("Rect")}} interface. - {{DOMxRef("CSSPrimitiveValue.getStringValue()")}} {{Deprecated_Inline}} - : This method is used to get the string value. If the CSS value doesn't contain a string value, a {{DOMxRef("DOMException")}} is raised. - {{DOMxRef("CSSPrimitiveValue.setFloatValue()")}} {{Deprecated_Inline}} - : A method to set the float value with a specified unit. If the property attached with this value can not accept the specified unit or the float value, the value will be unchanged and a {{DOMxRef("DOMException")}} will be raised. - {{DOMxRef("CSSPrimitiveValue.setStringValue()")}} {{Deprecated_Inline}} - : A method to set the string value with the specified unit. If the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a {{DOMxRef("DOMException")}} will be raised. ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("CSSValue")}} - {{DOMxRef("CSSValueList")}}
0
data/mdn-content/files/en-us/web/api/cssprimitivevalue
data/mdn-content/files/en-us/web/api/cssprimitivevalue/getstringvalue/index.md
--- title: "CSSPrimitiveValue: getStringValue() method" short-title: getStringValue() slug: Web/API/CSSPrimitiveValue/getStringValue page-type: web-api-instance-method status: - deprecated browser-compat: api.CSSPrimitiveValue.getStringValue --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`getStringValue()`** method of the {{domxref("CSSPrimitiveValue")}} interface is used to get a string value. If this CSS value doesn't contain a string value, a {{domxref("DOMException")}} is raised. > **Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Syntax ```js-nolint getStringValue() ``` ### Parameters None. ### Return value A `string` value. ### Exceptions | **Type** | **Description** | | -------------- | ---------------------------------------------------------------------------------- | | `DOMException` | An `INVALID_ACCESS_ERR` is raised if the CSS value doesn't contain a string value. | ## Examples ```js const cs = window.getComputedStyle(document.body); const cssValue = cs.getPropertyCSSValue("display"); console.log(cssValue.getStringValue()); ``` ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssprimitivevalue
data/mdn-content/files/en-us/web/api/cssprimitivevalue/getcountervalue/index.md
--- title: "CSSPrimitiveValue: getCounterValue() method" short-title: getCounterValue() slug: Web/API/CSSPrimitiveValue/getCounterValue page-type: web-api-instance-method status: - deprecated browser-compat: api.CSSPrimitiveValue.getCounterValue --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`getCounterValue()`** method of the {{domxref("CSSPrimitiveValue")}} interface is used to get the [counter](/en-US/docs/Web/CSS/CSS_counter_styles/Using_CSS_counters) value. If this CSS value doesn't contain a counter value, a {{domxref("DOMException")}} is raised. Modification to the corresponding style property can be achieved using the {{domxref("Counter")}} interface. > **Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Syntax ```js-nolint getCounterValue() ``` ### Parameters None. ### Return value A {{domxref("Counter")}} object representing the counter value. ### Exceptions | **Type** | **Description** | | -------------- | ---------------------------------------------------------------------------------------------------------------------- | | `DOMException` | An `INVALID_ACCESS_ERR` is raised if the CSS value doesn't contain a `Counter` value (e.g. this is not `CSS_COUNTER`). | ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssprimitivevalue
data/mdn-content/files/en-us/web/api/cssprimitivevalue/setfloatvalue/index.md
--- title: "CSSPrimitiveValue: setFloatValue() method" short-title: setFloatValue() slug: Web/API/CSSPrimitiveValue/setFloatValue page-type: web-api-instance-method status: - deprecated browser-compat: api.CSSPrimitiveValue.setFloatValue --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`setFloatValue()`** method of the {{domxref("CSSPrimitiveValue")}} interface is used to set a float value. If the property attached to this value can't accept the specified unit or the float value, the value will be unchanged and a {{domxref("DOMException")}} will be raised. > **Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Syntax ```js-nolint setFloatValue(unitType, floatValue) ``` ### Parameters - `unitType` - : An `unsigned short` representing the code for the unit type, in which the value should be returned. Valid values are: | Constant | Description | | ---------------- | ---------------------------------------------------------------------------------------------------------------------- | | `CSS_CM` | The value is a {{cssxref("&lt;length&gt;")}} in centimeters. | | `CSS_DEG` | The value is an {{cssxref("&lt;angle&gt;")}} in degrees. | | `CSS_DIMENSION` | The value is a {{cssxref("&lt;number&gt;")}} with an unknown dimension. | | `CSS_EMS` | The value is a {{cssxref("&lt;length&gt;")}} in em units. | | `CSS_EXS` | The value is a {{cssxref("&lt;length&gt;")}} in ex units. | | `CSS_GRAD` | The value is an {{cssxref("&lt;angle&gt;")}} in grads. | | `CSS_HZ` | The value is a {{cssxref("&lt;frequency&gt;")}} in Hertz. The value can be obtained by using the getFloatValue method. | | `CSS_IN` | The value is a {{cssxref("&lt;length&gt;")}} in inches. | | `CSS_KHZ` | The value is a {{cssxref("&lt;frequency&gt;")}} in Kilohertz. | | `CSS_MM` | The value is a {{cssxref("&lt;length&gt;")}} in millimeters. | | `CSS_MS` | The value is a {{cssxref("&lt;time&gt;")}} in milliseconds. | | `CSS_NUMBER` | The value is a simple {{cssxref("&lt;number&gt;")}}. | | `CSS_PC` | The value is a {{cssxref("&lt;length&gt;")}} in picas. | | `CSS_PERCENTAGE` | The value is a {{cssxref("&lt;percentage&gt;")}}. | | `CSS_PT` | The value is a {{cssxref("&lt;length&gt;")}} in points. | | `CSS_PX` | The value is a {{cssxref("&lt;length&gt;")}} in pixels. | | `CSS_RAD` | The value is an {{cssxref("&lt;angle&gt;")}} in radians. | | `CSS_S` | The value is a {{cssxref("&lt;time&gt;")}} in seconds. | - `floatValue` - : A `float` representing the new float value. ### Return value None ({{jsxref("undefined")}}). ### Exceptions <table class="no-markdown"> <thead> <tr> <th scope="col"><strong>Type</strong></th> <th scope="col"><strong>Description</strong></th> </tr> </thead> <tbody> <tr> <td><code>DOMException</code></td> <td> An <code>INVALID_ACCESS_ERR</code> is raised if the CSS value doesn't contain a float value or if the string value can't be converted into the specified unit.<br />An NO_MODIFICATION_ALLOWED_ERR is raised if this property is read-only. </td> </tr> </tbody> </table> ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssprimitivevalue
data/mdn-content/files/en-us/web/api/cssprimitivevalue/getrgbcolorvalue/index.md
--- title: "CSSPrimitiveValue: getRGBColorValue() method" short-title: getRGBColorValue() slug: Web/API/CSSPrimitiveValue/getRGBColorValue page-type: web-api-instance-method status: - deprecated browser-compat: api.CSSPrimitiveValue.getRGBColorValue --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`getRGBColorValue()`** method of the {{domxref("CSSPrimitiveValue")}} interface is used to get an RGB color value. If this CSS value doesn't contain a RGB color value, a {{domxref("DOMException")}} is raised. Modification to the corresponding style property can be achieved using the {{domxref("RGBColor")}} interface. > **Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Syntax ```js-nolint getRGBColorValue() ``` ### Parameters None. ### Return value An {{domxref("RGBColor")}} object representing the color value. ### Exceptions | **Type** | **Description** | | -------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `DOMException` | An `INVALID_ACCESS_ERR` is raised if the attached property can't return an RGB color value (i.e. this is not `CSS_RGBCOLOR`). | ## Examples ```js const cs = window.getComputedStyle(document.body); const cssValue = cs.getPropertyCSSValue("color"); console.log(cssValue.getRGBColorValue()); ``` ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssprimitivevalue
data/mdn-content/files/en-us/web/api/cssprimitivevalue/primitivetype/index.md
--- title: "CSSPrimitiveValue: primitiveType property" short-title: primitiveType slug: Web/API/CSSPrimitiveValue/primitiveType page-type: web-api-instance-property status: - deprecated browser-compat: api.CSSPrimitiveValue.primitiveType --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`primitiveType`** read-only property of the {{domxref("CSSPrimitiveValue")}} interface represents the type of a CSS value. > **Note:** This property was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Value An `unsigned short` representing the type of the value. Possible values are: <table class="no-markdown"> <thead> <tr> <th>Constant</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>CSS_ATTR</code></td> <td> The value is an {{cssxref("attr", "attr()")}} function. The value can be obtained by using the <code>getStringValue()</code> method. </td> </tr> <tr> <td><code>CSS_CM</code></td> <td> The value is a {{cssxref("&lt;length&gt;")}} in centimeters. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_COUNTER</code></td> <td> The value is a <a href="/en-US/docs/Web/CSS/CSS_Counter_Styles/Using_CSS_counters" >counter or counters</a > function. The value can be obtained by using the <code>getCounterValue()</code> method. </td> </tr> <tr> <td><code>CSS_DEG</code></td> <td> The value is an {{cssxref("&lt;angle&gt;")}} in degrees. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_DIMENSION</code></td> <td> The value is a {{cssxref("&lt;number&gt;")}} with an unknown dimension. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_EMS</code></td> <td> The value is a {{cssxref("&lt;length&gt;")}} in em units. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_EXS</code></td> <td> The value is a {{cssxref("&lt;length&gt;")}} in ex units. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_GRAD</code></td> <td> The value is an {{cssxref("&lt;angle&gt;")}} in grads. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_HZ</code></td> <td> The value is a {{cssxref("&lt;frequency&gt;")}} in Hertz. The value can be obtained by using the getFloatValue method. </td> </tr> <tr> <td><code>CSS_IDENT</code></td> <td> The value is an identifier. The value can be obtained by using the <code>getStringValue()</code> method. </td> </tr> <tr> <td><code>CSS_IN</code></td> <td> The value is a {{cssxref("&lt;length&gt;")}} in inches. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_KHZ</code></td> <td> The value is a {{cssxref("&lt;frequency&gt;")}} in Kilohertz. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_MM</code></td> <td> The value is a {{cssxref("&lt;length&gt;")}} in millimeters. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_MS</code></td> <td> The value is a {{cssxref("&lt;time&gt;")}} in milliseconds. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_NUMBER</code></td> <td> The value is a simple {{cssxref("&lt;number&gt;")}}. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_PC</code></td> <td> The value is a {{cssxref("&lt;length&gt;")}} in picas. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_PERCENTAGE</code></td> <td> The value is a {{cssxref("&lt;percentage&gt;")}}. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_PT</code></td> <td> The value is a {{cssxref("&lt;length&gt;")}} in points. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_PX</code></td> <td> The value is a {{cssxref("&lt;length&gt;")}} in pixels. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_RAD</code></td> <td> The value is an {{cssxref("&lt;angle&gt;")}} in radians. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_RECT</code></td> <td> The value is a {{cssxref("shape", "rect()", "#Syntax")}} function. The value can be obtained by using the <code>getRectValue()</code> method. </td> </tr> <tr> <td><code>CSS_RGBCOLOR</code></td> <td> The value is an {{cssxref("&lt;color&gt;")}}. The value can be obtained by using the <code>getRGBColorValue()</code> method. </td> </tr> <tr> <td><code>CSS_S</code></td> <td> The value is a {{cssxref("&lt;time&gt;")}} in seconds. The value can be obtained by using the <code>getFloatValue()</code> method. </td> </tr> <tr> <td><code>CSS_STRING</code></td> <td> The value is a {{cssxref("&lt;string&gt;")}}. The value can be obtained by using the <code>getStringValue()</code> method. </td> </tr> <tr> <td><code>CSS_UNKNOWN</code></td> <td> The value is not a recognized CSS2 value. The value can only be obtained by using the {{domxref("CSSValue.cssText", "cssText")}} attribute. </td> </tr> <tr> <td><code>CSS_URI</code></td> <td> The value is a {{cssxref("url", "url()")}}. The value can be obtained by using the <code>getStringValue()</code> method. </td> </tr> </tbody> </table> ## Examples ```js const cs = window.getComputedStyle(document.body); const cssValue = cs.getPropertyCSSValue("color"); console.log(cssValue.primitiveType); ``` ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}} ## See also - {{domxref("CSSStyleDeclaration.getPropertyCSSValue()")}}
0
data/mdn-content/files/en-us/web/api/cssprimitivevalue
data/mdn-content/files/en-us/web/api/cssprimitivevalue/setstringvalue/index.md
--- title: "CSSPrimitiveValue: setStringValue() method" short-title: setStringValue() slug: Web/API/CSSPrimitiveValue/setStringValue page-type: web-api-instance-method status: - deprecated browser-compat: api.CSSPrimitiveValue.setStringValue --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`setStringValue()`** method of the {{domxref("CSSPrimitiveValue")}} interface is used to set a string value. If the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a {{domxref("DOMException")}} will be raised. > **Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Syntax ```js-nolint setStringValue(stringType, stringValue) ``` ### Parameters - `stringType` - : An `unsigned short` representing the type of the value. Possible values are: | Constant | Description | | ------------ | ------------------------------------------------------- | | `CSS_ATTR` | The value is an {{cssxref("attr", "attr()")}} function. | | `CSS_IDENT` | The value is an identifier. | | `CSS_STRING` | The value is a {{cssxref("&lt;string&gt;")}}. | | `CSS_URI` | The value is a {{cssxref("url", "url()")}}. | - `stringValue` - : A string representing the new string value. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if the CSS value doesn't contain a string value or if the string value can't be converted into the specified unit. - `NoModificationAllowedError' {{domxref("DOMException")}} - : Thrown if the property is read-only. ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssprimitivevalue
data/mdn-content/files/en-us/web/api/cssprimitivevalue/getrectvalue/index.md
--- title: "CSSPrimitiveValue: getRectValue() method" short-title: getRectValue() slug: Web/API/CSSPrimitiveValue/getRectValue page-type: web-api-instance-method status: - deprecated browser-compat: api.CSSPrimitiveValue.getRectValue --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`getRectValue()`** method of the {{domxref("CSSPrimitiveValue")}} interface is used to get a rect value. If this CSS value doesn't contain a rect value, a {{domxref("DOMException")}} is raised. Modification to the corresponding style property can be achieved using the {{domxref("Rect")}} interface. > **Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Syntax ```js-nolint getRectValue() ``` ### Parameters None. ### Return value A {{domxref("Rect")}} object representing the rect value. ### Exceptions | **Type** | **Description** | | -------------- | --------------------------------------------------------------------------------------------------------------- | | `DOMException` | An `INVALID_ACCESS_ERR` is raised if the CSS value doesn't contain a Rect value. (i.e. this is not `CSS_RECT`). | ## Examples ```js const cs = window.getComputedStyle(document.getElementById("clippedDiv")); const cssValue = cs.getPropertyCSSValue("clip"); console.log(cssValue.getRectValue()); ``` ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssprimitivevalue
data/mdn-content/files/en-us/web/api/cssprimitivevalue/getfloatvalue/index.md
--- title: "CSSPrimitiveValue: getFloatValue() method" short-title: getFloatValue() slug: Web/API/CSSPrimitiveValue/getFloatValue page-type: web-api-instance-method status: - deprecated browser-compat: api.CSSPrimitiveValue.getFloatValue --- {{APIRef("CSSOM")}}{{deprecated_header}} The **`getFloatValue()`** method of the {{domxref("CSSPrimitiveValue")}} interface is used to get a float value in a specified unit. If this CSS value doesn't contain a float value or can't be converted into the specified unit, a {{domxref("DOMException")}} is raised. > **Note:** This method was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do > not implement it. > > To achieve your purpose, you can use: > > - the untyped [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model), widely supported, or > - the modern [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API), less supported and considered experimental. ## Syntax ```js-nolint getFloatValue(unit) ``` ### Parameters - `unit` - : An `unsigned short` representing the code for the unit type, in which the value should be returned. Valid values are: | Constant | Description | | ---------------- | ---------------------------------------------------------------------------------------------------------------------- | | `CSS_CM` | The value is a {{cssxref("&lt;length&gt;")}} in centimeters. | | `CSS_DEG` | The value is an {{cssxref("&lt;angle&gt;")}} in degrees. | | `CSS_DIMENSION` | The value is a {{cssxref("&lt;number&gt;")}} with an unknown dimension. | | `CSS_EMS` | The value is a {{cssxref("&lt;length&gt;")}} in em units. | | `CSS_EXS` | The value is a {{cssxref("&lt;length&gt;")}} in ex units. | | `CSS_GRAD` | The value is an {{cssxref("&lt;angle&gt;")}} in grads. | | `CSS_HZ` | The value is a {{cssxref("&lt;frequency&gt;")}} in Hertz. The value can be obtained by using the getFloatValue method. | | `CSS_IN` | The value is a {{cssxref("&lt;length&gt;")}} in inches. | | `CSS_KHZ` | The value is a {{cssxref("&lt;frequency&gt;")}} in Kilohertz. | | `CSS_MM` | The value is a {{cssxref("&lt;length&gt;")}} in millimeters. | | `CSS_MS` | The value is a {{cssxref("&lt;time&gt;")}} in milliseconds. | | `CSS_NUMBER` | The value is a simple {{cssxref("&lt;number&gt;")}}. | | `CSS_PC` | The value is a {{cssxref("&lt;length&gt;")}} in picas. | | `CSS_PERCENTAGE` | The value is a {{cssxref("&lt;percentage&gt;")}}. | | `CSS_PT` | The value is a {{cssxref("&lt;length&gt;")}} in points. | | `CSS_PX` | The value is a {{cssxref("&lt;length&gt;")}} in pixels. | | `CSS_RAD` | The value is an {{cssxref("&lt;angle&gt;")}} in radians. | | `CSS_S` | The value is a {{cssxref("&lt;time&gt;")}} in seconds. | ### Return value A `float` value in the specified unit. ### Exceptions <table class="no-markdown"> <thead> <tr> <th scope="col"><strong>Type</strong></th> <th scope="col"><strong>Description</strong></th> </tr> </thead> <tbody> <tr> <td><code>DOMException</code></td> <td> An <code>INVALID_ACCESS_ERR</code> is raised if the CSS value doesn't contain a float value or if the float value can't be converted into the specified unit. </td> </tr> </tbody> </table> ## Examples ```js const cs = window.getComputedStyle(document.body); const cssValue = cs.getPropertyCSSValue("margin-top"); console.log(cssValue.getFloatValue(CSSPrimitiveValue.CSS_CM)); ``` ## Specifications This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API) that is now on the standard track. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/barprop/index.md
--- title: BarProp slug: Web/API/BarProp page-type: web-api-interface browser-compat: api.BarProp --- {{APIRef("DOM")}} The **`BarProp`** interface of the {{domxref('Document Object Model')}} represents the web browser user interface elements that are exposed to scripts in web pages. Each of the following interface elements are represented by a `BarProp` object. - {{domxref("Window.locationbar")}} - : The browser location bar. - {{domxref("Window.menubar")}} - : The browser menu bar. - {{domxref("Window.personalbar")}} - : The browser personal bar. - {{domxref("Window.scrollbars")}} - : The browser scrollbars. - {{domxref("Window.statusbar")}} - : The browser status bar. - {{domxref("Window.toolbar")}} - : The browser toolbar. The `BarProp` interface is not accessed directly, but via one of these elements. ## Instance properties - {{domxref("BarProp.visible")}} {{ReadOnlyInline}} - : A {{jsxref("Boolean")}}, which is true if the bar represented by the used interface element is visible. ## Examples The following example prints a `BarProp` object to the console that represents the location bar. ```js console.log(window.locationbar); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/barprop
data/mdn-content/files/en-us/web/api/barprop/visible/index.md
--- title: "BarProp: visible property" short-title: visible slug: Web/API/BarProp/visible page-type: web-api-instance-property browser-compat: api.BarProp.visible --- {{APIRef("DOM")}} The **`visible`** read-only property of the {{domxref("BarProp")}} interface returns `true` if the user interface element it represents is visible. ## Value A {{jsxref("Boolean")}}, which is true if the top-level window is opened by {{domxref("window.open")}} with the {{domxref("window.open", "requesting a popup window", "popup_feature", 1)}}. > **Note:** Historically this represented whether the interface element used is visible > or not. But for privacy reasons, this no longer represents the actual visibility of each > interface element. ## Examples The following example prints `true` to the console if the window is not a popup. ```js console.log(window.locationbar.visible); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/css_font_loading_api/index.md
--- title: CSS Font Loading API slug: Web/API/CSS_Font_Loading_API page-type: web-api-overview browser-compat: api.FontFace --- {{DefaultAPISidebar("CSS Font Loading API")}} The CSS Font Loading API provides events and interfaces for dynamically loading font resources. > **Note:** This feature is available in [Web Workers](/en-US/docs/Web/API/Web_Workers_API) (`self.fonts` provides access to {{domxref('FontFaceSet')}}). ## Concepts and usage CSS stylesheets allow authors to use custom fonts; specifying fonts to download using the [`@font-face`](/en-US/docs/Web/CSS/@font-face) rule, and applying them to elements with the [`font-family`](/en-US/docs/Web/CSS/font-family) property. The point at which a font is downloaded is controlled by the user agent. Most agents only fetch and load fonts when they are first needed, which can result in a perceptible delay. The CSS Font Loading API overcomes this problem by letting authors control and track when a font face is fetched and loaded, and when it is added to the font face set owned by the document or worker. Adding a font face to the document or worker font face set allows the user agent to fetch and load the associated font resource automatically if needed. A font face can be loaded either before or after it is added to a font face set, but it _must_ be added to the set before it can be used for drawing. Font faces are defined in {{domxref('FontFace')}} objects, which specify a binary or URL font source and other properties of font in much the same way as the CSS [`@font-face`](/en-US/docs/Web/CSS/@font-face) rule. `FontFace` objects are added to the document or worker {{domxref('FontFaceSet')}} using {{domxref("Document.fonts")}} and {{domxref("WorkerGlobalScope.fonts")}}, respectively. Authors can trigger download of fonts using either `FontFace` or `FontFaceSet`, and monitor loading completion. `FontFaceSet` can additionally be used to determine when all fonts required by a page have loaded and the document layout is complete. The {{domxref('FontFace.status')}} property indicates the font face loading status: `unloaded`, `loading`, `loaded` or `failed`. This status is initially `unloaded`. It is set to `loading` when the file is being downloaded or the font data is being processed, and to `failed` if the font definition is invalid or the font data cannot be loaded. The status is set to `loaded` when the font face data has been successfully fetched (if needed) and loaded. ### Defining a font face Font faces are created using the [`FontFace` constructor](/en-US/docs/Web/API/FontFace/FontFace), which takes as parameters: the font family, the font source, and optional descriptors. The format and grammar of these arguments is the same as the equivalent [`@font-face`](/en-US/docs/Web/CSS/@font-face) definition. The font source can either be binary data in an [`ArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or a font resource at an URL. A typical font face definition using a URL source might be as shown below. Note that the `url()` function is required for URL font sources. ```js const font = new FontFace("myfont", "url(myfont.woff)", { style: "italic", weight: "400", stretch: "condensed", }); ``` > **Note:** As with `@font-face`, some descriptors represent the expected data in the font data and are used for font matching, while others actually set/define properties of the generated font face. > For example, setting the `style` to "italic" indicates that the file contains italic fonts; it is up to the author to specify a file for which this is true. Font faces with a _binary source_ are automatically loaded if the font definition is valid and the font data can be loaded — {{domxref('FontFace.status')}} is set to `loaded` on success and `failed` otherwise. Font faces with a URL source are validated but not automatically loaded — {{domxref('FontFace.status')}} is set `unloaded` if the font face definition is valid and `failed` otherwise. ### Adding a font to a document or worker Font faces are usually added to the document or worker {{domxref('FontFaceSet')}} to allow the user agent to automatically load the font when needed, and _must_ be added in order for the font to be used for rendering text. The code below shows a font face being added to the document. ```js // Define a FontFace const font = new FontFace("myfont", "url(myfont.woff)", { style: "italic", weight: "400", stretch: "condensed", }); // Add to the document.fonts (FontFaceSet) document.fonts.add(font); ``` ### Loading a font A font face can be loaded manually by calling {{domxref('FontFace.load()')}}, or by calling {{domxref('FontFaceSet.load()')}} if the font face has been added to the `FontFaceSet`. Note that attempting to load an already-loaded font has no effect. The code below shows how to define a font face, add it to the document fonts, and then initiate a font load. ```js // Define a FontFace const font = new FontFace("myfont", "url(myfont.woff)"); // Add to the document.fonts (FontFaceSet) document.fonts.add(font); // Load the font font.load(); // Wait until the fonts are all loaded document.fonts.ready.then(() => { // Use the font to render text (for example, in a canvas) }); ``` Note that the `font.load()` returns a promise, so we could have handled the completion of font loading by chaining `then` afterwards. Using [`document.fonts.ready`](/en-US/docs/Web/API/FontFaceSet/ready) can be better in some circumstances, as it is only called when all fonts in the document have been resolved and layout is complete. ## Interfaces - {{domxref('FontFace')}} - : Represents a single usable font face. - {{domxref('FontFaceSet')}} - : An interface loading font faces and checking their download statuses. - {{domxref('FontFaceSetLoadEvent')}} - : Fired whenever a {{domxref("FontFaceSet")}} loads. ## Examples ### Basic font loading This is a very simple example that shows a font being loaded from Google Fonts and used to draw text to a canvas. The example also logs the `status` immediately after creation and after loading. #### HTML This code defines a canvas for drawing to and a textarea for logging. ```html <canvas id="js-canvas"></canvas> <textarea id="log" rows="3" cols="100"></textarea> ``` #### JavaScript First we get the element to which we will log, and the canvas that will be used to render text in the downloaded font. ```js const log = document.getElementById("log"); const canvas = document.getElementById("js-canvas"); canvas.width = 650; canvas.height = 75; ``` Next we define a `FontFace` that has a URL source that is a Google Font and add it to `document.fonts`. We then log the font status, which should be `unloaded`. ```js const bitterFontFace = new FontFace( "FontFamily Bitter", "url(https://fonts.gstatic.com/s/bitter/v7/HEpP8tJXlWaYHimsnXgfCOvvDin1pK8aKteLpeZ5c0A.woff2)", ); document.fonts.add(bitterFontFace); log.textContent += `Bitter font: ${bitterFontFace.status}\n`; // > Bitter font: unloaded ``` Then we call the {{domxref('FontFace.load()')}} method to load the font face, and wait on the returned promise. Once the promise resolves we log the loaded status (which should be `loaded`) and draw text in the loaded font to the canvas. ```js bitterFontFace.load().then( () => { log.textContent += `Bitter font: ${bitterFontFace.status}\n`; // > Bitter font: loaded const ctx = canvas.getContext("2d"); ctx.font = '36px "FontFamily Bitter"'; ctx.fillText("Bitter font loaded", 20, 50); }, (err) => { console.error(err); }, ); ``` Note that we could also have waited on the promise returned by the {{domxref('FontFace.loaded')}} property, or on {{domxref('FontFaceSet.ready')}}. #### Result The result is shown below. It should show the name of the font drawn on the canvas in the downloaded font, and a log showing the load status before and after loading. {{ EmbedLiveSample('Basic font loading', 700, 180) }} ### Font loading with events This example is similar to the previous one, except that it uses {{domxref('FontFaceSet.load()')}} to load the font. It also demonstrates how to listen for font loading events. #### HTML ```html <canvas id="js-canvas"></canvas> <textarea id="log" rows="25" cols="100"></textarea> ``` #### JavaScript The code below defines a canvas context for drawing text, defines a font face, and adds it to the document font face set. ```js const log = document.getElementById("log"); const canvas = document.getElementById("js-canvas"); canvas.width = 650; canvas.height = 75; const ctx = canvas.getContext("2d"); const oxygenFontFace = new FontFace( "FontFamily Oxygen", "url(https://fonts.gstatic.com/s/oxygen/v5/qBSyz106i5ud7wkBU-FrPevvDin1pK8aKteLpeZ5c0A.woff2)", ); document.fonts.add(oxygenFontFace); log.textContent += `Oxygen status: ${oxygenFontFace.status}\n`; ``` Next we use `load()` on the font face set to load the font, specifying which of the fonts to load. The method returns a {{jsxref("Promise")}}. If the promise is resolved we use the font to draw some text. If it is rejected the error is logged. ```js document.fonts.load("36px FontFamily Oxygen").then( (fonts) => { log.textContent += `Bitter font: ${fonts}\n`; // > Oxygen font: loaded log.textContent += `Bitter font: ${oxygenFontFace.status}\n`; // > Oxygen font: loaded ctx.font = '36px "FontFamily Oxygen"'; ctx.fillText("Oxygen font loaded", 20, 50); }, (err) => { console.error(err); }, ); ``` Instead of waiting on a promise we might instead use events to track the font loading operation. The code below listens for the `loading` and `loadingerror` events and logs the number of font faces for each case. In the `loadingdone` event listener we additionally iterate through the font faces and log the family names. ```js document.fonts.addEventListener("loading", (event) => { log.textContent += `loading_event: ${event.fontfaces.length}\n`; }); document.fonts.addEventListener("loadingerror", (event) => { log.textContent += `loadingerror_event: ${event.fontfaces.length}\n`; }); document.fonts.addEventListener("loadingdone", (event) => { log.textContent += `loadingdone_event: ${event.fontfaces.length}\n`; event.fontfaces.forEach((value) => { log.textContent += ` fontface: ${value.family}\n`; }); }); ``` The last bit of code demonstrates how you can monitor the completion of font loading using the promise returned by {{domxref('FontFaceSet.ready')}}. Unlike the other mechanisms this returns when all fonts defined in the document have been downloaded and layout is complete. When the promise resolves we iterate the values in the document's font faces. ```js document.fonts.ready.then(function () { log.textContent += `\nFontFaces in document: ${document.fonts.size}.\n`; for (const fontFace of document.fonts.values()) { log.textContent += "FontFace:\n"; for (const property in fontFace) { log.textContent += ` ${property}: ${fontFace[property]}\n`; } } }); ``` #### Result The output below shows the text drawn in "Oxygen" font. This also shows logging from the events and when the promise returned by `document.fonts.ready` resolves. {{ EmbedLiveSample('Font loading with events', 700, 520) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/bluetoothdevice/index.md
--- title: BluetoothDevice slug: Web/API/BluetoothDevice page-type: web-api-interface status: - experimental browser-compat: api.BluetoothDevice --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The BluetoothDevice interface of the [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API) represents a Bluetooth device inside a particular script execution environment. {{InheritanceDiagram}} ## Instance properties - {{DOMxRef("BluetoothDevice.id")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A string that uniquely identifies a device. - {{DOMxRef("BluetoothDevice.name")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A string that provides a human-readable name for the device. - {{DOMxRef("BluetoothDevice.gatt")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A reference to the device's {{DOMxRef("BluetoothRemoteGATTServer")}}. ## Instance methods - {{DOMxRef("BluetoothDevice.watchAdvertisements()")}} {{Experimental_Inline}} - : A {{jsxref("Promise")}} that resolves to `undefined` or is rejected with an error if advertisements can't be shown for any reason. - {{DOMxRef("BluetoothDevice.forget()")}} {{Experimental_Inline}} - : Provides a way for the page to revoke access to a device the user has granted access to. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/bluetoothdevice
data/mdn-content/files/en-us/web/api/bluetoothdevice/name/index.md
--- title: "BluetoothDevice: name property" short-title: name slug: Web/API/BluetoothDevice/name page-type: web-api-instance-property status: - experimental browser-compat: api.BluetoothDevice.name --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`BluetoothDevice.name`** read-only property returns a string that provides a human-readable name for the device. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/bluetoothdevice
data/mdn-content/files/en-us/web/api/bluetoothdevice/id/index.md
--- title: "BluetoothDevice: id property" short-title: id slug: Web/API/BluetoothDevice/id page-type: web-api-instance-property status: - experimental browser-compat: api.BluetoothDevice.id --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`BluetoothDevice.id`** read-only property returns a string that uniquely identifies a device. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/bluetoothdevice
data/mdn-content/files/en-us/web/api/bluetoothdevice/gatt/index.md
--- title: "BluetoothDevice: gatt property" short-title: gatt slug: Web/API/BluetoothDevice/gatt page-type: web-api-instance-property status: - experimental browser-compat: api.BluetoothDevice.gatt --- {{APIRef("Bluetooth API") }}{{SeeCompatTable}}{{SecureContext_Header}} The **`BluetoothDevice.gatt`** read-only property returns a reference to the device's {{DOMxRef("BluetoothRemoteGATTServer")}}. ## Value A reference to the device's {{DOMxRef("BluetoothRemoteGATTServer")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/resizeobserverentry/index.md
--- title: ResizeObserverEntry slug: Web/API/ResizeObserverEntry page-type: web-api-interface browser-compat: api.ResizeObserverEntry --- {{APIRef("Resize Observer API")}} The **`ResizeObserverEntry`** interface represents the object passed to the {{domxref('ResizeObserver.ResizeObserver','ResizeObserver()')}} constructor's callback function, which allows you to access the new dimensions of the {{domxref("Element")}} or {{domxref("SVGElement")}} being observed. ## Instance properties - {{domxref('ResizeObserverEntry.borderBoxSize')}} {{ReadOnlyInline}} - : An array of objects containing the new border box size of the observed element when the callback is run. - {{domxref('ResizeObserverEntry.contentBoxSize')}} {{ReadOnlyInline}} - : An array of objects containing the new content box size of the observed element when the callback is run. - {{domxref('ResizeObserverEntry.devicePixelContentBoxSize')}} {{ReadOnlyInline}} - : An array of objects containing the new content box size in device pixels of the observed element when the callback is run. - {{domxref('ResizeObserverEntry.contentRect')}} {{ReadOnlyInline}} - : A {{domxref('DOMRectReadOnly')}} object containing the new size of the observed element when the callback is run. Note that this is now a legacy property that is retained in the spec for backward-compatibility reasons only. - {{domxref('ResizeObserverEntry.target')}} {{ReadOnlyInline}} - : A reference to the {{domxref('Element')}} or {{domxref("SVGElement")}} being observed. > **Note:** The content box is the box in which content can be placed, meaning the border box minus the padding and border width. The border box encompasses the content, padding, and border. See [The box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model) for further explanation. ## Instance methods None. ## Examples The following snippet is taken from the [resize-observer-text.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-text.html) ([see source](https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-text.html)) example. Note that the code covers three different compatibility cases: - Some old browsers may support `contentRect` but not `contentBoxSize`. - Old versions of Firefox support `contentBoxSize`, but incorrectly implemented it as a single object rather than an array. - Modern browsers support `contentBoxSize` as an array of objects, to enable them to report box sizes for fragmented elements (for example, in a multi-column scenario). ```js const resizeObserver = new ResizeObserver((entries) => { for (let entry of entries) { if (entry.contentBoxSize) { // The standard makes contentBoxSize an array... if (entry.contentBoxSize[0]) { h1Elem.style.fontSize = Math.max(1.5, entry.contentBoxSize[0].inlineSize / 200) + "rem"; pElem.style.fontSize = Math.max(1, entry.contentBoxSize[0].inlineSize / 600) + "rem"; } else { // ...but old versions of Firefox treat it as a single item h1Elem.style.fontSize = Math.max(1.5, entry.contentBoxSize.inlineSize / 200) + "rem"; pElem.style.fontSize = Math.max(1, entry.contentBoxSize.inlineSize / 600) + "rem"; } } else { h1Elem.style.fontSize = Math.max(1.5, entry.contentRect.width / 200) + "rem"; pElem.style.fontSize = Math.max(1, entry.contentRect.width / 600) + "rem"; } } console.log("Size changed"); }); resizeObserver.observe(divElem); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/resizeobserverentry
data/mdn-content/files/en-us/web/api/resizeobserverentry/target/index.md
--- title: "ResizeObserverEntry: target property" short-title: target slug: Web/API/ResizeObserverEntry/target page-type: web-api-instance-property browser-compat: api.ResizeObserverEntry.target --- {{APIRef("Resize Observer API")}} The **`target`** read-only property of the {{domxref("ResizeObserverEntry")}} interface returns a reference to the {{domxref('Element')}} or {{domxref('SVGElement')}} that is being observed. ## Value An {{domxref('Element')}} or {{domxref('SVGElement')}} representing the element being observed. ## Examples The following snippet is taken from the [resize-observer-border-radius.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-border-radius.html) ([see source](https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-border-radius.html)) example. This example includes a green box, sized as a percentage of the viewport size. When the viewport size is changed, the box's rounded corners change in proportion to the size of the box. We could just implement this using {{cssxref("border-radius")}} with a percentage, but that quickly leads to ugly-looking elliptical corners; this solution gives you nice square corners that scale with the box size. To grab a reference to the observed element so we can update its {{cssxref("border-radius")}} value after each change, we make use of the `target` property of each entry — `entry.target.style.borderRadius`. ```js const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { if (entry.contentBoxSize) { entry.target.style.borderRadius = `${Math.min( 100, entry.contentBoxSize.inlineSize / 10 + entry.contentBoxSize.blockSize / 10, )}px`; } else { entry.target.style.borderRadius = `${Math.min( 100, entry.contentRect.width / 10 + entry.contentRect.height / 10, )}px`; } } }); resizeObserver.observe(document.querySelector("div")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/resizeobserverentry
data/mdn-content/files/en-us/web/api/resizeobserverentry/devicepixelcontentboxsize/index.md
--- title: "ResizeObserverEntry: devicePixelContentBoxSize property" short-title: devicePixelContentBoxSize slug: Web/API/ResizeObserverEntry/devicePixelContentBoxSize page-type: web-api-instance-property browser-compat: api.ResizeObserverEntry.devicePixelContentBoxSize --- {{APIRef("Resize Observer API")}} The **`devicePixelContentBoxSize`** read-only property of the {{domxref("ResizeObserverEntry")}} interface returns an array containing the size in device pixels of the observed element when the callback is run. ## Value An array containing objects with the new size of the observed element in device pixels. The array is necessary to support elements that have multiple fragments, which occur in multi-column scenarios. Each object in the array contains two properties: - `blockSize` - : The size of the content-box, in device pixels, of the block dimension of the observed element. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width. - `inlineSize` - : The size of the content box, in device pixels, of the inline direction of the observed element. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height. > **Note:** For more information about writing modes and block and inline > dimensions, read [Handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions). ## Examples The following example is taken from the article [Pixel-perfect rendering with devicePixelContentBox](https://web.dev/articles/device-pixel-content-box). As the callback function of a {{domxref("ResizeObserver")}} is called after layout but before paint. This provides an opportunity to log the exact size in physical pixels to ensure a one-to-one mapping of canvas pixels to physical pixels. ```js const observer = new ResizeObserver((entries) => { const entry = entries.find((entry) => entry.target === canvas); canvas.width = entry.devicePixelContentBoxSize[0].inlineSize; canvas.height = entry.devicePixelContentBoxSize[0].blockSize; /* … render to canvas … */ }); observer.observe(canvas, { box: "device-pixel-content-box" }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/resizeobserverentry
data/mdn-content/files/en-us/web/api/resizeobserverentry/borderboxsize/index.md
--- title: "ResizeObserverEntry: borderBoxSize property" short-title: borderBoxSize slug: Web/API/ResizeObserverEntry/borderBoxSize page-type: web-api-instance-property browser-compat: api.ResizeObserverEntry.borderBoxSize --- {{APIRef("Resize Observer API")}} The **`borderBoxSize`** read-only property of the {{domxref("ResizeObserverEntry")}} interface returns an array containing the new border box size of the observed element when the callback is run. ## Value An array containing objects with the new border box size of the observed element. The array is necessary to support elements that have multiple fragments, which occur in multi-column scenarios. Each object in the array contains two properties: - `blockSize` - : The length of the observed element's border box in the block dimension. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width. - `inlineSize` - : The length of the observed element's border box in the inline dimension. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height. > **Note:** For more explanation of writing modes and block and inline > dimensions, read [Handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions). ## Examples ```js const resizeObserver = new ResizeObserver((entries) => { const calcBorderRadius = (size1, size2) => `${Math.min(100, size1 / 10 + size2 / 10)}px`; for (const entry of entries) { if (entry.borderBoxSize?.length > 0) { entry.target.style.borderRadius = calcBorderRadius( entry.borderBoxSize[0].inlineSize, entry.borderBoxSize[0].blockSize, ); } else { entry.target.style.borderRadius = calcBorderRadius( entry.contentRect.width, entry.contentRect.height, ); } } }); resizeObserver.observe(document.querySelector("div")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/resizeobserverentry
data/mdn-content/files/en-us/web/api/resizeobserverentry/contentrect/index.md
--- title: "ResizeObserverEntry: contentRect property" short-title: contentRect slug: Web/API/ResizeObserverEntry/contentRect page-type: web-api-instance-property browser-compat: api.ResizeObserverEntry.contentRect --- {{APIRef("Resize Observer API")}} The `contentRect` read-only property of the {{domxref("ResizeObserverEntry")}} interface returns a {{domxref('DOMRectReadOnly')}} object containing the new size of the observed element when the callback is run. Note that this is better supported than {{domxref("ResizeObserverEntry.borderBoxSize")}} or {{domxref("ResizeObserverEntry.contentBoxSize")}}, but it is left over from an earlier implementation of the Resize Observer API, is still included in the spec for web compat reasons, and may be deprecated in future versions. ## Value A {{domxref('DOMRectReadOnly')}} object containing the new size of the element indicated by the {{domxref("ResizeObserverEntry.target", "target")}} property. If the `target` is an HTML {{domxref("Element")}}, the returned `contentRect` is the element's content box. If the `target` is an {{domxref("SVGElement")}}, the returned `contentRect` is the SVG's bounding box. ## Examples The following snippet is taken from the [resize-observer-text.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-text.html) ([see source](https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-text.html)) example. This uses a simple feature detection test to see if the browser supports the newer {{domxref("ResizeObserverEntry.contentBoxSize")}} property — if so, it uses that to get the sizing data it needs. If not, it uses `contentRect`. ```js const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { if (entry.contentBoxSize) { h1Elem.style.fontSize = `${Math.max( 1.5, entry.contentBoxSize.inlineSize / 200, )}rem`; pElem.style.fontSize = `${Math.max( 1, entry.contentBoxSize.inlineSize / 600, )}rem`; } else { h1Elem.style.fontSize = `${Math.max( 1.5, entry.contentRect.width / 200, )}rem`; pElem.style.fontSize = `${Math.max(1, entry.contentRect.width / 600)}rem`; } } }); resizeObserver.observe(divElem); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/resizeobserverentry
data/mdn-content/files/en-us/web/api/resizeobserverentry/contentboxsize/index.md
--- title: "ResizeObserverEntry: contentBoxSize property" short-title: contentBoxSize slug: Web/API/ResizeObserverEntry/contentBoxSize page-type: web-api-instance-property browser-compat: api.ResizeObserverEntry.contentBoxSize --- {{APIRef("Resize Observer API")}} The **`contentBoxSize`** read-only property of the {{domxref("ResizeObserverEntry")}} interface returns an array containing the new content box size of the observed element when the callback is run. ## Value An array containing objects with the new content box size of the observed element. The array is necessary to support elements that have multiple fragments, which occur in multi-column scenarios. Each object in the array contains two properties: - `blockSize` - : The length of the observed element's content box in the block dimension. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width. - `inlineSize` - : The length of the observed element's content box in the inline dimension. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height. > **Note:** For more explanation of writing modes and block and inline > dimensions, read [Handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions). ## Examples The following snippet is taken from the [resize-observer-border-radius.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-border-radius.html) ([see source](https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-border-radius.html)) example. This example includes a green box, sized as a percentage of the viewport size. When the viewport size is changed, the box's rounded corners change in proportion to the size of the box. We could just implement this using {{cssxref("border-radius")}} with a percentage, but that quickly leads to ugly-looking elliptical corners; this solution gives you nice square corners that scale with the box size. ```js const resizeObserver = new ResizeObserver((entries) => { for (let entry of entries) { if (entry.contentBoxSize) { // The standard makes contentBoxSize an array... if (entry.contentBoxSize[0]) { entry.target.style.borderRadius = Math.min( 100, entry.contentBoxSize[0].inlineSize / 10 + entry.contentBoxSize[0].blockSize / 10, ) + "px"; } else { // ...but old versions of Firefox treat it as a single item entry.target.style.borderRadius = Math.min( 100, entry.contentBoxSize.inlineSize / 10 + entry.contentBoxSize.blockSize / 10, ) + "px"; } } else { entry.target.style.borderRadius = Math.min( 100, entry.contentRect.width / 10 + entry.contentRect.height / 10, ) + "px"; } } }); resizeObserver.observe(document.querySelector("div")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/wheelevent/index.md
--- title: WheelEvent slug: Web/API/WheelEvent page-type: web-api-interface browser-compat: api.WheelEvent --- {{APIRef("UI Events")}} The **`WheelEvent`** interface represents events that occur due to the user moving a mouse wheel or similar input device. > **Note:** This is the standard wheel event interface to use. Old versions of browsers implemented the non-standard and non-cross-browser-compatible `MouseWheelEvent` and {{DOMxRef("MouseScrollEvent")}} interfaces. Use this interface and avoid the non-standard ones. > **Note:** Do not confuse the {{domxref("Element/wheel_event", "wheel")}} event with the {{domxref("Element/scroll_event", "scroll")}} event. The default action of a `wheel` event is implementation-defined. Thus, a `wheel` event doesn't necessarily dispatch a `scroll` event. Even when it does, that doesn't mean that the `delta*` values in the `wheel` event necessarily reflect the content's scrolling direction. Therefore, do not rely on `delta*` properties to get the content's scrolling direction. Instead, detect value changes to {{DOMxRef("Element.scrollLeft", "scrollLeft")}} and {{DOMxRef("Element.scrollTop", "scrollTop")}} of the target in the `scroll` event. {{InheritanceDiagram}} ## Constructor - {{DOMxRef("WheelEvent.WheelEvent", "WheelEvent()")}} - : Creates a `WheelEvent` object. ## Instance properties _This interface inherits properties from its ancestors, {{DOMxRef("MouseEvent")}}, {{DOMxRef("UIEvent")}}, and {{DOMxRef("Event")}}._ - {{DOMxRef("WheelEvent.deltaX")}} {{ReadOnlyInline}} - : Returns a `double` representing the horizontal scroll amount. - {{DOMxRef("WheelEvent.deltaY")}} {{ReadOnlyInline}} - : Returns a `double` representing the vertical scroll amount. - {{DOMxRef("WheelEvent.deltaZ")}} {{ReadOnlyInline}} - : Returns a `double` representing the scroll amount for the z-axis. - {{DOMxRef("WheelEvent.deltaMode")}} {{ReadOnlyInline}} - : Returns an `unsigned long` representing the unit of the `delta*` values' scroll amount. Permitted values are: | Constant | Value | Description | | ---------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `WheelEvent.DOM_DELTA_PIXEL` | `0x00` | The `delta*` values are specified in pixels. | | `WheelEvent.DOM_DELTA_LINE` | `0x01` | The `delta*` values are specified in lines. Each mouse click scrolls a line of content, where the method used to calculate line height is browser dependent. | | `WheelEvent.DOM_DELTA_PAGE` | `0x02` | The `delta*` values are specified in pages. Each mouse click scrolls a page of content. | - {{DOMxRef("WheelEvent.wheelDelta")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns an integer (32-bit) representing the distance in pixels. - {{DOMxRef("WheelEvent.wheelDeltaX")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns an integer representing the horizontal scroll amount. - {{DOMxRef("WheelEvent.wheelDeltaY")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns an integer representing the vertical scroll amount. > **Note:** [Element: mousewheel event](/en-US/docs/Web/API/Element/mousewheel_event) has additional documentation about the deprecated properties `wheelDelta`, `wheelDeltaX`, `wheelDeltaY`. ## Instance methods _This interface doesn't define any specific methods, but inherits methods from its ancestors, {{DOMxRef("MouseEvent")}}, {{DOMxRef("UIEvent")}}, and {{DOMxRef("Event")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element/wheel_event", "wheel")}} event - Interfaces replaced by this one: - Gecko's legacy mouse wheel event object: {{DOMxRef("MouseScrollEvent")}}
0
data/mdn-content/files/en-us/web/api/wheelevent
data/mdn-content/files/en-us/web/api/wheelevent/deltay/index.md
--- title: "WheelEvent: deltaY property" short-title: deltaY slug: Web/API/WheelEvent/deltaY page-type: web-api-instance-property browser-compat: api.WheelEvent.deltaY --- {{APIRef("UI Events")}} The **`WheelEvent.deltaY`** read-only property is a `double` representing the vertical scroll amount in the {{domxref("WheelEvent.deltaMode")}} unit. ## Value A number. ## Examples ```js const syntheticEvent = new WheelEvent("syntheticWheel", { deltaY: 4, deltaMode: 0, }); console.log(syntheticEvent.deltaY); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element/wheel_event","wheel")}} - {{domxref("WheelEvent")}}
0
data/mdn-content/files/en-us/web/api/wheelevent
data/mdn-content/files/en-us/web/api/wheelevent/deltamode/index.md
--- title: "WheelEvent: deltaMode property" short-title: deltaMode slug: Web/API/WheelEvent/deltaMode page-type: web-api-instance-property browser-compat: api.WheelEvent.deltaMode --- {{APIRef("UI Events")}} The **`WheelEvent.deltaMode`** read-only property returns an `unsigned long` representing the unit of the delta values scroll amount. Permitted values are: | Constant | Value | Description | | ----------------- | ------ | ----------------------------------------- | | `DOM_DELTA_PIXEL` | `0x00` | The delta values are specified in pixels. | | `DOM_DELTA_LINE` | `0x01` | The delta values are specified in lines. | | `DOM_DELTA_PAGE` | `0x02` | The delta values are specified in pages. | ## Value An `unsigned long`. ## Examples ```js const syntheticEvent = new WheelEvent("syntheticWheel", { deltaX: 4, deltaMode: 0, }); console.log(syntheticEvent.deltaMode); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element/wheel_event","wheel")}} - {{domxref("WheelEvent")}}
0
data/mdn-content/files/en-us/web/api/wheelevent
data/mdn-content/files/en-us/web/api/wheelevent/deltax/index.md
--- title: "WheelEvent: deltaX property" short-title: deltaX slug: Web/API/WheelEvent/deltaX page-type: web-api-instance-property browser-compat: api.WheelEvent.deltaX --- {{APIRef("UI Events")}} The **`WheelEvent.deltaX`** read-only property is a `double` representing the horizontal scroll amount in the {{domxref("WheelEvent.deltaMode")}} unit. ## Value A number. ## Examples ```js const syntheticEvent = new WheelEvent("syntheticWheel", { deltaX: 4, deltaMode: 0, }); console.log(syntheticEvent.deltaX); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element/wheel_event","wheel")}} - {{domxref("WheelEvent")}}
0
data/mdn-content/files/en-us/web/api/wheelevent
data/mdn-content/files/en-us/web/api/wheelevent/wheelevent/index.md
--- title: "WheelEvent: WheelEvent() constructor" short-title: WheelEvent() slug: Web/API/WheelEvent/WheelEvent page-type: web-api-constructor browser-compat: api.WheelEvent.WheelEvent --- {{APIRef("UI Events")}} The **`WheelEvent()`** constructor returns a new {{domxref("WheelEvent")}} object. > **Note:** If you construct a synthetic event using this constructor, that event will not be _trusted_, for security reasons. > Only browser-generated `WheelEvent` objects are trusted and only trusted events trigger default actions. ## Syntax ```js-nolint new WheelEvent(type) new WheelEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers always set it to `wheel`. - `options` {{optional_inline}} - : An object that, _in addition of the properties defined in {{domxref("MouseEvent/MouseEvent", "MouseEvent()")}}_, can have the following properties: - `deltaX` {{optional_inline}} - : A floating number representing the horizontal scroll amount in the `deltaMode` unit. It defaults to `0.0`. - `deltaY` {{optional_inline}} - : A floating number representing the vertical scroll amount in the `deltaMode` unit. It defaults to `0.0`. - `deltaZ` {{optional_inline}} - : A floating number representing the scroll amount for the z-axis scroll amount in the `deltaMode` unit. It defaults to `0.0`. - `deltaMode` {{optional_inline}} - : An integer representing the unit of the delta values scroll amount. It defaults to `0x00`. Permitted values are: | Constant | Value | Description | | ----------------- | ------ | ----------------------------------------- | | `DOM_DELTA_PIXEL` | `0x00` | The delta values are specified in pixels. | | `DOM_DELTA_LINE` | `0x01` | The delta values are specified in lines. | | `DOM_DELTA_PAGE` | `0x02` | The delta values are specified in pages. | ### Return value A new {{domxref("WheelEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("WheelEvent")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api/wheelevent
data/mdn-content/files/en-us/web/api/wheelevent/deltaz/index.md
--- title: "WheelEvent: deltaZ property" short-title: deltaZ slug: Web/API/WheelEvent/deltaZ page-type: web-api-instance-property browser-compat: api.WheelEvent.deltaZ --- {{APIRef("UI Events")}} The **`WheelEvent.deltaZ`** read-only property is a `double` representing the scroll amount along the z-axis, in the {{domxref("WheelEvent.deltaMode")}} unit. ## Value A number. ## Examples ```js const syntheticEvent = new WheelEvent("syntheticWheel", { deltaZ: 4, deltaMode: 0, }); console.log(syntheticEvent.deltaZ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element/wheel_event","wheel")}} - {{domxref("WheelEvent")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/webgl_compressed_texture_s3tc_srgb/index.md
--- title: WEBGL_compressed_texture_s3tc_srgb extension short-title: WEBGL_compressed_texture_s3tc_srgb slug: Web/API/WEBGL_compressed_texture_s3tc_srgb page-type: webgl-extension browser-compat: api.WEBGL_compressed_texture_s3tc_srgb --- {{APIRef("WebGL")}} The **`WEBGL_compressed_texture_s3tc_srgb`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and exposes four [S3TC compressed texture formats](https://en.wikipedia.org/wiki/S3_Texture_Compression) for the sRGB colorspace. Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial). > **Note:** This extension is available to both {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts. ## Constants The compressed texture formats are exposed by four constants and can be used in two functions: {{domxref("WebGLRenderingContext.compressedTexImage2D", "compressedTexImage2D()")}} and {{domxref("WebGLRenderingContext.compressedTexSubImage2D", "compressedTexSubImage2D()")}}. - `ext.COMPRESSED_SRGB_S3TC_DXT1_EXT` - : A DXT1-compressed image in an sRGB image format. - `ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT` - : A DXT1-compressed image in an sRGB image format with a simple on/off alpha value. - `ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT` - : A DXT3-compressed image in an sRGBA image format. - `ext.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT` - : A DXT5-compressed image in an sRGBA image format. ## Examples ```js const ext = gl.getExtension("WEBGL_compressed_texture_s3tc_srgb"); const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D( gl.TEXTURE_2D, 0, ext.COMPRESSED_SRGB_S3TC_DXT1_EXT, 512, 512, 0, textureData, ); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [S3 Texture Compression – OpenGL wiki](https://www.khronos.org/opengl/wiki/S3_Texture_Compression#sRGB_and_S3TC) - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("WebGLRenderingContext.compressedTexImage2D()")}} - {{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}} - {{domxref("WebGLRenderingContext.getParameter()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/pictureinpicturewindow/index.md
--- title: PictureInPictureWindow slug: Web/API/PictureInPictureWindow page-type: web-api-interface browser-compat: api.PictureInPictureWindow --- {{APIRef("Picture-in-Picture API")}} The **`PictureInPictureWindow`** interface represents an object able to programmatically obtain the **`width`** and **`height`** and **`resize event`** of the floating video window. An object with this interface is obtained using the {{domxref("HTMLVideoElement.requestPictureInPicture()")}} promise return value. {{InheritanceDiagram}} ## Instance properties _The `PictureInPictureWindow` interface doesn't inherit any properties._ - {{domxref("PictureInPictureWindow.width")}} {{ReadOnlyInline}} - : Determines the width of the floating video window. - {{domxref("PictureInPictureWindow.height")}} {{ReadOnlyInline}} - : Determines the height of the floating video window. ## Instance methods _The `PictureInPictureWindow` interface doesn't inherit any methods._ ## Events _The `PictureInPictureWindow` interface doesn't inherit any events._ - {{domxref("PictureInPictureWindow.resize_event", "resize")}} - : Sent to a {{DOMxRef("PictureInPictureWindow")}} when the floating video window is resized. ## Examples Given a `<button>` and a `<video>`, clicking the button will make the video enter the picture-in-picture mode; we then attach an event to print the floating video window dimensions to the console. ```js const button = document.querySelector("button"); const video = document.querySelector("video"); function printPipWindowDimensions(evt) { const pipWindow = evt.target; console.log( `The floating window dimensions are: ${pipWindow.width}x${pipWindow.height}px`, ); // will print: // The floating window dimensions are: 640x360px } button.onclick = () => { video.requestPictureInPicture().then((pictureInPictureWindow) => { pictureInPictureWindow.onresize = printPipWindowDimensions; }); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("Picture-in-Picture_API", "Picture-in-Picture API")}}
0
data/mdn-content/files/en-us/web/api/pictureinpicturewindow
data/mdn-content/files/en-us/web/api/pictureinpicturewindow/resize_event/index.md
--- title: "PictureInPictureWindow: resize event" short-title: resize slug: Web/API/PictureInPictureWindow/resize_event page-type: web-api-event browser-compat: api.PictureInPictureWindow.resize_event --- {{APIRef("Picture-in-Picture API")}} The **`resize`** event fires when the floating video window has been resized. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("resize", (event) => {}); onresize = (event) => {}; ``` ## Event type A {{domxref("PictureInPictureEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PictureInPictureEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("PictureInPictureEvent.pictureInPictureWindow")}} - : Returns the {{domxref("PictureInPictureWindow")}} that is resized. ## Examples ### Window size logger ```html <p>Resize the floating video window to fire the <code>resize</code> event.</p> <p>Window height: <span id="height"></span></p> <p>Window width: <span id="width"></span></p> <video id="video" src="" muted autoplay></video> ``` ```js const video = document.querySelector("#video"); const heightOutput = document.querySelector("#height"); const widthOutput = document.querySelector("#width"); function resize(evt) { heightOutput.textContent = evt.target.height; widthOutput.textContent = evt.target.width; } video.requestPictureInPicture().then((pictureInPictureWindow) => { pictureInPictureWindow.onresize = resize; // or pictureInPictureWindow.addEventListener("resize", resize); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/pictureinpicturewindow
data/mdn-content/files/en-us/web/api/pictureinpicturewindow/width/index.md
--- title: "PictureInPictureWindow: width property" short-title: width slug: Web/API/PictureInPictureWindow/width page-type: web-api-instance-property browser-compat: api.PictureInPictureWindow.width --- {{APIRef("Picture-in-Picture API")}} The read-only **`width`** property of the {{domxref("PictureInPictureWindow")}} inbterface returns the width of the floating video window in pixels. ## Syntax ```js-nolint pictureInPictureWindow.width ``` ### Value An integer value indicating the width of the floating video window in pixels if the Picture-in-Picture window is open. Otherwise, it returns `0`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Picture-in-Picture API](/en-US/docs/Web/API/Picture-in-Picture_API) - {{DOMxRef("PictureInPictureWindow.height")}}
0
data/mdn-content/files/en-us/web/api/pictureinpicturewindow
data/mdn-content/files/en-us/web/api/pictureinpicturewindow/height/index.md
--- title: "PictureInPictureWindow: height property" short-title: height slug: Web/API/PictureInPictureWindow/height page-type: web-api-instance-property browser-compat: api.PictureInPictureWindow.height --- {{APIRef("Picture-in-Picture API")}} The read-only **`height`** property of the {{domxref("PictureInPictureWindow")}} interface returns the height of the floating video window in pixels. ## Syntax ```js-nolint pictureInPictureWindow.height ``` ### Value An integer value indicating the height of the floating video window in pixels if the Picture-in-Picture window is open. Otherwise, it returns `0`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Picture-in-Picture API](/en-US/docs/Web/API/Picture-in-Picture_API) - {{DOMxRef("PictureInPictureWindow.width")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/mediarecorder/index.md
--- title: MediaRecorder slug: Web/API/MediaRecorder page-type: web-api-interface browser-compat: api.MediaRecorder --- {{APIRef("MediaStream Recording")}} The **`MediaRecorder`** interface of the [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API) provides functionality to easily record media. It is created using the {{domxref("MediaRecorder.MediaRecorder", "MediaRecorder()")}} constructor. {{InheritanceDiagram}} ## Constructor - {{domxref("MediaRecorder.MediaRecorder", "MediaRecorder()")}} - : Creates a new `MediaRecorder` object, given a {{domxref("MediaStream")}} to record. Options are available to do things like set the container's MIME type (such as `"video/webm"` or `"video/mp4"`) and the bit rates of the audio and video tracks or a single overall bit rate. ## Instance properties - {{domxref("MediaRecorder.mimeType")}} {{ReadOnlyInline}} - : Returns the MIME type that was selected as the recording container for the `MediaRecorder` object when it was created. - {{domxref("MediaRecorder.state")}} {{ReadOnlyInline}} - : Returns the current state of the `MediaRecorder` object (`inactive`, `recording`, or `paused`.) - {{domxref("MediaRecorder.stream")}} {{ReadOnlyInline}} - : Returns the stream that was passed into the constructor when the `MediaRecorder` was created. - {{domxref("MediaRecorder.videoBitsPerSecond")}} {{ReadOnlyInline}} - : Returns the video encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided). - {{domxref("MediaRecorder.audioBitsPerSecond")}} {{ReadOnlyInline}} - : Returns the audio encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided). - {{domxref("MediaRecorder.audioBitrateMode")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the bitrate mode used to encode audio tracks. ## Static methods - {{domxref("MediaRecorder.isTypeSupported_static", "MediaRecorder.isTypeSupported()")}} - : A static method which returns a `true` or `false` value indicating if the given MIME media type is supported by the current user agent. ## Instance methods - {{domxref("MediaRecorder.pause()")}} - : Pauses the recording of media. - {{domxref("MediaRecorder.requestData()")}} - : Requests a {{domxref("Blob")}} containing the saved data received thus far (or since the last time `requestData()` was called. After calling this method, recording continues, but in a new `Blob`. - {{domxref("MediaRecorder.resume()")}} - : Resumes recording of media after having been paused. - {{domxref("MediaRecorder.start()")}} - : Begins recording media; this method can optionally be passed a `timeslice` argument with a value in milliseconds. If this is specified, the media will be captured in separate chunks of that duration, rather than the default behavior of recording the media in a single large chunk. - {{domxref("MediaRecorder.stop()")}} - : Stops recording, at which point a {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event containing the final `Blob` of saved data is fired. No more recording occurs. ## Events Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface. - {{domxref("MediaRecorder/dataavailable_event", "dataavailable")}} - : Fires periodically each time `timeslice` milliseconds of media have been recorded (or when the entire media has been recorded, if `timeslice` wasn't specified). The event, of type {{domxref("BlobEvent")}}, contains the recorded media in its {{domxref("BlobEvent.data", "data")}} property. - {{domxref("MediaRecorder/error_event", "error")}} - : Fired when there are fatal errors that stop recording. The received event is based on the {{domxref("MediaRecorderErrorEvent")}} interface, whose {{domxref("MediaRecorderErrorEvent.error", "error")}} property contains a {{domxref("DOMException")}} that describes the actual error that occurred. - {{domxref("MediaRecorder/pause_event", "pause")}} - : Fired when media recording is paused. - {{domxref("MediaRecorder/resume_event", "resume")}} - : Fired when media recording resumes after being paused. - {{domxref("MediaRecorder/start_event", "start")}} - : Fired when media recording starts. - {{domxref("MediaRecorder/stop_event", "stop")}} - : Fired when media recording ends, either when the {{domxref("MediaStream")}} ends, or after the {{domxref("MediaRecorder.stop()")}} method is called. ## Example ```js if (navigator.mediaDevices) { console.log("getUserMedia supported."); const constraints = { audio: true }; let chunks = []; navigator.mediaDevices .getUserMedia(constraints) .then((stream) => { const mediaRecorder = new MediaRecorder(stream); record.onclick = () => { mediaRecorder.start(); console.log(mediaRecorder.state); console.log("recorder started"); record.style.background = "red"; record.style.color = "black"; }; stop.onclick = () => { mediaRecorder.stop(); console.log(mediaRecorder.state); console.log("recorder stopped"); record.style.background = ""; record.style.color = ""; }; mediaRecorder.onstop = (e) => { console.log("data available after MediaRecorder.stop() called."); const clipName = prompt("Enter a name for your sound clip"); const clipContainer = document.createElement("article"); const clipLabel = document.createElement("p"); const audio = document.createElement("audio"); const deleteButton = document.createElement("button"); const mainContainer = document.querySelector("body"); clipContainer.classList.add("clip"); audio.setAttribute("controls", ""); deleteButton.textContent = "Delete"; clipLabel.textContent = clipName; clipContainer.appendChild(audio); clipContainer.appendChild(clipLabel); clipContainer.appendChild(deleteButton); mainContainer.appendChild(clipContainer); audio.controls = true; const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" }); chunks = []; const audioURL = URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); deleteButton.onclick = (e) => { const evtTgt = e.target; evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode); }; }; mediaRecorder.ondataavailable = (e) => { chunks.push(e.data); }; }) .catch((err) => { console.error(`The following error occurred: ${err}`); }); } ``` > **Note:** This code sample is inspired by the Web Dictaphone demo. Some lines have been omitted for brevity; [refer to the source](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone) for the complete code. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [Recording a media element](/en-US/docs/Web/API/MediaStream_Recording_API/Recording_a_media_element) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("MediaDevices.getUserMedia()")}} - [OpenLang](https://github.com/chrisjohndigital/OpenLang): HTML video language lab web application using MediaDevices and the MediaStream Recording API for video recording ([source on GitHub](https://github.com/chrisjohndigital/OpenLang))
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/pause_event/index.md
--- title: "MediaRecorder: pause event" short-title: pause slug: Web/API/MediaRecorder/pause_event page-type: web-api-event browser-compat: api.MediaRecorder.pause_event --- {{APIRef("MediaStream Recording")}} The **`pause`** event of the {{domxref("MediaRecorder")}} interface is fired when {{domxref("MediaRecorder.pause()")}} is called. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("pause", (event) => {}); onpause = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example ```js pause.onclick = () => { if (mediaRecorder.state === "recording") { mediaRecorder.pause(); // recording paused } else if (mediaRecorder.state === "paused") { mediaRecorder.resume(); // resume recording } }; mediaRecorder.onpause = () => { // do something in response to // recording being paused }; mediaRecorder.onresume = () => { // do something in response to // recording being resumed }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/resume/index.md
--- title: "MediaRecorder: resume() method" short-title: resume() slug: Web/API/MediaRecorder/resume page-type: web-api-instance-method browser-compat: api.MediaRecorder.resume --- {{APIRef("MediaStream Recording")}} The **`resume()`** method of the {{domxref("MediaRecorder")}} interface is used to resume media recording when it has been previously paused. If {{domxref("MediaRecorder.state")}} is already "recording", calling `resume()` has no effect. When the `resume()` method is invoked, the browser queues a task that runs the following steps: 1. If {{domxref("MediaRecorder.state")}} is "inactive", raise a DOM `InvalidStateError` exception and terminate these steps. If {{domxref("MediaRecorder.state")}} is not "inactive", continue to the next step. 2. Set {{domxref("MediaRecorder.state")}} to "recording". 3. Continue gathering data into the current {{domxref("Blob")}}. 4. Raise a `resume` event. ## Syntax ```js-nolint resume() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the `MediaRecorder` is currently `"inactive"`. ## Examples ```js pause.onclick = () => { if (MediaRecorder.state === "recording") { mediaRecorder.pause(); // recording paused } else if (MediaRecorder.state === "paused") { mediaRecorder.resume(); // resume recording } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/stop_event/index.md
--- title: "MediaRecorder: stop event" short-title: stop slug: Web/API/MediaRecorder/stop_event page-type: web-api-event browser-compat: api.MediaRecorder.stop_event --- {{APIRef("MediaStream Recording")}} The **`stop`** event of the {{domxref("MediaRecorder")}} interface is fired when {{domxref("MediaRecorder.stop()")}} is called, or when the media stream being captured ends. In each case, the `stop` event is preceded by a `dataavailable` event, making the {{domxref("Blob")}} captured up to that point available for you to use in your application. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("stop", (event) => {}); onstop = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example ```js mediaRecorder.onstop = (e) => { console.log("data available after MediaRecorder.stop() called."); const audio = document.createElement("audio"); audio.controls = true; const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" }); const audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); }; mediaRecorder.ondataavailable = (e) => { chunks.push(e.data); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/stop/index.md
--- title: "MediaRecorder: stop() method" short-title: stop() slug: Web/API/MediaRecorder/stop page-type: web-api-instance-method browser-compat: api.MediaRecorder.stop --- {{APIRef("MediaStream Recording")}} The **`stop()`** method of the {{domxref("MediaRecorder")}} interface is used to stop media capture. When the `stop()` method is invoked, the UA queues a task that runs the following steps: 1. If {{domxref("MediaRecorder.state")}} is "inactive", raise a DOM `InvalidState` error and terminate these steps. If the {{domxref("MediaRecorder.state")}} is not "inactive", continue on to the next step. 2. Set the {{domxref("MediaRecorder.state")}} to "inactive" and stop capturing media. 3. Raise a `dataavailable` event containing the Blob of data that has been gathered. 4. Raise a `stop` event. ## Syntax ```js-nolint stop() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the `MediaRecorder` is currently `"inactive"`; you cannot stop the recording if the `MediaRecorder` is not active. ## Examples ```js stop.onclick = () => { mediaRecorder.stop(); console.log("recorder stopped, data available"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/videobitspersecond/index.md
--- title: "MediaRecorder: videoBitsPerSecond property" short-title: videoBitsPerSecond slug: Web/API/MediaRecorder/videoBitsPerSecond page-type: web-api-instance-property browser-compat: api.MediaRecorder.videoBitsPerSecond --- {{APIRef("MediaStream Recording")}} The **`videoBitsPerSecond`** read-only property of the {{domxref("MediaRecorder")}} interface returns the video encoding bit rate in use. This may differ from the bit rate specified in the constructor, if it was provided. ## Value A {{jsxref("Number")}} (unsigned long). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/start/index.md
--- title: "MediaRecorder: start() method" short-title: start() slug: Web/API/MediaRecorder/start page-type: web-api-instance-method browser-compat: api.MediaRecorder.start --- {{APIRef("MediaStream Recording")}} The **`start()`** method of the {{domxref("MediaRecorder")}} interface begins recording media into one or more {{domxref("Blob")}} objects. You can record the entire duration of the media into a single `Blob` (or until you call {{domxref("MediaRecorder.requestData", "requestData()")}}), or you can specify the number of milliseconds to record at a time. Then, each time that amount of media has been recorded, an event will be delivered to let you act upon the recorded media, while a new `Blob` is created to record the next slice of the media. Assuming the `MediaRecorder`'s {{domxref("MediaRecorder.state", "state")}} is `inactive`, `start()` sets the `state` to `recording`, then begins capturing media from the input stream. A `Blob` is created and the data is collected in it until the time slice period elapses or the source media ends. Each time a `Blob` is filled up to that point (the timeslice duration or the end-of-media, if no slice duration was provided), a {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event is sent to the `MediaRecorder` with the recorded data. If the source is still playing, a new `Blob` is created and recording continues into that, and so forth. When the source stream ends, `state` is set to `inactive` and data gathering stops. A final {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event is sent to the `MediaRecorder`, followed by a {{domxref("MediaRecorder/stop_event", "stop")}} event. > **Note:** If the browser is unable to start recording or continue > recording, it will raise an {{domxref("MediaRecorder.error_event", "error")}} event, followed by a > {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event containing the `Blob` it > has gathered, followed by the {{domxref("MediaRecorder/stop_event", "stop")}} event. ## Syntax ```js-nolint start() start(timeslice) ``` ### Parameters - `timeslice` {{optional_inline}} - : The number of milliseconds to record into each {{domxref("Blob")}}. If this parameter isn't included, the entire media duration is recorded into a single `Blob` unless the {{domxref("MediaRecorder.requestData", "requestData()")}} method is called to obtain the `Blob` and trigger the creation of a new `Blob` into which the media continues to be recorded. ### Return value None ({{jsxref("undefined")}}). ### Exceptions Errors that can be detected immediately are thrown as DOM exceptions. All other errors are reported through {{domxref("MediaRecorder.error_event", "error")}} events sent to the `MediaRecorder` object. You can implement the {{domxref("MediaRecorder.error_event", "onerror")}} event handler to respond to these errors. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the `MediaRecorder` is not in the `inactive` state; you cannot start recording media if it is already being recorded. See the {{domxref("MediaRecorder.state", "state")}} property. - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if: - The media stream you are attempting to record is inactive. - One or more of the stream's tracks is in a format that cannot be recorded using the current configuration - The `videoKeyFrameIntervalDuration` and `videoKeyFrameIntervalCount` parameter are both specificed when creating the `MediaRecorder`. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the {{domxref("MediaStream")}} is configured to disallow recording. This may be the case, for example, with sources obtained using {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} when the user denies permission to use an input device. This exception may also be delivered as an {{domxref("MediaRecorder.error_event", "error")}} event if the security options for the source media change after recording begins. ## Examples ```js record.onclick = () => { mediaRecorder.start(); console.log("recorder started"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/mimetype/index.md
--- title: "MediaRecorder: mimeType property" short-title: mimeType slug: Web/API/MediaRecorder/mimeType page-type: web-api-instance-property browser-compat: api.MediaRecorder.mimeType --- {{APIRef("MediaStream Recording")}} The **`mimeType`** read-only property of the {{domxref("MediaRecorder")}} interface returns the {{Glossary("MIME")}} media type that was specified when creating the {{domxref("MediaRecorder")}} object, or, if none was specified, which was chosen by the browser. This is the file format of the file that would result from writing all of the recorded data to disk. Keep in mind that not all codecs are supported by a given container; if you write media using a codec that is not supported by a given media container, the resulting file may not work reliably if at all when you try to play it back. See our [media type and format guide](/en-US/docs/Web/Media/Formats) for information about container and codec support across browsers. > **Note:** The term "MIME type" is officially considered to be historical; these strings are now officially known as **media types**. > MDN Web Docs content uses the terms interchangeably. ## Value The MIME media type which describes the format of the recorded media, as a string. This string _may_ include the [`codecs` parameter,](/en-US/docs/Web/Media/Formats/codecs_parameter) giving details about the codecs and the codec configurations used by the media recorder. The media type strings are standardized by the Internet Assigned Numbers Authority (IANA). For their official list of defined media type strings, see the article [Media Types](https://www.iana.org/assignments/media-types/media-types.xhtml) on the IANA site. See also [media types](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) to learn more about media types and how they're used in web content and by web browsers. ## Examples ```js if (navigator.mediaDevices) { console.log("getUserMedia supported."); const constraints = { audio: true, video: true }; const chunks = []; navigator.mediaDevices .getUserMedia(constraints) .then((stream) => { const options = { audioBitsPerSecond: 128000, videoBitsPerSecond: 2500000, mimeType: "video/mp4", }; const mediaRecorder = new MediaRecorder(stream, options); m = mediaRecorder; m.mimeType; // would return 'video/mp4' // … }) .catch((error) => { console.error(error.message); }); } ``` Changing line 14 to the following causes `MediaRecorder` to try to use AVC Constrained Baseline Profile Level 4 for video and AAC-LC (Low Complexity) for audio, which is good for mobile and other possible resource-constrained situations. ```js mimeType: 'video/mp4; codecs="avc1.424028, mp4a.40.2"'; ``` Assuming this configuration is acceptable to the user agent, the value returned later by `m.mimeType` would then be `video/mp4; codecs="avc1.424028, mp4a.40.2"`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Codecs in common media types](/en-US/docs/Web/Media/Formats/codecs_parameter) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("MediaDevices.getUserMedia()")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/requestdata/index.md
--- title: "MediaRecorder: requestData() method" short-title: requestData() slug: Web/API/MediaRecorder/requestData page-type: web-api-instance-method browser-compat: api.MediaRecorder.requestData --- {{APIRef("MediaStream Recording")}} The **`requestData()`** method of the {{domxref("MediaRecorder")}} interface is used to raise a {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event containing a {{domxref("Blob")}} object of the captured media as it was when the method was called. This can then be grabbed and manipulated as you wish. When the `requestData()` method is invoked, the browser queues a task that runs the following steps: 1. If {{domxref("MediaRecorder.state")}} is "inactive", raise a DOM `InvalidState` error and terminate these steps. If {{domxref("MediaRecorder.state")}} is not "inactive", continue to the next step. 2. Raise a {{domxref("MediaRecorder.dataavailable_event", "dataavailable")}} event containing a {{domxref("Blob")}} of the currently captured data (the Blob is available under the event's `data` attribute.) 3. Create a new Blob and place subsequently captured data into it. ## Syntax ```js-nolint requestData() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the `MediaRecorder` is currently `"inactive"`; you cannot capture the recording if the `MediaRecorder` is not active. ## Examples ```js captureMedia.onclick = () => { mediaRecorder.requestData(); // makes snapshot available of data so far // ondataavailable fires, then capturing continues // in new Blob }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia()")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/mediarecorder/index.md
--- title: "MediaRecorder: MediaRecorder() constructor" short-title: MediaRecorder() slug: Web/API/MediaRecorder/MediaRecorder page-type: web-api-constructor browser-compat: api.MediaRecorder.MediaRecorder --- {{APIRef("MediaStream Recording")}} The **`MediaRecorder()`** constructor creates a new {{domxref("MediaRecorder")}} object that will record a specified {{domxref("MediaStream")}}. The object can optionally be configured to record using a specific media container (file type), and, further, can specify the exact codec and codec configuration(s) to use by specifying [the `codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter). ## Syntax ```js-nolint new MediaRecorder(stream) new MediaRecorder(stream, options) ``` ### Parameters - `stream` - : The {{domxref("MediaStream")}} that will be recorded. This source media can come from a stream created using {{domxref("MediaDevices.getUserMedia", "navigator.mediaDevices.getUserMedia()")}} or from an {{HTMLElement("audio")}}, {{HTMLElement("video")}} or {{HTMLElement("canvas")}} element. - `options` {{optional_inline}} - : A dictionary object that can contain the following properties: - `mimeType` {{optional_inline}} - : A MIME type specifying the format for the resulting media; you may specify the container format (the browser will select its preferred codecs for audio and/or video), or you may [use the `codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter) and/or the `profiles` parameter to provide detailed information about which codecs to use and how to configure them. Applications can check in advance if a `mimeType` is supported by the {{Glossary("user agent")}} by calling {{domxref("MediaRecorder.isTypeSupported_static", "MediaRecorder.isTypeSupported()")}}. Defaults to an empty string. - `audioBitsPerSecond` {{optional_inline}} - : The chosen bitrate for the audio component of the media. - `videoBitsPerSecond` {{optional_inline}} - : The chosen bitrate for the video component of the media. - `bitsPerSecond` {{optional_inline}} - : The chosen bitrate for the audio and video components of the media. This can be specified instead of the above two properties. If this is specified along with one or the other of the above properties, this will be used for the one that isn't specified. - `audioBitrateMode` {{optional_inline}} - : The bitrate mode that should be used to encode the audio. Can be `constant`, which indicates that the recorder should encode at a constant bitrate, or `variable`, which indicates that the recorder should encode using a variable bitrate, thus allowing more space to be used for complex signals and less space for less-complex signals. Defaults to `variable`. - `videoKeyFrameIntervalDuration` {{optional_inline}} - : The nominal interval in time between key frames in the encoded video stream. The {{glossary("user agent")}} controls key-frame generation based on this option and the `videoKeyFrameIntervalCount` option. - `videoKeyFrameIntervalCount` {{optional_inline}} - : The interval in number of frames between key frames in the encoded video stream. The {{glossary("user agent")}} controls key-frame generation considering this option as well as `videoKeyFrameIntervalDuration` option. > **Note:** If bits per second values are not specified for video and/or audio, the default > adopted for video is 2.5Mbps, while the audio default is adaptive, depending upon > the sample rate and the number of channels. > **Note:** Video resolution, frame rate and similar settings are specified as constraints > when calling {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}, > not here in the MediaStream Recording API. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the specified MIME type is not supported by the user agent. ## Examples This example shows how to create a media recorder for a specified stream, whose audio bit rate is set to 128 Kbit/sec and whose video bit rate is set to 2.5 Mbit/sec. The recorded media data will be stored in an MP4 wrapper (so if you gather the chunks of media data and save them to disk, they will be in an MP4 file). ```js if (navigator.mediaDevices.getUserMedia) { const constraints = { audio: true, video: true }; const chunks = []; const onSuccess = (stream) => { const options = { audioBitsPerSecond: 128000, videoBitsPerSecond: 2500000, mimeType: "video/mp4", }; const mediaRecorder = new MediaRecorder(stream, options); m = mediaRecorder; // … }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("MediaDevices.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/pause/index.md
--- title: "MediaRecorder: pause() method" short-title: pause() slug: Web/API/MediaRecorder/pause page-type: web-api-instance-method browser-compat: api.MediaRecorder.pause --- {{APIRef("MediaStream Recording")}} The **`pause()`** method of the {{domxref("MediaRecorder")}} interface is used to pause recording of media streams. When a `MediaRecorder` object's `pause()`method is called, the browser queues a task that runs the below steps: 1. If {{domxref("MediaRecorder.state")}} is "inactive", raise a DOM `InvalidState` error and terminate these steps. If not, continue to the next step. 2. Set {{domxref("MediaRecorder.state")}} to "paused". 3. Stop gathering data into the current {{domxref("Blob")}}, but keep it available so that recording can be resumed later on. 4. Raise a {{domxref("MediaRecorder/pause_event", "pause")}} event. ## Syntax ```js-nolint pause() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the `MediaRecorder` is currently `"inactive"`; you cannot pause the recording if the `MediaRecorder` is not active. If you call `pause()` while already paused, the method silently does nothing. ## Examples ```js pause.onclick = () => { mediaRecorder.pause(); console.log("recording paused"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/resume_event/index.md
--- title: "MediaRecorder: resume event" short-title: resume slug: Web/API/MediaRecorder/resume_event page-type: web-api-event browser-compat: api.MediaRecorder.resume_event --- {{APIRef("MediaStream Recording")}} The **`resume`** event of the {{domxref("MediaRecorder")}} interface is fired when {{domxref("MediaRecorder.resume()")}} is called. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("resume", (event) => {}); onresume = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example ```js pause.onclick = () => { if (MediaRecorder.state === "recording") { mediaRecorder.pause(); // recording paused } else if (MediaRecorder.state === "paused") { mediaRecorder.resume(); // resume recording } }; mediaRecorder.onpause = () => { // do something in response to // recording being paused }; mediaRecorder.onresume = () => { // do something in response to // recording being resumed }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/start_event/index.md
--- title: "MediaRecorder: start event" short-title: start slug: Web/API/MediaRecorder/start_event page-type: web-api-event browser-compat: api.MediaRecorder.start_event --- {{APIRef("MediaStream Recording")}} The **`start`** event of the {{domxref("MediaRecorder")}} interface is fired when {{domxref("MediaRecorder.start()")}} is called. At this point, the data starts being gathered into a {{domxref("Blob")}}. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("start", (event) => {}); onstart = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example ```js record.onclick = () => { mediaRecorder.start(); console.log("recorder started"); }; mediaRecorder.onstart = () => { // do something in response to // recording being started }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/stream/index.md
--- title: "MediaRecorder: stream property" short-title: stream slug: Web/API/MediaRecorder/stream page-type: web-api-instance-property browser-compat: api.MediaRecorder.stream --- {{APIRef("MediaStream Recording")}} The **`stream`** read-only property of the {{domxref("MediaRecorder")}} interface returns the stream that was passed into the {{domxref("MediaRecorder.MediaRecorder", "MediaRecorder()")}} constructor when the `MediaRecorder` was created. ## Value The {{domxref("MediaStream")}} passed into the `MediaRecorder()` constructor when the `MediaRecorder` was originally created. ## Examples ```js if (navigator.getUserMedia) { console.log("getUserMedia supported."); navigator.getUserMedia( // constraints - only audio needed for this app { audio: true, }, // Success callback (stream) => { const mediaRecorder = new MediaRecorder(stream); const myStream = mediaRecorder.stream; console.log(myStream); }, ); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://github.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).) - [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://github.com/samdutton). - {{domxref("Navigator.getUserMedia")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/istypesupported_static/index.md
--- title: "MediaRecorder: isTypeSupported() static method" short-title: isTypeSupported() slug: Web/API/MediaRecorder/isTypeSupported_static page-type: web-api-static-method browser-compat: api.MediaRecorder.isTypeSupported_static --- {{APIRef("MediaStream Recording")}} The **`isTypeSupported()`** static method of the {{domxref("MediaRecorder")}} interface returns a {{jsxref("Boolean")}} which is `true` if the MIME media type specified is one the user agent should be able to successfully record. ## Syntax ```js-nolint MediaRecorder.isTypeSupported(mimeType) ``` ### Parameters - `mimeType` - : The MIME media type to check. ### Return value A {{jsxref("Boolean")}}, `true` if the {{domxref("MediaRecorder")}} implementation is capable of recording {{domxref("Blob")}} objects for the specified MIME type. Recording may still fail if there are insufficient resources to support the recording and encoding process. If the value is `false`, the user agent is incapable of recording the specified format. ## Examples ```js const types = [ "video/webm", "audio/webm", "video/webm;codecs=vp8", "video/webm;codecs=daala", "video/webm;codecs=h264", "audio/webm;codecs=opus", "video/mpeg", ]; for (const type of types) { console.log( `Is ${type} supported? ${ MediaRecorder.isTypeSupported(type) ? "Maybe!" : "Nope :(" }`, ); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API) - [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API) - [Guide to media types and formats on the web](/en-US/docs/Web/Media/Formats) - [Codecs in common media types](/en-US/docs/Web/Media/Formats/codecs_parameter) - {{domxref("MediaStreamTrack")}} - {{domxref("MediaStream")}} - {{domxref("MediaCapabilities")}}
0
data/mdn-content/files/en-us/web/api/mediarecorder
data/mdn-content/files/en-us/web/api/mediarecorder/audiobitratemode/index.md
--- title: "MediaRecorder: audioBitrateMode property" short-title: audioBitrateMode slug: Web/API/MediaRecorder/audioBitrateMode page-type: web-api-instance-property status: - experimental browser-compat: api.MediaRecorder.audioBitrateMode --- {{APIRef("MediaStream Recording")}}{{SeeCompatTable}} The **`audioBitrateMode`** read-only property of the {{domxref("MediaRecorder")}} interface returns the bitrate mode used to encode audio tracks. ## Value One of the following: - `constant` - : The {{domxref("MediaRecorder")}} encodes at this constant bitrate. - `variable` - : The {{domxref("MediaRecorder")}} encodes using this variable bitrate, allowing more space to be used for complex signals and less space for less complex signals. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0