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/eventtarget
data/mdn-content/files/en-us/web/api/eventtarget/eventtarget/index.md
--- title: "EventTarget: EventTarget() constructor" short-title: EventTarget() slug: Web/API/EventTarget/EventTarget page-type: web-api-constructor browser-compat: api.EventTarget.EventTarget --- {{APIRef("DOM")}} The **`EventTarget()`** constructor creates a new {{domxref("EventTarget")}} object instance. > **Note:** It is fairly rare to explicitly call this constructor. Most of the time, this constructor is used inside the constructor of an object extending the {{domxref("EventTarget")}} interface, using the [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super) keyword. ## Syntax ```js-nolint new EventTarget() ``` ### Parameters None. ### Return value A new instance of the {{domxref("EventTarget")}} object. ## Examples ### Implementing a counter This example implements a `Counter` class, with `increment()` and `decrement()` methods. It fires a custom `"valuechange"` event when either of these methods is called. #### HTML ```html <button id="dec" aria-label="Decrement">-</button> <span id="currentValue">0</span> <button id="inc" aria-label="Increment">+</button> ``` #### JavaScript ```js class Counter extends EventTarget { constructor(initialValue = 0) { super(); this.value = initialValue; } #emitChangeEvent() { this.dispatchEvent(new CustomEvent("valuechange", { detail: this.value })); } increment() { this.value++; this.#emitChangeEvent(); } decrement() { this.value--; this.#emitChangeEvent(); } } const initialValue = 0; const counter = new Counter(initialValue); document.querySelector("#currentValue").innerText = initialValue; counter.addEventListener("valuechange", (event) => { document.querySelector("#currentValue").innerText = event.detail; }); document.querySelector("#inc").addEventListener("click", () => { counter.increment(); }); document.querySelector("#dec").addEventListener("click", () => { counter.decrement(); }); ``` #### Result {{EmbedLiveSample("Implementing a counter")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventTarget")}}
0
data/mdn-content/files/en-us/web/api/eventtarget
data/mdn-content/files/en-us/web/api/eventtarget/addeventlistener/index.md
--- title: "EventTarget: addEventListener() method" short-title: addEventListener() slug: Web/API/EventTarget/addEventListener page-type: web-api-instance-method browser-compat: api.EventTarget.addEventListener --- {{APIRef("DOM")}} The **`addEventListener()`** method of the {{domxref("EventTarget")}} interface sets up a function that will be called whenever the specified event is delivered to the target. Common targets are {{domxref("Element")}}, or its children, {{domxref("Document")}}, and {{domxref("Window")}}, but the target may be any object that supports events (such as {{domxref("IDBRequest")}}). > **Note:** The `addEventListener()` method is the _recommended_ way to register an event listener. The benefits are as follows: > > - It allows adding more than one handler for an event. This is particularly > useful for libraries, JavaScript modules, or any other kind of > code that needs to work well with other libraries or extensions. > - In contrast to using an `onXYZ` property, it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling). > - It works on any event target, not just HTML or SVG elements. The method `addEventListener()` works by adding a function, or an object that implements a `handleEvent()` function, to the list of event listeners for the specified event type on the {{domxref("EventTarget")}} on which it's called. If the function or object is already in the list of event listeners for this target, the function or object is not added a second time. > **Note:** If a particular anonymous function is in the list of event listeners registered for a certain target, and then later in the code, an identical anonymous function is given in an `addEventListener` call, the second function will _also_ be added to the list of event listeners for that target. > > Indeed, anonymous functions are not identical even if defined using > the _same_ unchanging source-code called repeatedly, **even if in a loop**. > > Repeatedly defining the same unnamed function in such cases can be > problematic. (See [Memory issues](#memory_issues), below.) If an event listener is added to an {{domxref("EventTarget")}} from inside another listener — that is, during the processing of the event — that event will not trigger the new listener. However, the new listener may be triggered during a later stage of event flow, such as during the bubbling phase. ## Syntax ```js-nolint addEventListener(type, listener) addEventListener(type, listener, options) addEventListener(type, listener, useCapture) ``` ### Parameters - `type` - : A case-sensitive string representing the [event type](/en-US/docs/Web/Events) to listen for. - `listener` - : The object that receives a notification (an object that implements the {{domxref("Event")}} interface) when an event of the specified type occurs. This must be `null`, an object with a `handleEvent()` method, or a JavaScript [function](/en-US/docs/Web/JavaScript/Guide/Functions). See [The event listener callback](#the_event_listener_callback) for details on the callback itself. - `options` {{optional_inline}} - : An object that specifies characteristics about the event listener. The available options are: - `capture` {{optional_inline}} - : A boolean value indicating that events of this type will be dispatched to the registered `listener` before being dispatched to any `EventTarget` beneath it in the DOM tree. If not specified, defaults to `false`. - `once` {{optional_inline}} - : A boolean value indicating that the `listener` should be invoked at most once after being added. If `true`, the `listener` would be automatically removed when invoked. If not specified, defaults to `false`. - `passive` {{optional_inline}} - : A boolean value that, if `true`, indicates that the function specified by `listener` will never call {{domxref("Event.preventDefault", "preventDefault()")}}. If a passive listener does call `preventDefault()`, the user agent will do nothing other than generate a console warning. If this option is not specified it defaults to `false` – except that in browsers other than Safari, it defaults to `true` for {{domxref("Element/wheel_event", "wheel")}}, {{domxref("Element/mousewheel_event", "mousewheel")}}, {{domxref("Element/touchstart_event", "touchstart")}} and {{domxref("Element/touchmove_event", "touchmove")}} events. See [Using passive listeners](#using_passive_listeners) to learn more. - `signal` {{optional_inline}} - : An {{domxref("AbortSignal")}}. The listener will be removed when the given `AbortSignal` object's {{domxref("AbortController/abort()", "abort()")}} method is called. If not specified, no `AbortSignal` is associated with the listener. - `useCapture` {{optional_inline}} - : A boolean value indicating whether events of this type will be dispatched to the registered `listener` _before_ being dispatched to any `EventTarget` beneath it in the DOM tree. Events that are bubbling upward through the tree will not trigger a listener designated to use capture. Event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event. See [DOM Level 3 Events](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow) and [JavaScript Event order](https://www.quirksmode.org/js/events_order.html#link4) for a detailed explanation. If not specified, `useCapture` defaults to `false`. > **Note:** For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases. > Event listeners in the _capturing_ phase are called before event listeners in any non-capturing phases. - `wantsUntrusted` {{optional_inline}} {{non-standard_inline}} - : A Firefox (Gecko)-specific parameter. If `true`, the listener receives synthetic events dispatched by web content (the default is `false` for browser {{glossary("chrome")}} and `true` for regular web pages). This parameter is useful for code found in add-ons, as well as the browser itself. ### Return value None ({{jsxref("undefined")}}). ## Usage notes ### The event listener callback The event listener can be specified as either a callback function or an object whose `handleEvent()` method serves as the callback function. The callback function itself has the same parameters and return value as the `handleEvent()` method; that is, the callback accepts a single parameter: an object based on {{domxref("Event")}} describing the event that has occurred, and it returns nothing. For example, an event handler callback that can be used to handle both {{domxref("Element/fullscreenchange_event", "fullscreenchange")}} and {{domxref("Element/fullscreenerror_event", "fullscreenerror")}} might look like this: ```js function handleEvent(event) { if (event.type === "fullscreenchange") { /* handle a full screen toggle */ } else { /* handle a full screen toggle error */ } } ``` ### Safely detecting option support In older versions of the DOM specification, the third parameter of `addEventListener()` was a Boolean value indicating whether or not to use capture. Over time, it became clear that more options were needed. Rather than adding more parameters to the function (complicating things enormously when dealing with optional values), the third parameter was changed to an object that can contain various properties defining the values of options to configure the process of removing the event listener. Because older browsers (as well as some not-too-old browsers) still assume the third parameter is a Boolean, you need to build your code to handle this scenario intelligently. You can do this by using feature detection for each of the options you're interested in. For example, if you want to check for the `passive` option: ```js let passiveSupported = false; try { const options = { get passive() { // This function will be called when the browser // attempts to access the passive property. passiveSupported = true; return false; }, }; window.addEventListener("test", null, options); window.removeEventListener("test", null, options); } catch (err) { passiveSupported = false; } ``` This creates an `options` object with a getter function for the `passive` property; the getter sets a flag, `passiveSupported`, to `true` if it gets called. That means that if the browser checks the value of the `passive` property on the `options` object, `passiveSupported` will be set to `true`; otherwise, it will remain `false`. We then call `addEventListener()` to set up a fake event handler, specifying those options, so that the options will be checked if the browser recognizes an object as the third parameter. Then, we call [`removeEventListener()`](/en-US/docs/Web/API/EventTarget/removeEventListener) to clean up after ourselves. (Note that `handleEvent()` is ignored on event listeners that aren't called.) You can check whether any option is supported this way. Just add a getter for that option using code similar to what is shown above. Then, when you want to create an actual event listener that uses the options in question, you can do something like this: ```js someElement.addEventListener( "mouseup", handleMouseUp, passiveSupported ? { passive: true } : false, ); ``` Here we're adding a listener for the {{domxref("Element/mouseup_event", "mouseup")}} event on the element `someElement`. For the third parameter, if `passiveSupported` is `true`, we're specifying an `options` object with `passive` set to `true`; otherwise, we know that we need to pass a Boolean, and we pass `false` as the value of the `useCapture` parameter. You can learn more in the [Implementing feature detection](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection) documentation and the explainer about [`EventListenerOptions`](https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection) from the [Web Incubator Community Group](https://wicg.github.io/admin/charter.html). ### The value of "this" within the handler It is often desirable to reference the element on which the event handler was fired, such as when using a generic handler for a set of similar elements. When attaching a handler function to an element using `addEventListener()`, the value of {{jsxref("Operators/this","this")}} inside the handler will be a reference to the element. It will be the same as the value of the `currentTarget` property of the event argument that is passed to the handler. ```js my_element.addEventListener("click", function (e) { console.log(this.className); // logs the className of my_element console.log(e.currentTarget === this); // logs `true` }); ``` As a reminder, [arrow functions do not have their own `this` context](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#cannot_be_used_as_methods). ```js my_element.addEventListener("click", (e) => { console.log(this.className); // WARNING: `this` is not `my_element` console.log(e.currentTarget === this); // logs `false` }); ``` If an event handler (for example, {{domxref("Element.click_event", "onclick")}}) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function that binds the value of `this` in a manner consistent with the `addEventListener()`; an occurrence of `this` within the code represents a reference to the element. ```html <table id="my_table" onclick="console.log(this.id);"> <!-- `this` refers to the table; logs 'my_table' --> … </table> ``` Note that the value of `this` inside a function, _called by_ the code in the attribute value, behaves as per [standard rules](/en-US/docs/Web/JavaScript/Reference/Operators/this). This is shown in the following example: ```html <script> function logID() { console.log(this.id); } </script> <table id="my_table" onclick="logID();"> <!-- when called, `this` will refer to the global object --> … </table> ``` The value of `this` within `logID()` is a reference to the global object {{domxref("Window")}} (or `undefined` in the case of [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode). #### Specifying "this" using bind() The {{jsxref("Function.prototype.bind()")}} method lets you establish a fixed `this` context for all subsequent calls — bypassing problems where it's unclear what `this` will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can remove it later. This is an example with and without `bind()`: ```js class Something { name = "Something Good"; constructor(element) { // bind causes a fixed `this` context to be assigned to `onclick2` this.onclick2 = this.onclick2.bind(this); element.addEventListener("click", this.onclick1, false); element.addEventListener("click", this.onclick2, false); // Trick } onclick1(event) { console.log(this.name); // undefined, as `this` is the element } onclick2(event) { console.log(this.name); // 'Something Good', as `this` is bound to the Something instance } } const s = new Something(document.body); ``` Another solution is using a special function called `handleEvent()` to catch any events: ```js class Something { name = "Something Good"; constructor(element) { // Note that the listeners in this case are `this`, not this.handleEvent element.addEventListener("click", this, false); element.addEventListener("dblclick", this, false); } handleEvent(event) { console.log(this.name); // 'Something Good', as this is bound to newly created object switch (event.type) { case "click": // some code here… break; case "dblclick": // some code here… break; } } } const s = new Something(document.body); ``` Another way of handling the reference to `this` is to use an arrow function, which doesn't create a separate `this` context. ```js class SomeClass { name = "Something Good"; register() { window.addEventListener("keydown", (e) => { this.someMethod(e); }); } someMethod(e) { console.log(this.name); switch (e.keyCode) { case 5: // some code here… break; case 6: // some code here… break; } } } const myObject = new SomeClass(); myObject.register(); ``` ### Getting data into and out of an event listener It may seem that event listeners are like islands, and that it is extremely difficult to pass them any data, much less to get any data back from them after they execute. Event listeners only take one argument, the [Event Object](/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_objects), which is automatically passed to the listener, and the return value is ignored. So how can we get data in and back out of them? There are a number of good methods for doing this. #### Getting data into an event listener using "this" As mentioned [above](#specifying_this_using_bind), you can use `Function.prototype.bind()` to pass a value to an event listener via the `this` reference variable. ```js const myButton = document.getElementById("my-button-id"); const someString = "Data"; myButton.addEventListener("click", passIntoEvtListener.bind(someString)); //function declaration for event listener function passIntoEvtListener(e) { console.log("Expected Value:", this); // Expected Value: 'Data' console.log("current target:", e.currentTarget.id); // current target: my-button-id } ``` This method is suitable when you don't need to know which HTML element the event listener fired on programmatically from within the event listener. The primary benefit to doing this is that the event listener receives the data in much the same way that it would if you were to actually pass it through its argument list. #### Getting data into an event listener using the outer scope property When an outer scope contains a variable declaration (with `const`, `let`), all the inner functions declared in that scope have access to that variable (look [here](/en-US/docs/Glossary/Function#different_types_of_functions) for information on outer/inner functions, and [here](/en-US/docs/Web/JavaScript/Reference/Statements/var#implicit_globals_and_outer_function_scope) for information on variable scope). Therefore, one of the simplest ways to access data from outside of an event listener is to make it accessible to the scope in which the event listener is declared. ```js const myButton = document.getElementById("my-button-id"); let someString = "Data"; myButton.addEventListener("click", () => { console.log(someString); // Expected Value: 'Data' someString = "Data Again"; }); console.log(someString); // Expected Value: 'Data' (will never output 'Data Again') ``` > **Note:** Although inner scopes have access to `const`, > `let` variables from outer scopes, you cannot expect any changes to these > variables to be accessible after the event listener definition, within the same outer > scope. Why? Because by the time the event listener would execute, the scope in which > it was defined would have already finished executing. #### Getting data into and out of an event listener using objects Unlike most functions in JavaScript, objects are retained in memory as long as a variable referencing them exists in memory. This, and the fact that objects can have properties, and that they can be passed around by reference, makes them likely candidates for sharing data among scopes. Let's explore this. > **Note:** Functions in JavaScript are actually objects. (Hence they too > can have properties, and will be retained in memory even after they finish executing > if assigned to a variable that persists in memory.) Because object properties can be used to store data in memory as long as a variable referencing the object exists in memory, you can actually use them to get data into an event listener, and any changes to the data back out after an event handler executes. Consider this example. ```js const myButton = document.getElementById("my-button-id"); const someObject = { aProperty: "Data" }; myButton.addEventListener("click", () => { console.log(someObject.aProperty); // Expected Value: 'Data' someObject.aProperty = "Data Again"; // Change the value }); setInterval(() => { if (someObject.aProperty === "Data Again") { console.log("Data Again: True"); someObject.aProperty = "Data"; // Reset value to wait for next event execution } }, 5000); ``` In this example, even though the scope in which both the event listener and the interval function are defined would have finished executing before the original value of `someObject.aProperty` would have changed, because `someObject` persists in memory (by _reference_) in both the event listener and interval function, both have access to the same data (i.e. when one changes the data, the other can respond to the change). > **Note:** Objects are stored in variables by reference, meaning only the > memory location of the actual data is stored in the variable. Among other things, this > means variables that "store" objects can actually affect other variables that get > assigned ("store") the same object reference. When two variables reference the same > object (e.g., `let a = b = {aProperty: 'Yeah'};`), changing the data in > either variable will affect the other. > **Note:** Because objects are stored in variables by reference, you can > return an object from a function to keep it alive (preserve it in memory so you don't > lose the data) after that function stops executing. ### Memory issues ```js const elts = document.getElementsByTagName("*"); // Case 1 for (const elt of elts) { elt.addEventListener( "click", (e) => { // Do something }, false, ); } // Case 2 function processEvent(e) { // Do something } for (const elt of elts) { elt.addEventListener("click", processEvent, false); } ``` In the first case above, a new (anonymous) handler function is created with each iteration of the loop. In the second case, the same previously declared function is used as an event handler, which results in smaller memory consumption because there is only one handler function created. Moreover, in the first case, it is not possible to call {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} because no reference to the anonymous function is kept (or here, not kept to any of the multiple anonymous functions the loop might create.) In the second case, it's possible to do `myElement.removeEventListener("click", processEvent, false)` because `processEvent` is the function reference. Actually, regarding memory consumption, the lack of keeping a function reference is not the real issue; rather it is the lack of keeping a _static_ function reference. ### Using passive listeners If an event has a default action — for example, a {{domxref("Element/wheel_event", "wheel")}} event that scrolls the container by default — the browser is in general unable to start the default action until the event listener has finished, because it doesn't know in advance whether the event listener might cancel the default action by calling {{domxref("Event.preventDefault()")}}. If the event listener takes too long to execute, this can cause a noticeable delay, also known as {{glossary("jank")}}, before the default action can be executed. By setting the `passive` option to `true`, an event listener declares that it will not cancel the default action, so the browser can start the default action immediately, without waiting for the listener to finish. If the listener does then call {{domxref("Event.preventDefault()")}}, this will have no effect. The specification for `addEventListener()` defines the default value for the `passive` option as always being `false`. However, to realize the scroll performance benefits of passive listeners in legacy code, browsers other than Safari have changed the default value of the `passive` option to `true` for the {{domxref("Element/wheel_event", "wheel")}}, {{domxref("Element/mousewheel_event", "mousewheel")}}, {{domxref("Element/touchstart_event", "touchstart")}} and {{domxref("Element/touchmove_event", "touchmove")}} events on the document-level nodes {{domxref("Window")}}, {{domxref("Document")}}, and {{domxref("Document.body")}}. That prevents the event listener from [canceling the event](/en-US/docs/Web/API/Event/preventDefault), so it can't block page rendering while the user is scrolling. > **Note:** See the compatibility table below if you need to know which > browsers (and/or which versions of those browsers) implement this altered behavior. Because of that, when you want to override that behavior and ensure the `passive` option is `false` in all browsers, you must explicitly set the option to `false` (rather than relying on the default). You don't need to worry about the value of `passive` for the basic {{domxref("Element/scroll_event", "scroll")}} event. Since it can't be canceled, event listeners can't block page rendering anyway. See [Improving scroll performance using passive listeners](#improving_scroll_performance_using_passive_listeners) for an example showing the effect of passive listeners. ### Older browsers In older browsers that don't support the `options` parameter to `addEventListener()`, attempting to use it prevents the use of the `useCapture` argument without proper use of [feature detection](#safely_detecting_option_support). ## Examples ### Add a simple listener This example demonstrates how to use `addEventListener()` to watch for mouse clicks on an element. #### HTML ```html <table id="outside"> <tr> <td id="t1">one</td> </tr> <tr> <td id="t2">two</td> </tr> </table> ``` #### JavaScript ```js // Function to change the content of t2 function modifyText() { const t2 = document.getElementById("t2"); const isNodeThree = t2.firstChild.nodeValue === "three"; t2.firstChild.nodeValue = isNodeThree ? "two" : "three"; } // Add event listener to table const el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ``` In this code, `modifyText()` is a listener for `click` events registered using `addEventListener()`. A click anywhere in the table bubbles up to the handler and runs `modifyText()`. #### Result {{EmbedLiveSample('Add_a_simple_listener')}} ### Add an abortable listener This example demonstrates how to add an `addEventListener()` that can be aborted with an {{domxref("AbortSignal")}}. #### HTML ```html <table id="outside"> <tr> <td id="t1">one</td> </tr> <tr> <td id="t2">two</td> </tr> </table> ``` #### JavaScript ```js // Add an abortable event listener to table const controller = new AbortController(); const el = document.getElementById("outside"); el.addEventListener("click", modifyText, { signal: controller.signal }); // Function to change the content of t2 function modifyText() { const t2 = document.getElementById("t2"); if (t2.firstChild.nodeValue === "three") { t2.firstChild.nodeValue = "two"; } else { t2.firstChild.nodeValue = "three"; controller.abort(); // remove listener after value reaches "three" } } ``` In the example above, we modify the code in the previous example such that after the second row's content changes to "three", we call `abort()` from the {{domxref("AbortController")}} we passed to the `addEventListener()` call. That results in the value remaining as "three" forever because we no longer have any code listening for a click event. #### Result {{EmbedLiveSample('Add_an_abortable_listener')}} ### Event listener with anonymous function Here, we'll take a look at how to use an anonymous function to pass parameters into the event listener. #### HTML ```html <table id="outside"> <tr> <td id="t1">one</td> </tr> <tr> <td id="t2">two</td> </tr> </table> ``` #### JavaScript ```js // Function to change the content of t2 function modifyText(new_text) { const t2 = document.getElementById("t2"); t2.firstChild.nodeValue = new_text; } // Function to add event listener to table const el = document.getElementById("outside"); el.addEventListener( "click", function () { modifyText("four"); }, false, ); ``` Notice that the listener is an anonymous function that encapsulates code that is then, in turn, able to send parameters to the `modifyText()` function, which is responsible for actually responding to the event. #### Result {{EmbedLiveSample('Event_listener_with_anonymous_function')}} ### Event listener with an arrow function This example demonstrates a simple event listener implemented using arrow function notation. #### HTML ```html <table id="outside"> <tr> <td id="t1">one</td> </tr> <tr> <td id="t2">two</td> </tr> </table> ``` #### JavaScript ```js // Function to change the content of t2 function modifyText(new_text) { const t2 = document.getElementById("t2"); t2.firstChild.nodeValue = new_text; } // Add event listener to table with an arrow function const el = document.getElementById("outside"); el.addEventListener( "click", () => { modifyText("four"); }, false, ); ``` #### Result {{EmbedLiveSample('Event_listener_with_an_arrow_function')}} Please note that while anonymous and arrow functions are similar, they have different `this` bindings. While anonymous (and all traditional JavaScript functions) create their own `this` bindings, arrow functions inherit the `this` binding of the containing function. That means that the variables and constants available to the containing function are also available to the event handler when using an arrow function. ### Example of options usage #### HTML ```html <div class="outer"> outer, once & none-once <div class="middle" target="_blank"> middle, capture & none-capture <a class="inner1" href="https://www.mozilla.org" target="_blank"> inner1, passive & preventDefault(which is not allowed) </a> <a class="inner2" href="https://developer.mozilla.org/" target="_blank"> inner2, none-passive & preventDefault(not open new page) </a> </div> </div> ``` #### CSS ```css .outer, .middle, .inner1, .inner2 { display: block; width: 520px; padding: 15px; margin: 15px; text-decoration: none; } .outer { border: 1px solid red; color: red; } .middle { border: 1px solid green; color: green; width: 460px; } .inner1, .inner2 { border: 1px solid purple; color: purple; width: 400px; } ``` #### JavaScript ```js const outer = document.querySelector(".outer"); const middle = document.querySelector(".middle"); const inner1 = document.querySelector(".inner1"); const inner2 = document.querySelector(".inner2"); const capture = { capture: true, }; const noneCapture = { capture: false, }; const once = { once: true, }; const noneOnce = { once: false, }; const passive = { passive: true, }; const nonePassive = { passive: false, }; outer.addEventListener("click", onceHandler, once); outer.addEventListener("click", noneOnceHandler, noneOnce); middle.addEventListener("click", captureHandler, capture); middle.addEventListener("click", noneCaptureHandler, noneCapture); inner1.addEventListener("click", passiveHandler, passive); inner2.addEventListener("click", nonePassiveHandler, nonePassive); function onceHandler(event) { alert("outer, once"); } function noneOnceHandler(event) { alert("outer, none-once, default"); } function captureHandler(event) { //event.stopImmediatePropagation(); alert("middle, capture"); } function noneCaptureHandler(event) { alert("middle, none-capture, default"); } function passiveHandler(event) { // Unable to preventDefault inside passive event listener invocation. event.preventDefault(); alert("inner1, passive, open new page"); } function nonePassiveHandler(event) { event.preventDefault(); //event.stopPropagation(); alert("inner2, none-passive, default, not open new page"); } ``` #### Result Click the outer, middle, inner containers respectively to see how the options work. {{ EmbedLiveSample('Example_of_options_usage', 600, 310, '') }} Before using a particular value in the `options` object, it's a good idea to ensure that the user's browser supports it, since these are an addition that not all browsers have supported historically. See [Safely detecting option support](#safely_detecting_option_support) for details. ### Event listener with multiple options You can set more than one of the options in the `options` parameter. In the following example we are setting two options: - `passive`, to assert that the handler will not call {{domxref("Event.preventDefault", "preventDefault()")}} - `once`, to ensure that the event handler will only be called once. #### HTML ```html <button id="example-button">You have not clicked this button.</button> <button id="reset-button">Click this button to reset the first button.</button> ``` #### JavaScript ```js const buttonToBeClicked = document.getElementById("example-button"); const resetButton = document.getElementById("reset-button"); // the text that the button is initialized with const initialText = buttonToBeClicked.textContent; // the text that the button contains after being clicked const clickedText = "You have clicked this button."; // we hoist the event listener callback function // to prevent having duplicate listeners attached function eventListener() { buttonToBeClicked.textContent = clickedText; } function addListener() { buttonToBeClicked.addEventListener("click", eventListener, { passive: true, once: true, }); } // when the reset button is clicked, the example button is reset, // and allowed to have its state updated again resetButton.addEventListener("click", () => { buttonToBeClicked.textContent = initialText; addListener(); }); addListener(); ``` #### Result {{EmbedLiveSample('Event_listener_with_multiple_options')}} ### Improving scroll performance using passive listeners The following example shows the effect of setting `passive`. It includes a {{htmlelement("div")}} that contains some text, and a check box. #### HTML ```html <div id="container"> <p> But down there it would be dark now, and not the lovely lighted aquarium she imagined it to be during the daylight hours, eddying with schools of tiny, delicate animals floating and dancing slowly to their own serene currents and creating the look of a living painting. That was wrong, in any case. The ocean was different from an aquarium, which was an artificial environment. The ocean was a world. And a world is not art. Dorothy thought about the living things that moved in that world: large, ruthless and hungry. Like us up here. </p> </div> <div> <input type="checkbox" id="passive" name="passive" checked /> <label for="passive">passive</label> </div> ``` ```css hidden #container { width: 150px; height: 200px; overflow: scroll; margin: 2rem 0; padding: 0.4rem; border: 1px solid black; } ``` #### JavaScript The code adds a listener to the container's {{domxref("Element/wheel_event", "wheel")}} event, which by default scrolls the container. The listener runs a long-running operation. Initially the listener is added with the `passive` option, and whenever the checkbox is toggled, the code toggles the `passive` option. ```js const passive = document.querySelector("#passive"); passive.addEventListener("change", (event) => { container.removeEventListener("wheel", wheelHandler); container.addEventListener("wheel", wheelHandler, { passive: passive.checked, once: true, }); }); const container = document.querySelector("#container"); container.addEventListener("wheel", wheelHandler, { passive: true, once: true, }); function wheelHandler() { function isPrime(n) { for (let c = 2; c <= Math.sqrt(n); ++c) { if (n % c === 0) { return false; } } return true; } const quota = 1000000; const primes = []; const maximum = 1000000; while (primes.length < quota) { const candidate = Math.floor(Math.random() * (maximum + 1)); if (isPrime(candidate)) { primes.push(candidate); } } console.log(primes); } ``` #### Result The effect is that: - Initially, the listener is passive, so trying to scroll the container with the wheel is immediate. - If you uncheck "passive" and try to scroll the container using the wheel, then there is a noticeable delay before the container scrolls, because the browser has to wait for the long-running listener to finish. {{EmbedLiveSample("Improving scroll performance using passive listeners", 100, 300)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventTarget.removeEventListener()")}} - [Creating and triggering custom events](/en-US/docs/Web/Events/Creating_and_triggering_events) - [More details on the use of `this` in event handlers](https://www.quirksmode.org/js/this.html)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfontfacesrcelement/index.md
--- title: SVGFontFaceSrcElement slug: Web/API/SVGFontFaceSrcElement page-type: web-api-interface status: - deprecated browser-compat: api.SVGFontFaceSrcElement --- {{APIRef("SVG")}}{{deprecated_header}} The **`SVGFontFaceSrcElement`** interface corresponds to the {{SVGElement("font-face-src")}} elements. Object-oriented access to the attributes of the {{SVGElement("font-face-src")}} element via the SVG DOM is not possible. {{InheritanceDiagram}} ## Instance properties _This interface has no properties but inherits properties from its parent, {{domxref("SVGElement")}}._ ## Instance methods _This interface has no methods but inherits methods from its parent, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("font-face-src")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/local_font_access_api/index.md
--- title: Local Font Access API slug: Web/API/Local_Font_Access_API page-type: web-api-overview status: - experimental browser-compat: api.Window.queryLocalFonts spec-urls: https://wicg.github.io/local-font-access/ --- {{SeeCompatTable}}{{DefaultAPISidebar("Local Font Access API")}} The **Local Font Access API** provides a mechanism to access the user's locally installed font data — this includes higher-level details such as names, styles, and families, as well as the raw bytes of the underlying font files. ## Concepts and usage [Web fonts](/en-US/docs/Learn/CSS/Styling_text/Web_fonts) were revolutionary in enabling typography on the web by allowing web designers to provide custom fonts to use on a web document. Specified via the {{cssxref("@font-face")}} at-rule, a web font can be loaded from a URL provided in the `url()` function. `@font-face` has several other useful features available. In particular, you can also specify the font's full or Postscript name inside the `local()` function to tell the browser to use a local copy if the user has the font installed on their computer. This is not without its problems — `local()` has become notorious as a [fingerprinting vector](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts#local_fonts_as_fingerprint_vector). In addition, high-end design tools have historically been difficult to deliver on the web, due to challenges in accurate font enumeration and accessing low-level font data (for example, to apply filters and transformations). Current apps often rely on workarounds such as asking users to upload their fonts to a server where they are processed to get raw byte data, or installing a separate local program to provide additional capabilities. The Local Font Access API has been created to address these problems. The {{domxref("Window.queryLocalFonts()")}} method provides access to an array of locally-installed fonts, each represented by a {{domxref("FontData")}} object instance. {{domxref("FontData")}} has several properties providing access to names, styles, and families, and it also has a {{domxref("FontData.blob", "blob()")}} method providing access to a {{domxref("Blob")}} containing the raw bytes of the underlying font file. In terms of privacy and security: - The Local Font Access API is designed to only provide access to the data required to solve the above problems. There is also no requirement for browsers to provide the full list of available local fonts, nor to provide the data in the same order as it appears on disk. - When {{domxref("Window.queryLocalFonts()")}} is invoked, the user is asked for permission to access their local fonts. The status of this permission can be queried via the {{domxref("Permissions API")}} (the `local-fonts` permission). - You can control access to this feature using a {{httpheader("Permissions-Policy/local-fonts", "local-fonts")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). ## Interfaces - {{domxref("FontData")}} - : Represents a single local font face. ## Extensions to other interfaces - {{domxref("Window.queryLocalFonts()")}} - : Returns a {{jsxref("Promise")}} that fulfills with an array of {{domxref("FontData")}} objects representing the font faces available locally. ## Examples For a working live demo, see [Font Select Demo](https://local-font-access.glitch.me/demo/). ### Feature detection ```js if ("queryLocalFonts" in window) { // The Local Font Access API is supported } ``` ### Font enumeration The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control. ```js async function logFontData() { try { const availableFonts = await window.queryLocalFonts(); for (const fontData of availableFonts) { console.log(fontData.postscriptName); console.log(fontData.fullName); console.log(fontData.family); console.log(fontData.style); } } catch (err) { console.error(err.name, err.message); } } ``` ### Accessing low-level data The {{domxref("FontData.blob", "blob()")}} method provides access to low-level [SFNT](https://en.wikipedia.org/wiki/SFNT) data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF). ```js async function computeOutlineFormat() { try { const availableFonts = await window.queryLocalFonts({ postscriptNames: ["ComicSansMS"], }); for (const fontData of availableFonts) { // `blob()` returns a Blob containing valid and complete // SFNT-wrapped font data. const sfnt = await fontData.blob(); // Slice out only the bytes we need: the first 4 bytes are the SFNT // version info. // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font const sfntVersion = await sfnt.slice(0, 4).text(); let outlineFormat = "UNKNOWN"; switch (sfntVersion) { case "\x00\x01\x00\x00": case "true": case "typ1": outlineFormat = "truetype"; break; case "OTTO": outlineFormat = "cff"; break; } console.log("Outline format:", outlineFormat); } } catch (err) { console.error(err.name, err.message); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Use advanced typography with local fonts](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts) - {{cssxref("@font-face")}} - The {{httpheader("Permissions-Policy/local-fonts", "local-fonts")}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) directive
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/ext_color_buffer_float/index.md
--- title: EXT_color_buffer_float extension short-title: EXT_color_buffer_float slug: Web/API/EXT_color_buffer_float page-type: webgl-extension browser-compat: api.EXT_color_buffer_float --- {{APIRef("WebGL")}} The **`EXT_color_buffer_float`** extension is part of [WebGL](/en-US/docs/Web/API/WebGL_API) and adds the ability to render a variety of floating point formats. 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 {{domxref("WebGL2RenderingContext", "WebGL 2", "", 1)}} contexts only. > > For {{domxref("WebGLRenderingContext", "WebGL 1", "", 1)}}, see the {{domxref("EXT_color_buffer_half_float")}} and {{domxref("WEBGL_color_buffer_float")}} extensions. ## Extended methods The following sized formats become **color-renderable**: - `gl.R16F`, - `gl.RG16F`, - `gl.RGBA16F`, - `gl.R32F`, - `gl.RG32F`, - `gl.RGBA32F`, - `gl.R11F_G11F_B10F`. **Color-renderable** means: - The {{domxref("WebGLRenderingContext.renderbufferStorage()")}} method now accepts these formats. - Framebuffers with attached textures of these formats may now be **FRAMEBUFFER_COMPLETE**. ## Examples `gl` must be a {{domxref("WebGL2RenderingContext")}}. This extension does not work in WebGL 1 contexts. ```js const ext = gl.getExtension("EXT_color_buffer_float"); gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA16F, 256, 256); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("WebGLRenderingContext.renderbufferStorage()")}} - {{domxref("EXT_color_buffer_half_float")}} - {{domxref("WEBGL_color_buffer_float")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/presentationreceiver/index.md
--- title: PresentationReceiver slug: Web/API/PresentationReceiver page-type: web-api-interface status: - experimental browser-compat: api.PresentationReceiver --- {{securecontext_header}}{{SeeCompatTable}}{{APIRef("Presentation API")}} The **`PresentationReceiver`** interface of the [Presentation API](/en-US/docs/Web/API/Presentation_API) provides a means for a receiving browsing context to access controlling browsing contexts and communicate with them. ## Instance properties - {{domxref('PresentationReceiver.connectionList')}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{jsxref('Promise')}} that resolves with a {{domxref('PresentationConnectionList')}} object containing a list of _incoming presentation connections._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssnumericvalue/index.md
--- title: CSSNumericValue slug: Web/API/CSSNumericValue page-type: web-api-interface browser-compat: api.CSSNumericValue --- {{APIRef("CSS Typed OM")}} The **`CSSNumericValue`** interface of the [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Object_Model#css_typed_object_model) represents operations that all numeric values can perform. {{InheritanceDiagram}} ## Interfaces based on CSSNumericValue Below is a list of interfaces based on the CSSNumericValue interface. - {{domxref('CSSMathClamp')}} - {{domxref('CSSMathInvert')}} - {{domxref('CSSMathMax')}} - {{domxref('CSSMathMin')}} - {{domxref('CSSMathNegate')}} - {{domxref('CSSMathProduct')}} - {{domxref('CSSMathSum')}} - {{domxref('CSSMathValue')}} - {{domxref('CSSNumericArray')}} - {{domxref('CSSUnitValue')}} ## Instance properties None. ## Static methods - {{domxref('CSSNumericValue/parse_static', 'CSSNumericValue.parse')}} - : Allows a `CSSNumericValue` to be constructed directly from a string containing CSS. ## Instance methods - {{domxref('CSSNumericValue.add')}} - : Adds a supplied number to the `CSSNumericValue`. - {{domxref('CSSNumericValue.sub')}} - : Subtracts a supplied number from the `CSSNumericValue`. - {{domxref('CSSNumericValue.mul')}} - : Multiplies the `CSSNumericValue` by the supplied value. - {{domxref('CSSNumericValue.div')}} - : Divides the `CSSNumericValue` by the supplied value. - {{domxref('CSSNumericValue.min')}} - : Returns the minimum value passed - {{domxref('CSSNumericValue.max')}} - : Returns the maximum value passed - {{domxref('CSSNumericValue.equals')}} - : _True_ if all the values are the exact same type and value, in the same order. Otherwise, _false._ - {{domxref('CSSNumericValue.to')}} - : Converts `value` into another one with the specified _unit._ - {{domxref('CSSNumericValue.toSum')}} - : Converts an existing `CSSNumericValue` into a {{domxref("CSSMathSum")}} object with values of a specified unit. - {{domxref('CSSNumericValue.type')}} - : Returns the type of `CSSNumericValue`, one of `angle`, `flex`, `frequency`, `length`, `resolution`, `percent`, `percentHint`, or `time`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref('CSSImageValue')}} - {{domxref('CSSKeywordValue')}} - {{domxref('CSSPositionValue')}} - {{domxref('CSSTransformValue')}} - {{domxref('CSSUnparsedValue')}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/parse_static/index.md
--- title: "CSSNumericValue: parse() static method" short-title: parse() slug: Web/API/CSSNumericValue/parse_static page-type: web-api-static-method browser-compat: api.CSSNumericValue.parse_static --- {{APIRef("CSS Typed OM")}} The **`parse()`** static method of the {{domxref("CSSNumericValue")}} interface converts a value string into an object whose members are value and the units. ## Syntax ```js-nolint CSSNumericValue.parse(cssText) ``` ### Parameters - `cssText` - : a string containing numeric and unit parts. ### Return value A {{domxref('CSSNumericValue')}}. ### Exceptions - `SyntaxError` {{domxref("DOMException")}} - : TBD ## Examples The following returns a {{domxref('CSSUnitValue')}} object with a `unit` property equal to `"px"` and a `value` property equal to `42`. ```js let numValue = CSSNumericValue.parse("42.0px"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/add/index.md
--- title: "CSSNumericValue: add() method" short-title: add() slug: Web/API/CSSNumericValue/add page-type: web-api-instance-method browser-compat: api.CSSNumericValue.add --- {{APIRef("CSS Typed OM")}} The **`add()`** method of the {{domxref("CSSNumericValue")}} interface adds a supplied number to the `CSSNumericValue`. ## Syntax ```js-nolint add(number) ``` ### Parameters - `number` - : Either a number or a {{domxref('CSSNumericValue')}}. ### Return value A {{domxref('CSSMathSum')}} ### Exceptions - {{jsxref("TypeError")}} - : Thrown if an invalid type was passed to the method. ## Examples ```js let mathSum = CSS.px("23") .add(CSS.percent("4")) .add(CSS.cm("3")) .add(CSS.in("9")); // Prints "calc(23px + 4% + 3cm + 9in)" console.log(mathSum.toString()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/div/index.md
--- title: "CSSNumericValue: div() method" short-title: div() slug: Web/API/CSSNumericValue/div page-type: web-api-instance-method browser-compat: api.CSSNumericValue.div --- {{APIRef("CSS Typed OM")}} The **`div()`** method of the {{domxref("CSSNumericValue")}} interface divides the `CSSNumericValue` by the supplied value. ## Syntax ```js-nolint div(number) ``` ### Parameters - `number` - : Either a number or a {{domxref('CSSNumericValue')}}. ### Return value A {{domxref('CSSMathProduct')}}. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if an invalid type was passed to the method. ## Examples ```js let mathProduct = CSS.px("24").div(CSS.percent("4")); // Prints "calc(24px / 4%)" mathProduct.toString(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/equals/index.md
--- title: "CSSNumericValue: equals() method" short-title: equals() slug: Web/API/CSSNumericValue/equals page-type: web-api-instance-method browser-compat: api.CSSNumericValue.equals --- {{APIRef("CSS Typed OM")}} The **`equals()`** method of the {{domxref("CSSNumericValue")}} interface returns a boolean indicating whether the passed value are strictly equal. To return a value of `true`, all passed values must be of the same type and value and must be in the same order. This allows structural equality to be tested quickly. ## Syntax ```js-nolint equals(number) ``` ### Parameters - `number` - : Either a number or a {{domxref('CSSNumericValue')}}. ### Return value A boolean value. ### Exceptions None. ## Examples As stated earlier, all passed values must be of the same type and value and must be in the same order. Some of the following examples illustrate what happens when they are not. ```js let cssMathSum = new CSSMathSum(CSS.px(1), CSS.px(2)); let matchingCssMathSum = new CSSMathSum(CSS.px(1), CSS.px(2)); // Prints true console.log(cssMathSum.equals(matchingCssMathSum)); let otherCssMathSum = CSSMathSum(CSS.px(2), CSS.px(1)); // Prints false console.log(cssMathSum.equals(otherCssMathSum)); // Also prints false console.log(CSS.cm("1").equal(CSS.in("0.393701"))); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/mul/index.md
--- title: "CSSNumericValue: mul() method" short-title: mul() slug: Web/API/CSSNumericValue/mul page-type: web-api-instance-method browser-compat: api.CSSNumericValue.mul --- {{APIRef("CSS Typed OM")}} The **`mul()`** method of the {{domxref("CSSNumericValue")}} interface multiplies the `CSSNumericValue` by the supplied value. ## Syntax ```js-nolint mul(number) ``` ### Parameters - `number` - : Either a number or a {{domxref('CSSNumericValue')}}. ### Return value A {{domxref('CSSMathProduct')}} ### Exceptions - {{jsxref("TypeError")}} - : Thrown if an invalid type was passed to the method. ## Examples ```js let mathSum = CSS.px("23") .mul(CSS.percent("4")) .mul(CSS.cm("3")) .mul(CSS.in("9")); // Prints "calc(23px * 4% * 3cm * 9in)" console.log(mathSum.toString()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/to/index.md
--- title: "CSSNumericValue: to() method" short-title: to() slug: Web/API/CSSNumericValue/to page-type: web-api-instance-method browser-compat: api.CSSNumericValue.to --- {{APIRef("CSS Typed OM")}} The **`to()`** method of the {{domxref("CSSNumericValue")}} interface converts a numeric value from one unit to another. ## Syntax ```js-nolint to(unit) ``` ### Parameters - `unit` - : The unit to which you want to convert. ### Return value A {{domxref('CSSMathSum')}}. ### Exceptions - `SyntaxError` {{domxref("DOMException")}} - : Thrown if an invalid type was passed to the method. - {{jsxref("TypeError")}} - : Thrown if the passed values cannot be summed. ## Examples ```js // Prints "0.608542cm" console.log(CSS.px("23").to("cm").toString()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/min/index.md
--- title: "CSSNumericValue: min() method" short-title: min() slug: Web/API/CSSNumericValue/min page-type: web-api-instance-method browser-compat: api.CSSNumericValue.min --- {{APIRef("CSS Typed OM")}} The **`min()`** method of the {{domxref("CSSNumericValue")}} interface returns the lowest value from among those values passed. The passed values must be of the same type. ## Syntax ```js-nolint min(number1, /* …, */ numberN) ``` ### Parameters - `number1`, …, `numberN` - : Either a number or a {{domxref('CSSNumericValue')}}. ### Return value A {{domxref('CSSUnitValue')}}. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if an invalid type was passed to the method. ## Examples As stated earlier, all passed values must be of the same type and value. Some of the following examples illustrate what happens when they are not. ```js // Prints "1cm" console.log(CSS.cm("1").min(CSS.cm("2")).toString()); // Prints "max(1cm, 0.393701in)" console.log(CSS.cm("1").max(CSS.in("0.393701")).toString()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/tosum/index.md
--- title: "CSSNumericValue: toSum() method" short-title: toSum() slug: Web/API/CSSNumericValue/toSum page-type: web-api-instance-method browser-compat: api.CSSNumericValue.toSum --- {{APIRef("CSS Typed OM")}} The **`toSum()`** method of the {{domxref("CSSNumericValue")}} interface converts the object's value to a {{domxref("CSSMathSum")}} object to values of the specified unit. ## Syntax ```js-nolint toSum(units) ``` ### Parameters - `units` - : The units to convert to. ### Return value A {{domxref('CSSNumericValue')}}. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if an invalid type was passed to the method. ## Examples ```js let v = CSS.px("23").add(CSS.percent("4")).add(CSS.cm("3")).add(CSS.in("9")); v.toString(); // => "calc(23px + 4% + 3cm + 9in)" v.toSum("px", "percent").toString(); // => "calc(1000.39px + 4%)" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/type/index.md
--- title: "CSSNumericValue: type() method" short-title: type() slug: Web/API/CSSNumericValue/type page-type: web-api-instance-method browser-compat: api.CSSNumericValue.type --- {{APIRef("CSS Typed OM")}} The **`type()`** method of the {{domxref("CSSNumericValue")}} interface returns the type of `CSSNumericValue`, one of `angle`, `flex`, `frequency`, `length`, `resolution`, `percent`, `percentHint`, or `time`. ## Syntax ```js-nolint type() ``` ### Parameters None. ### Return value A {{domxref('CSSNumericType')}} object. ### Exceptions None. ## Examples ```js let mathSum = CSS.px("23") .sub(CSS.percent("4")) .sub(CSS.cm("3")) .sub(CSS.in("9")); // Returns an object with the structure: {length: 1, percentHint: "length"} let cssNumericType = mathSum.type(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/sub/index.md
--- title: "CSSNumericValue: sub() method" short-title: sub() slug: Web/API/CSSNumericValue/sub page-type: web-api-instance-method browser-compat: api.CSSNumericValue.sub --- {{APIRef("CSS Typed OM")}} The **`sub()`** method of the {{domxref("CSSNumericValue")}} interface subtracts a supplied number from the `CSSNumericValue`. ## Syntax ```js-nolint sub(number) ``` ### Parameters - `number` - : Either a number or a {{domxref('CSSMathSum')}}. ### Return value A {{domxref('CSSMathSum')}} ### Exceptions - {{jsxref("TypeError")}} - : Thrown if an invalid type was passed to the method. ## Examples ```js let mathSum = CSS.px("23") .sum(CSS.percent("4")) .sum(CSS.cm("3")) .sum(CSS.in("9")); // Prints "calc(23px - 4% - 3cm - 9in)" console.log(mathSum.toString()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssnumericvalue
data/mdn-content/files/en-us/web/api/cssnumericvalue/max/index.md
--- title: "CSSNumericValue: max() method" short-title: max() slug: Web/API/CSSNumericValue/max page-type: web-api-instance-method browser-compat: api.CSSNumericValue.max --- {{APIRef("CSS Typed OM")}} The **`max()`** method of the {{domxref("CSSNumericValue")}} interface returns the highest value from among the values passed. The passed values must be of the same type. ## Syntax ```js-nolint max(number1, /* …, */ numberN) ``` ### Parameters - `number1`, …, `numberN` - : Either a number or a {{domxref('CSSNumericValue')}}. ### Return value A {{domxref('CSSUnitValue')}}. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if an invalid type was passed to the method. ## Examples As stated earlier, all passed values must be of the same type and value. Some of the following examples illustrate what happens when they are not. ```js // Prints "2cm" console.log(CSS.cm("1").max(CSS.cm("2")).toString()); // Prints "max(1cm, 0.393701in)" console.log(CSS.cm("1").max(CSS.in("0.393701")).toString()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/audioscheduledsourcenode/index.md
--- title: AudioScheduledSourceNode slug: Web/API/AudioScheduledSourceNode page-type: web-api-interface browser-compat: api.AudioScheduledSourceNode --- {{APIRef("Web Audio API")}} The `AudioScheduledSourceNode` interface—part of the Web Audio API—is a parent interface for several types of audio source node interfaces which share the ability to be started and stopped, optionally at specified times. Specifically, this interface defines the {{domxref("AudioScheduledSourceNode.start", "start()")}} and {{domxref("AudioScheduledSourceNode.stop", "stop()")}} methods, as well as the {{domxref("AudioScheduledSourceNode.ended_event", "ended")}} event. > **Note:** You can't create an `AudioScheduledSourceNode` object directly. Instead, use an interface which extends it, such as {{domxref("AudioBufferSourceNode")}}, {{domxref("OscillatorNode")}} or {{domxref("ConstantSourceNode")}}. Unless stated otherwise, nodes based upon `AudioScheduledSourceNode` output silence when not playing (that is, before `start()` is called and after `stop()` is called). Silence is represented, as always, by a stream of samples with the value zero (0). {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent interface, {{domxref("AudioNode")}}._ ## Instance methods _Inherits methods from its parent interface, {{domxref("AudioNode")}}, and adds the following methods:_ - {{domxref("AudioScheduledSourceNode.start", "start()")}} - : Schedules the node to begin playing the constant sound at the specified time. If no time is specified, the node begins playing immediately. - {{domxref("AudioScheduledSourceNode.stop", "stop()")}} - : Schedules the node to stop playing at the specified time. If no time is specified, the node stops playing at once. ## Events Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the `oneventname` property of this interface: - [`ended`](/en-US/docs/Web/API/AudioScheduledSourceNode/ended_event) - : Fired when the source node has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API) - {{domxref("AudioNode")}}
0
data/mdn-content/files/en-us/web/api/audioscheduledsourcenode
data/mdn-content/files/en-us/web/api/audioscheduledsourcenode/stop/index.md
--- title: "AudioScheduledSourceNode: stop() method" short-title: stop() slug: Web/API/AudioScheduledSourceNode/stop page-type: web-api-instance-method browser-compat: api.AudioScheduledSourceNode.stop --- {{ APIRef("Web Audio API") }} The `stop()` method on {{domxref("AudioScheduledSourceNode")}} schedules a sound to cease playback at the specified time. If no time is specified, then the sound stops playing immediately. Each time you call `stop()` on the same node, the specified time replaces any previously-scheduled stop time that hasn't occurred yet. If the node has already stopped, this method has no effect. > **Note:** If a scheduled stop time occurs before the node's scheduled > start time, the node never starts to play. ## Syntax ```js-nolint stop() stop(when) ``` ### Parameters - `when` {{optional_inline}} - : The time, in seconds, at which the sound should stop playing. This value is specified in the same time coordinate system as the {{domxref("AudioContext")}} is using for its {{domxref("BaseAudioContext/currentTime", "currentTime")}} attribute. Omitting this parameter, specifying a value of 0, or passing a negative value causes the sound to stop playback immediately. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateNode` {{domxref("DOMException")}} - : Thrown if the node has not been started by calling {{domxref("AudioScheduledSourceNode.start", "start()")}}. - {{jsxref("RangeError")}} - : Thrown if the value specified for `when` is negative. ## Examples This example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second. The stop time is determined by taking the audio context's current time from {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}} and adding 1 second. ```js context = new AudioContext(); osc = context.createOscillator(); osc.connect(context.destination); /* Let's play a sine wave for one second. */ osc.start(); osc.stop(context.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) - {{domxref("AudioScheduledSourceNode.start", "start()")}} - {{domxref("AudioScheduledSourceNode")}} - {{domxref("AudioBufferSourceNode")}} - {{domxref("ConstantSourceNode")}} - {{domxref("OscillatorNode")}}
0
data/mdn-content/files/en-us/web/api/audioscheduledsourcenode
data/mdn-content/files/en-us/web/api/audioscheduledsourcenode/start/index.md
--- title: "AudioScheduledSourceNode: start() method" short-title: start() slug: Web/API/AudioScheduledSourceNode/start page-type: web-api-instance-method browser-compat: api.AudioScheduledSourceNode.start --- {{APIRef("Web Audio API")}} The `start()` method on {{domxref("AudioScheduledSourceNode")}} schedules a sound to begin playback at the specified time. If no time is specified, then the sound begins playing immediately. ## Syntax ```js-nolint start() start(when) ``` ### Parameters - `when` {{optional_inline}} - : The time, in seconds, at which the sound should begin to play. This value is specified in the same time coordinate system as the {{domxref("AudioContext")}} is using for its {{domxref("BaseAudioContext/currentTime", "currentTime")}} attribute. A value of 0 (or omitting the `when` parameter entirely) causes the sound to start playback immediately. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateNode` {{domxref("DOMException")}} - : Thrown if the node has already been started. This error occurs even if the node is no longer running because of a prior call to {{domxref("AudioScheduledSourceNode.stop", "stop()")}}. - {{jsxref("RangeError")}} - : Thrown if the value specified for `when` is negative. ## Examples This example demonstrates how to create an {{domxref("OscillatorNode")}} which is scheduled to start playing in 2 seconds and stop playing 1 second after that. The times are calculated by adding the desired number of seconds to the context's current time stamp returned by {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}. ```js context = new AudioContext(); osc = context.createOscillator(); osc.connect(context.destination); /* Schedule the start and stop times for the oscillator */ osc.start(context.currentTime + 2); osc.stop(context.currentTime + 3); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API) - {{domxref("AudioScheduledSourceNode.stop", "stop()")}} - {{domxref("AudioScheduledSourceNode")}} - {{domxref("AudioBufferSourceNode")}} - {{domxref("ConstantSourceNode")}} - {{domxref("OscillatorNode")}}
0
data/mdn-content/files/en-us/web/api/audioscheduledsourcenode
data/mdn-content/files/en-us/web/api/audioscheduledsourcenode/ended_event/index.md
--- title: "AudioScheduledSourceNode: ended event" short-title: ended slug: Web/API/AudioScheduledSourceNode/ended_event page-type: web-api-event browser-compat: api.AudioScheduledSourceNode.ended_event --- {{DefaultAPISidebar("Web Audio API")}} The `ended` event of the {{domxref("AudioScheduledSourceNode")}} interface is fired when the source node has stopped playing. This event occurs when a {{domxref("AudioScheduledSourceNode")}} has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played. 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-nolint addEventListener("ended", (event) => { }) onended = (event) => { } ``` ## Event type A generic {{domxref("Event")}}. ## Examples In this simple example, an event listener for the `ended` event is set up to enable a "Start" button in the user interface when the node stops playing: ```js node.addEventListener("ended", () => { document.getElementById("startButton").disabled = false; }); ``` You can also set up the event handler using the `onended` property: ```js node.onended = () => { document.getElementById("startButton").disabled = false; }; ``` For an example of the ended event in use, see our [audio-buffer example on GitHub](https://mdn.github.io/webaudio-examples/audio-buffer/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related events - [audioprocess](/en-US/docs/Web/API/ScriptProcessorNode/audioprocess_event) - [complete](/en-US/docs/Web/API/OfflineAudioContext/complete_event) ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}} - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The MediaStreamTrack {{domxref("MediaStreamTrack.ended_event", 'ended')}} event
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/speechrecognitionevent/index.md
--- title: SpeechRecognitionEvent slug: Web/API/SpeechRecognitionEvent page-type: web-api-interface browser-compat: api.SpeechRecognitionEvent --- {{APIRef("Web Speech API")}} The **`SpeechRecognitionEvent`** interface of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) represents the event object for the {{domxref("SpeechRecognition.result_event", "result")}} and {{domxref("SpeechRecognition.nomatch_event", "nomatch")}} events, and contains all the data associated with an interim or final speech recognition result. {{InheritanceDiagram}} ## Instance properties _`SpeechRecognitionEvent` also inherits properties from its parent interface, {{domxref("Event")}}._ - {{domxref("SpeechRecognitionEvent.emma")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns an Extensible MultiModal Annotation markup language (EMMA) — XML — representation of the result. - {{domxref("SpeechRecognitionEvent.interpretation")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns the semantic meaning of what the user said. - {{domxref("SpeechRecognitionEvent.resultIndex")}} {{ReadOnlyInline}} - : Returns the lowest index value result in the {{domxref("SpeechRecognitionResultList")}} "array" that has actually changed. - {{domxref("SpeechRecognitionEvent.results")}} {{ReadOnlyInline}} - : Returns a {{domxref("SpeechRecognitionResultList")}} object representing all the speech recognition results for the current session. ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. ```js recognition.onresult = (event) => { // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects. // It has a getter so it can be accessed like an array // The first [0] returns the SpeechRecognitionResult at position 0. // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects that contain // individual results. // These also have getters so they can be accessed like arrays. // The second [0] returns the SpeechRecognitionAlternative at position 0. // We then return the transcript property of the SpeechRecognitionAlternative object const color = event.results[0][0].transcript; diagnostic.textContent = `Result received: ${color}.`; bg.style.backgroundColor = color; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognitionevent
data/mdn-content/files/en-us/web/api/speechrecognitionevent/results/index.md
--- title: "SpeechRecognitionEvent: results property" short-title: results slug: Web/API/SpeechRecognitionEvent/results page-type: web-api-instance-property browser-compat: api.SpeechRecognitionEvent.results --- {{APIRef("Web Speech API")}} The **`results`** read-only property of the {{domxref("SpeechRecognitionEvent")}} interface returns a {{domxref("SpeechRecognitionResultList")}} object representing all the speech recognition results for the current session. Specifically this object will contain all final results that have been returned, followed by the current best hypothesis for all interim results. When subsequent {{domxref("SpeechRecognition.result_event", "result")}} events are fired, interim results may be overwritten by a newer interim result or by a final result — they may even be removed, if they are at the end of the "results" array and the array length decreases. Final results on the other hand will not be overwritten or removed. ## Value A {{domxref("SpeechRecognitionResultList")}} object. ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. ```js recognition.onresult = (event) => { // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects. // It has a getter so it can be accessed like an array // The first [0] returns the SpeechRecognitionResult at position 0. // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects that contain individual results. // These also have getters so they can be accessed like arrays. // The second [0] returns the SpeechRecognitionAlternative at position 0. // We then return the transcript property of the SpeechRecognitionAlternative object const color = event.results[0][0].transcript; diagnostic.textContent = `Result received: ${color}.`; bg.style.backgroundColor = color; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognitionevent
data/mdn-content/files/en-us/web/api/speechrecognitionevent/interpretation/index.md
--- title: "SpeechRecognitionEvent: interpretation property" short-title: interpretation slug: Web/API/SpeechRecognitionEvent/interpretation page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.SpeechRecognitionEvent.interpretation --- {{APIRef("Web Speech API")}}{{deprecated_header}}{{Non-standard_header}} The **`interpretation`** read-only property of the {{domxref("SpeechRecognitionEvent")}} interface returns the semantic meaning of what the user said. This might be determined, for instance, through the SISR specification of semantics in a grammar (see [Semantic Interpretation for Speech Recognition (SISR) Version 1.0](https://www.w3.org/TR/semantic-interpretation/) for specification and examples.) ## Value The returned value can be of any type. If no semantic interpretation has been returned by the speech recognition system, `null` will be returned. ## Examples ```js recognition.onresult = (event) => { const color = event.results[0][0].transcript; diagnostic.textContent = `Result received: ${color}.`; bg.style.backgroundColor = color; console.log(event.interpretation); }; ``` ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognitionevent
data/mdn-content/files/en-us/web/api/speechrecognitionevent/resultindex/index.md
--- title: "SpeechRecognitionEvent: resultIndex property" short-title: resultIndex slug: Web/API/SpeechRecognitionEvent/resultIndex page-type: web-api-instance-property browser-compat: api.SpeechRecognitionEvent.resultIndex --- {{APIRef("Web Speech API")}} The **`resultIndex`** read-only property of the {{domxref("SpeechRecognitionEvent")}} interface returns the lowest index value result in the {{domxref("SpeechRecognitionResultList")}} "array" that has actually changed. The {{domxref("SpeechRecognitionResultList")}} object is not an array, but it has a getter that allows it to be accessed by array syntax. ## Value A number. ## Examples ```js recognition.onresult = (event) => { const color = event.results[0][0].transcript; diagnostic.textContent = `Result received: ${color}.`; bg.style.backgroundColor = color; console.log(event.resultIndex); // returns 0 if there is only one result }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognitionevent
data/mdn-content/files/en-us/web/api/speechrecognitionevent/emma/index.md
--- title: "SpeechRecognitionEvent: emma property" short-title: emma slug: Web/API/SpeechRecognitionEvent/emma page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.SpeechRecognitionEvent.emma --- {{APIRef("Web Speech API")}}{{deprecated_header}}{{Non-standard_header}} The **`emma`** read-only property of the {{domxref("SpeechRecognitionEvent")}} interface returns an Extensible MultiModal Annotation markup language (EMMA) — XML — representation of the result. > **Note:** EMMA is defined in the specification [EMMA: Extensible MultiModal Annotation markup language](https://www.w3.org/TR/emma/). You can see multiple EMMA examples in the spec. ## Value A valid XML document. The exact contents can vary across user agents and recognition engines, but all supporting implementations will expose a valid XML document complete with an EMMA namespace. If the speech recognition system does not supply EMMA data then the user agent will return `null`. ## Examples ```js recognition.onresult = (event) => { const color = event.results[0][0].transcript; diagnostic.textContent = `Result received: ${color}.`; bg.style.backgroundColor = color; console.log(event.emma); }; ``` ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/media_session_api/index.md
--- title: Media Session API slug: Web/API/Media_Session_API page-type: web-api-overview browser-compat: api.MediaSession --- {{DefaultAPISidebar("Media Session API")}} The **Media Session API** provides a way to customize media notifications. It does this by providing metadata for display by the user agent for the media your web app is playing. It also provides action handlers that the browser can use to access platform media keys such as hardware keys found on keyboards, headsets, remote controls, and software keys found in notification areas and on lock screens of mobile devices. So you can seamlessly control web-provided media via your device, even when not looking at the web page. The aim is to allow users to know what's playing and to control it, without needing to open the specific page that launched it. To be able to support the Media Session API, a browser first needs a mechanism by which to access and be controlled by the OS-level media controls (such as Firefox's [MediaControl](https://bugzil.la/1648100)). ## Media Session concepts and usage The {{domxref("MediaMetadata")}} interface lets a website provide rich metadata to the platform UI for media that is playing. This metadata includes the title, artist (creator) name, album (collection), and artwork. The platform can show this metadata in media centers, notifications, device lockscreens, etc. The {{domxref("MediaSession")}} interface lets users control playback of media through user-agent defined interface elements. Interaction with these elements triggers action handlers in the web page, playing the media. Since multiple pages may be simultaneously using this API, the user agent is responsible for calling the correct page's action handlers. The user agent provides default behaviors, when no page-defined behavior is available. ## Accessing the Media Session API The primary interface for the Media Session API is the {{domxref("MediaSession")}} interface. Rather than creating your own `MediaSession` instance, you access the API using the {{domxref("navigator.mediaSession")}} property. For example, to set the current state of the media session to `playing`: ```js navigator.mediaSession.playbackState = "playing"; ``` ## Interfaces - {{domxref("MediaMetadata")}} - : Allows a web page to provide rich media metadata for display in a platform UI. - {{domxref("MediaSession")}} - : Allows a web page to provide custom behaviors for standard media playback interactions. ## Examples ### Setting up action handlers for a music player The following example shows feature detection for the Media Session API. It then instantiates a metadata object for the session, and adds action handlers for the user control actions: ```js if ("mediaSession" in navigator) { navigator.mediaSession.metadata = new MediaMetadata({ title: "Unforgettable", artist: "Nat King Cole", album: "The Ultimate Collection (Remastered)", artwork: [ { src: "https://dummyimage.com/96x96", sizes: "96x96", type: "image/png", }, { src: "https://dummyimage.com/128x128", sizes: "128x128", type: "image/png", }, { src: "https://dummyimage.com/192x192", sizes: "192x192", type: "image/png", }, { src: "https://dummyimage.com/256x256", sizes: "256x256", type: "image/png", }, { src: "https://dummyimage.com/384x384", sizes: "384x384", type: "image/png", }, { src: "https://dummyimage.com/512x512", sizes: "512x512", type: "image/png", }, ], }); navigator.mediaSession.setActionHandler("play", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("pause", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("stop", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("seekbackward", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("seekforward", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("seekto", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("previoustrack", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("nexttrack", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("skipad", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("togglecamera", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("togglemicrophone", () => { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler("hangup", () => { /* Code excerpted. */ }); } ``` Some user agents disable autoplay for media elements on mobile devices and require a user gesture to start media. The following example adds a `pointerup` event to an on-page play button, which is then used to kick off the media session code: ```js playButton.addEventListener("pointerup", (event) => { const audio = document.querySelector("audio"); // User interacted with the page. Let's play audio! audio .play() .then(() => { /* Set up media session controls, as shown above. */ }) .catch((error) => { console.error(error); }); }); ``` ### Using action handlers to control a slide presentation The `"previousslide"` and `"nextslide"` action handlers can be used to handle moving forward and backward through a slide presentation, for example when the user puts their presentation into a {{domxref("Picture-in-Picture API", "Picture-in-Picture", "", "nocode")}} window, and presses the browser-supplied controls for navigating through slides. ```js try { navigator.mediaSession.setActionHandler("previousslide", () => { log('> User clicked "Previous Slide" icon.'); if (slideNumber > 1) slideNumber--; updateSlide(); }); } catch (error) { log('Warning! The "previousslide" media session action is not supported.'); } try { navigator.mediaSession.setActionHandler("nextslide", () => { log('> User clicked "Next Slide" icon.'); slideNumber++; updateSlide(); }); } catch (error) { log('Warning! The "nextslide" media session action is not supported.'); } ``` See [Presenting Slides / Media Session Sample](https://googlechrome.github.io/samples/media-session/slides.html) for a working example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrviewerpose/index.md
--- title: XRViewerPose slug: Web/API/XRViewerPose page-type: web-api-interface browser-compat: api.XRViewerPose --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The WebXR Device API interface **`XRViewerPose`** represents the pose (the position and orientation) of a viewer's point of view on the scene. Each `XRViewerPose` can have multiple views to represent, for example, the slight separation between the left and right eye. This view can represent anything from the point-of-view of a user's XR headset to the viewpoint represented by a player's movement of an avatar using mouse and keyboard, presented on the screen, to a virtual camera capturing the scene for a spectator. {{InheritanceDiagram}} ## Instance properties _In addition to the properties inherited from {{domxref("XRPose")}}, `XRViewerPose` includes the following:_ - {{domxref("XRViewerPose.views", "views")}} {{ReadOnlyInline}} - : An array of {{domxref("XRView")}} objects, one for each viewpoint on the scene which is needed to represent the scene to the user. A typical headset provides a viewer pose with two views whose {{domxref("XRView.eye", "eye")}} property is either `left` or `right`, indicating which eye that view represents. Taken together, these views can reproduce the 3D effect when displayed on the XR device. ## Usage notes The `XRViewerPose` object is used to describe the state of a viewer of a WebXR scene as it's tracked by the user's XR hardware. The viewer may be the virtual representation of the user, or it may represent another device or interface which may serve as the source of a position and orientation that make up a view upon the scene. For example, every player in a MMORPG might have an instance of `XRViewerPose` to provide a way to calculate what they can see; if the game provides a mechanism that tells the player if another player sees them, or that they see another player, this information becomes crucial. An `XRViewerPose` is always obtained and referenced relative to an existing {{domxref("XRReferenceSpace")}}. This ensures that positions and orientations are reported using the expected relative coordinate system. To render a scene using the `XRViewerPose` representing the user's head, one would iterate over the views in the {{domxref("XRViewerPose.views", "views")}} array, rendering them one after another. By calling {{domxref("WebGLRenderingContext.viewport", "viewport()")}} on the WebGL context, specifying the `XRView` as input, you can get the viewport to use when rendering in order to draw the frame for that eye into the correct part of the drawing surface. Also, when rendering the scene for spectators or other players in a multiplayer game, the {{domxref("XRPose.transform", "transform")}} of the `XRViewerPose` can be used to determine both placement and facing direction of the other players in the game, so that they can be drawn in the correct place with the correct facing. The viewer's pose for the animation frame represented by {{domxref("XRFrame")}} can be obtained by calling the frame's {{domxref("XRFrame.getViewerPose", "getViewerPose()")}} method, specifying the reference space in which the origin's position should be computed. The returned `XRViewerPose` tells you where the viewer is and what direction they're facing at the time at which the frame takes place. ## Examples In this example—part of the code to render an {{domxref("XRFrame")}}, `getViewerPose()` is called to get an `XRViewerPose` using the same reference space the code is using as its base reference space. If a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. ```js const pose = frame.getViewerPose(xrReferenceSpace); if (pose) { const glLayer = xrSession.renderState.baseLayer; gl.bindFrameBuffer(gl.FRAMEBUFFER, glLayer.framebuffer); gl.clearColor(0, 0, 0, 1); gl.clearDepth(1); gl.clear(gl.COLOR_BUFFER_BIT, gl.DEPTH_BUFFER_BIT); for (const view of pose.views) { const viewport = glLayer.getViewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); /* render the scene for the eye view.eye */ } } ``` Passing each `view` to {{domxref("XRWebGLLayer.getViewport", "getViewport()")}} returns the WebGL viewport to apply in order to cause the rendered output to be positioned correctly in the framebuffer for rendering to the corresponding eye on the output device. This code is derived from [Drawing a frame](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion#drawing_a_frame) in our "Movement and motion" WebXR example. You can see more context and see much more on that page. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) - [Movement, orientation, and motion](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion) - {{domxref("XRPose")}} and {{domxref("XRView")}}
0
data/mdn-content/files/en-us/web/api/xrviewerpose
data/mdn-content/files/en-us/web/api/xrviewerpose/views/index.md
--- title: "XRViewerPose: views property" short-title: views slug: Web/API/XRViewerPose/views page-type: web-api-instance-property browser-compat: api.XRViewerPose.views --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The read-only {{domxref("XRViewerPose")}} property **`views`** returns an array which contains every {{domxref("XRView")}} which must be rendered in order to fully represent the scene from the viewpoint defined by the viewer pose. For monoscopic devices, this array contains a single view. > **Warning:** There is no guarantee that the number of views will > remain constant over the lifetime of an {{domxref("XRSession")}}. For each frame, you > should always use the current length of this array rather than caching the value. Stereo views require two views to render properly, with the left eye's view having its {{domxref("XRView.eye", "eye")}} set to the string `left` and the right eye's view a value of `right`. ## Value An array of {{domxref("XRView")}} objects, one for each view available as part of the scene for the current viewer pose. This array's length may potentially vary over the lifetime of the {{domxref("XRSession")}} (for example, if the viewer enables or disables stereo mode on their XR output device). ## Examples See [`XRViewerPose`](/en-US/docs/Web/API/XRViewerPose#examples) for example code. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) - [Movement, orientation, and motion](/en-US/docs/Web/API/WebXR_Device_API/Movement_and_motion)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlmediaelement/index.md
--- title: HTMLMediaElement slug: Web/API/HTMLMediaElement page-type: web-api-interface browser-compat: api.HTMLMediaElement --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement`** interface adds to {{domxref("HTMLElement")}} the properties and methods needed to support basic media-related capabilities that are common to audio and video. The {{domxref("HTMLVideoElement")}} and {{domxref("HTMLAudioElement")}} elements both inherit this interface. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its ancestors {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}}, and {{domxref("EventTarget")}}._ - {{domxref("HTMLMediaElement.audioTracks")}} - : An {{domxref("AudioTrackList")}} that lists the {{domxref("AudioTrack")}} objects contained in the element. - {{domxref("HTMLMediaElement.autoplay")}} - : A boolean value that reflects the [`autoplay`](/en-US/docs/Web/HTML/Element/video#autoplay) HTML attribute, indicating whether playback should automatically begin as soon as enough media is available to do so without interruption. > **Note:** Automatically playing audio when the user doesn't expect or desire it is a poor user experience and should be avoided in most cases, though there are exceptions. See the [Autoplay guide for media and Web Audio APIs](/en-US/docs/Web/Media/Autoplay_guide) for more information. Keep in mind that browsers may ignore autoplay requests, so you should ensure that your code isn't dependent on autoplay working. - {{domxref("HTMLMediaElement.buffered")}} {{ReadOnlyInline}} - : Returns a {{domxref("TimeRanges")}} object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the `buffered` property is accessed. - {{domxref("HTMLMediaElement.controls")}} - : A boolean that reflects the [`controls`](/en-US/docs/Web/HTML/Element/video#controls) HTML attribute, indicating whether user interface items for controlling the resource should be displayed. - {{domxref("HTMLMediaElement.controlsList")}} {{ReadOnlyInline}} - : Returns a {{domxref("DOMTokenList")}} that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The `DOMTokenList` takes one or more of three possible values: `nodownload`, `nofullscreen`, and `noremoteplayback`. - {{domxref("HTMLMediaElement.crossOrigin")}} - : A string indicating the [CORS setting](/en-US/docs/Web/HTML/Attributes/crossorigin) for this media element. - {{domxref("HTMLMediaElement.currentSrc")}} {{ReadOnlyInline}} - : Returns a string with the absolute URL of the chosen media resource. - {{domxref("HTMLMediaElement.currentTime")}} - : A double-precision floating-point value indicating the current playback time in seconds; if the media has not started to play and has not been seeked, this value is the media's initial playback time. Setting this value seeks the media to the new time. The time is specified relative to the media's timeline. - {{domxref("HTMLMediaElement.defaultMuted")}} - : A boolean that reflects the [`muted`](/en-US/docs/Web/HTML/Element/video#muted) HTML attribute, which indicates whether the media element's audio output should be muted by default. - {{domxref("HTMLMediaElement.defaultPlaybackRate")}} - : A `double` indicating the default playback rate for the media. - {{domxref("HTMLMediaElement.disableRemotePlayback")}} - : A boolean that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI. - {{domxref("HTMLMediaElement.duration")}} {{ReadOnlyInline}} - : A read-only double-precision floating-point value indicating the total duration of the media in seconds. If no media data is available, the returned value is `NaN`. If the media is of indefinite length (such as streamed live media, a WebRTC call's media, or similar), the value is `+Infinity`. - {{domxref("HTMLMediaElement.ended")}} {{ReadOnlyInline}} - : Returns a boolean that indicates whether the media element has finished playing. - {{domxref("HTMLMediaElement.error")}} {{ReadOnlyInline}} - : Returns a {{domxref("MediaError")}} object for the most recent error, or `null` if there has not been an error. - {{domxref("HTMLMediaElement.loop")}} - : A boolean that reflects the [`loop`](/en-US/docs/Web/HTML/Element/video#loop) HTML attribute, which indicates whether the media element should start over when it reaches the end. - {{domxref("HTMLMediaElement.mediaKeys")}} {{ReadOnlyInline}} - : Returns a {{domxref("MediaKeys")}} object, that is a set of keys that the element can use for decryption of media data during playback. If no key is available, it can be `null`. - {{domxref("HTMLMediaElement.muted")}} - : A boolean that determines whether audio is muted. `true` if the audio is muted and `false` otherwise. - {{domxref("HTMLMediaElement.networkState")}} {{ReadOnlyInline}} - : Returns a `unsigned short` (enumeration) indicating the current state of fetching the media over the network. - {{domxref("HTMLMediaElement.paused")}} {{ReadOnlyInline}} - : Returns a boolean that indicates whether the media element is paused. - {{domxref("HTMLMediaElement.playbackRate")}} - : A `double` that indicates the rate at which the media is being played back. - {{domxref("HTMLMediaElement.played")}} {{ReadOnlyInline}} - : Returns a {{domxref('TimeRanges')}} object that contains the ranges of the media source that the browser has played, if any. - {{domxref("HTMLMediaElement.preload")}} - : A string that reflects the [`preload`](/en-US/docs/Web/HTML/Element/video#preload) HTML attribute, indicating what data should be preloaded, if any. Possible values are: `none`, `metadata`, `auto`. - {{domxref("HTMLMediaElement.preservesPitch")}} - : A boolean value that determines if the pitch of the sound will be preserved. If set to `false`, the pitch will adjust to the speed of the audio. - {{domxref("HTMLMediaElement.readyState")}} {{ReadOnlyInline}} - : Returns a `unsigned short` (enumeration) indicating the readiness state of the media. - {{domxref("HTMLMediaElement.remote")}} {{ReadOnlyInline}} - : Return a {{domxref("RemotePlayback")}} object instance associated with the media element. - {{domxref("HTMLMediaElement.seekable")}} {{ReadOnlyInline}} - : Returns a {{domxref('TimeRanges')}} object that contains the time ranges that the user is able to seek to, if any. - {{domxref("HTMLMediaElement.seeking")}} {{ReadOnlyInline}} - : Returns a boolean that indicates whether the media is in the process of seeking to a new position. - {{domxref("HTMLMediaElement.sinkId")}} {{ReadOnlyInline}} - : Returns a string that is the unique ID of the audio device delivering output, or an empty string if the user agent default audio device is being used. - {{domxref("HTMLMediaElement.src")}} - : A string that reflects the [`src`](/en-US/docs/Web/HTML/Element/video#src) HTML attribute, which contains the URL of a media resource to use. - {{domxref("HTMLMediaElement.srcObject")}} - : A {{domxref('MediaStream')}} representing the media to play or that has played in the current `HTMLMediaElement`, or `null` if not assigned. - {{domxref("HTMLMediaElement.textTracks")}} {{ReadOnlyInline}} - : Returns a {{domxref('TextTrackList')}} object containing the list of {{domxref("TextTrack")}} objects contained in the element. - {{domxref("HTMLMediaElement.videoTracks")}} {{ReadOnlyInline}} - : Returns a {{domxref('VideoTrackList')}} object containing the list of {{domxref("VideoTrack")}} objects contained in the element. - {{domxref("HTMLMediaElement.volume")}} - : A `double` indicating the audio volume, from 0.0 (silent) to 1.0 (loudest). ## Obsolete properties These properties are obsolete and should not be used, even if a browser still supports them. - {{domxref("HTMLMediaElement.controller")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : A {{domxref("MediaController")}} object that represents the media controller assigned to the element, or `null` if none is assigned. - {{domxref("HTMLMediaElement.mediaGroup")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : A string that reflects the [`mediagroup`](/en-US/docs/Web/HTML/Element/video#mediagroup) HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common {{domxref('MediaController')}}. - {{domxref("HTMLMediaElement.mozAudioCaptured")}} {{ReadOnlyInline}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Returns a boolean. Related to audio stream capture. - {{domxref("HTMLMediaElement.mozFragmentEnd")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : A `double` that provides access to the fragment end time if the media element has a fragment URI for `currentSrc`, otherwise it is equal to the media duration. ## Instance methods _This interface also inherits methods from its ancestors {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}}, and {{domxref("EventTarget")}}._ - {{domxref("HTMLMediaElement.addTextTrack()")}} - : Adds a new {{domxref("TextTrack")}} object (such as a track for subtitles) to a media element. This is a programmatic interface only and does not affect the DOM. - {{domxref("HTMLMediaElement.captureStream()")}} - : Returns {{domxref("MediaStream")}}, captures a stream of the media content. - {{domxref("HTMLMediaElement.canPlayType()")}} - : Given a string specifying a MIME media type (potentially with the [`codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter) included), `canPlayType()` returns the string `probably` if the media should be playable, `maybe` if there's not enough information to determine whether the media will play or not, or an empty string if the media cannot be played. - {{domxref("HTMLMediaElement.fastSeek()")}} - : Quickly seeks to the given time with low precision. - {{domxref("HTMLMediaElement.load()")}} - : Resets the media to the beginning and selects the best available source from the sources provided using the [`src`](/en-US/docs/Web/HTML/Element/video#src) attribute or the {{HTMLElement("source")}} element. - {{domxref("HTMLMediaElement.pause()")}} - : Pauses the media playback. - {{domxref("HTMLMediaElement.play()")}} - : Begins playback of the media. - {{domxref("HTMLMediaElement.seekToNextFrame()")}} {{Deprecated_Inline}} {{non-standard_inline}} - : Seeks to the next frame in the media. This non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering or other operations. - {{domxref("HTMLMediaElement.setMediaKeys()")}} - : Returns {{jsxref("Promise")}}. Sets the {{domxref("MediaKeys")}} keys to use when decrypting media during playback. - {{domxref("HTMLMediaElement.setSinkId()")}} - : Sets the ID of the audio device to use for output and returns a {{jsxref("Promise")}}. This only works when the application is authorized to use the specified device. ## Obsolete methods _These methods are obsolete and should not be used, even if a browser still supports them._ - {{domxref("HTMLMediaElement.mozCaptureStream()")}} {{Non-standard_Inline}} - : \[enter description] - {{domxref("HTMLMediaElement.mozCaptureStreamUntilEnded()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : \[enter description] - {{domxref("HTMLMediaElement.mozGetMetadata()")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Returns {{jsxref('Object')}}, which contains properties that represent metadata from the playing media resource as `{key: value}` pairs. A separate copy of the data is returned each time the method is called. This method must be called after the [`loadedmetadata`](/en-US/docs/Web/API/HTMLMediaElement/loadedmetadata_event) event fires. ## Events _Inherits events from its parent, {{domxref("HTMLElement")}}_. Listen to these events using {{domxref("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface. - {{domxref("HTMLMediaElement.abort_event", 'abort')}} - : Fired when the resource was not fully loaded, but not as the result of an error. - {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} - : Fired when the user agent can play the media, but estimates that **not** enough data has been loaded to play the media up to its end without having to stop for further buffering of content. - {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} - : Fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content. - {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} - : Fired when the duration property has been updated. - {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} - : Fired when the media has become empty; for example, when the media has already been loaded (or partially loaded), and the {{domxref("HTMLMediaElement.load()")}} method is called to reload it. - {{domxref("HTMLMediaElement.ended_event", 'ended')}} - : Fired when playback stops when end of the media (\<audio> or \<video>) is reached or because no further data is available. - {{domxref("HTMLMediaElement.error_event", 'error')}} - : Fired when the resource could not be loaded due to an error. - {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} - : Fired when the first frame of the media has finished loading. - {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} - : Fired when the metadata has been loaded. - {{domxref("HTMLMediaElement.loadstart_event", 'loadstart')}} - : Fired when the browser has started to load a resource. - {{domxref("HTMLMediaElement.pause_event", 'pause')}} - : Fired when a request to pause play is handled and the activity has entered its paused state, most commonly occurring when the media's {{domxref("HTMLMediaElement.pause()")}} method is called. - {{domxref("HTMLMediaElement.play_event", 'play')}} - : Fired when the `paused` property is changed from `true` to `false`, as a result of the {{domxref("HTMLMediaElement.play()")}} method, or the `autoplay` attribute. - {{domxref("HTMLMediaElement.playing_event", "playing")}} - : Fired when playback is ready to start after having been paused or delayed due to lack of data. - {{domxref("HTMLMediaElement.progress_event", "progress")}} - : Fired periodically as the browser loads a resource. - {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} - : Fired when the playback rate has changed. - {{domxref("HTMLMediaElement.resize_event", 'resize ')}} - : Fired when one or both of the `videoWidth` and `videoHeight` properties have just been updated. - {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} - : Fired when a seek operation completes. - {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} - : Fired when a seek operation begins. - {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} - : Fired when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. - {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} - : Fired when the media data loading has been suspended. - {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} - : Fired when the time indicated by the {{domxref("HTMLMediaElement.currentTime", "currentTime")}} property has been updated. - {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} - : Fired when the volume has changed. - {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} - : Fired when playback has stopped because of a temporary lack of data. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also ### References - {{HTMLElement("video")}} and {{HTMLElement("audio")}} HTML elements - {{domxref("HTMLVideoElement")}} and {{domxref("HTMLAudioElement")}} interfaces, derived from `HTMLMediaElement` ### Guides - [Web media technologies](/en-US/docs/Web/Media) - Learning area: [Video and audio content](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) - [Media type and format guide](/en-US/docs/Web/Media/Formats) - [Handling media support issues in web content](/en-US/docs/Web/Media/Formats/Support_issues)
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/pause_event/index.md
--- title: "HTMLMediaElement: pause event" short-title: pause slug: Web/API/HTMLMediaElement/pause_event page-type: web-api-event browser-compat: api.HTMLMediaElement.pause_event --- {{APIRef("HTMLMediaElement")}} The `pause` event is sent when a request to pause an activity is handled and the activity has entered its paused state, most commonly after the media has been paused through a call to the element's {{domxref("HTMLMediaElement.pause", "pause()")}} method. The event is sent once the `pause()` method returns and after the media element's {{domxref("HTMLMediaElement.paused", "paused")}} property has been changed to `true`. 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("pause", (event) => {}); onpause = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `pause` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("pause", (event) => { console.log( "The Boolean paused property is now 'true'. Either the pause() method was called or the autoplay attribute was toggled.", ); }); ``` Using the `onpause` event handler property: ```js const video = document.querySelector("video"); video.onpause = (event) => { console.log( "The Boolean paused property is now 'true'. Either the pause() method was called or the autoplay attribute was toggled.", ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}} - {{domxref("SpeechSynthesisUtterance")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/seekable/index.md
--- title: "HTMLMediaElement: seekable property" short-title: seekable slug: Web/API/HTMLMediaElement/seekable page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.seekable --- {{APIRef("HTML DOM")}} The **`seekable`** read-only property of {{domxref("HTMLMediaElement")}} objects returns a new static [normalized `TimeRanges` object](/en-US/docs/Web/API/TimeRanges#normalized_timeranges_objects) that represents the ranges of the media resource, if any, that the user agent is able to seek to at the time `seekable` property is accessed. ## Value A new static [normalized TimeRanges object](/en-US/docs/Web/API/TimeRanges#normalized_timeranges_objects) that represents the ranges of the media resource, if any, that the user agent is able to seek to at the time `seekable` property is accessed. ## Examples ```js const video = document.querySelector("video"); const timeRangesObject = video.seekable; const timeRanges = []; //Go through the object and output an array for (let count = 0; count < timeRangesObject.length; count++) { timeRanges.push([timeRangesObject.start(count), timeRangesObject.end(count)]); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.seekable` property - [Media Source API](/en-US/docs/Web/API/Media_Source_Extensions_API) - [Media buffering, seeking, and time ranges](/en-US/docs/Web/Media/Audio_and_video_delivery/buffering_seeking_time_ranges)
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/stalled_event/index.md
--- title: "HTMLMediaElement: stalled event" short-title: stalled slug: Web/API/HTMLMediaElement/stalled_event page-type: web-api-event browser-compat: api.HTMLMediaElement.stalled_event --- {{APIRef("HTMLMediaElement")}} The `stalled` event is fired when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. 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("stalled", (event) => {}); onstalled = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `stalled` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("stalled", (event) => { console.log("Failed to fetch data, but trying."); }); ``` Using the `onstalled` event handler property: ```js const video = document.querySelector("video"); video.onstalled = (event) => { console.log("Failed to fetch data, but trying."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/currenttime/index.md
--- title: "HTMLMediaElement: currentTime property" short-title: currentTime slug: Web/API/HTMLMediaElement/currentTime page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.currentTime --- {{APIRef("HTML DOM")}} The {{domxref("HTMLMediaElement")}} interface's **`currentTime`** property specifies the current playback time in seconds. Changing the value of `currentTime` seeks the media to the new time. ## Value A double-precision floating-point value indicating the current playback time in seconds. If the media is not yet playing, the value of `currentTime` indicates the time position within the media at which playback will begin once the {{domxref("HTMLMediaElement.play", "play()")}} method is called. Setting `currentTime` to a new value seeks the media to the given time, if the media is available. For media without a known duration—such as media being streamed live—it's possible that the browser may not be able to obtain parts of the media that have expired from the media buffer. Also, media whose timeline doesn't begin at 0 seconds cannot be seeked to a time before its timeline's earliest time. The length of the media in seconds can be determined using the {{domxref("HTMLMediaElement.duration", "duration")}} property. ## Examples ```js const video = document.createElement("video"); console.log(video.currentTime); ``` ## Usage notes ### Reduced time precision To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting), browsers may round or otherwise adjust the value returned by `currentTime`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.currentTime` property - {{domxref("HTMLMediaElement.fastSeek()")}}: Another way to set the time - {{domxref("HTMLMediaElement.duration")}}: The duration of the media in seconds
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/crossorigin/index.md
--- title: "HTMLMediaElement: crossOrigin property" short-title: crossOrigin slug: Web/API/HTMLMediaElement/crossOrigin page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.crossOrigin --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.crossOrigin`** property is the CORS setting for this media element. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for details. ## Value A string of a keyword specifying the CORS mode to use when fetching the resource. Possible values are: - `anonymous` or the empty string (`""`) - : Requests sent by the {{domxref("HTMLMediaElement")}} will use the `cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `same-origin` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode. This means that CORS is enabled and credentials are sent _if_ the resource is fetched from the same origin from which the document was loaded. - `use-credentials` - : Requests sent by the {{domxref("HTMLMediaElement")}} will use the `cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `include` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode. All resources requests by the element will use CORS, regardless of what domain the fetch is from. If the `crossOrigin` property is specified with any other value, it is the same as specifing as the `anonymous`. If the `crossOrigin` property is not specified, the resource is fetched without CORS (the `no-cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `same-origin` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLImageElement.crossOrigin")}} - {{domxref("HTMLLinkElement.crossOrigin")}} - {{domxref("HTMLScriptElement.crossOrigin")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/defaultplaybackrate/index.md
--- title: "HTMLMediaElement: defaultPlaybackRate property" short-title: defaultPlaybackRate slug: Web/API/HTMLMediaElement/defaultPlaybackRate page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.defaultPlaybackRate --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.defaultPlaybackRate`** property indicates the default playback rate for the media. ## Value A double. `1.0` is "normal speed," values lower than `1.0` make the media play slower than normal, higher values make it play faster. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the specified value is not supported. ## Examples ```js const obj = document.createElement("video"); console.log(obj.defaultPlaybackRate); // 1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.defaultPlaybackRate` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/canplay_event/index.md
--- title: "HTMLMediaElement: canplay event" short-title: canplay slug: Web/API/HTMLMediaElement/canplay_event page-type: web-api-event browser-compat: api.HTMLMediaElement.canplay_event --- {{APIRef("HTMLMediaElement")}} The `canplay` event is fired when the user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. 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("canplay", (event) => {}); oncanplay = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `canplay` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("canplay", (event) => { console.log("Video can start, but not sure it will play through."); }); ``` Using the `oncanplay` event handler property: ```js const video = document.querySelector("video"); video.oncanplay = (event) => { console.log("Video can start, but not sure it will play through."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/emptied_event/index.md
--- title: "HTMLMediaElement: emptied event" short-title: emptied slug: Web/API/HTMLMediaElement/emptied_event page-type: web-api-event browser-compat: api.HTMLMediaElement.emptied_event --- {{APIRef("HTMLMediaElement")}} The `emptied` event is fired when the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the `load()` method is called to reload it. 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("emptied", (event) => {}); onemptied = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `emptied` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("emptied", (event) => { console.log("Uh oh. The media is empty. Did you call load()?"); }); ``` Using the `onemptied` event handler property: ```js const video = document.querySelector("video"); video.onemptied = (event) => { console.log("Uh oh. The media is empty. Did you call load()?"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/timeupdate_event/index.md
--- title: "HTMLMediaElement: timeupdate event" short-title: timeupdate slug: Web/API/HTMLMediaElement/timeupdate_event page-type: web-api-event browser-compat: api.HTMLMediaElement.timeupdate_event --- {{APIRef("HTMLMediaElement")}} The `timeupdate` event is fired when the time indicated by the `currentTime` attribute has been updated. The event frequency is dependent on the system load, but will be thrown between about 4Hz and 66Hz (assuming the event handlers don't take longer than 250ms to run). User agents are encouraged to vary the frequency of the event based on the system load and the average cost of processing the event each time, so that the UI updates are not any more frequent than the user agent can comfortably handle while decoding the video. 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("timeupdate", (event) => {}); ontimeupdate = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `timeupdate` event, then post a message when that event handler has reacted to the event firing. Remember, the event frequency is dependent on the system load. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("timeupdate", (event) => { console.log("The currentTime attribute has been updated. Again."); }); ``` Using the `ontimeupdate` event handler property: ```js const video = document.querySelector("video"); video.ontimeupdate = (event) => { console.log("The currentTime attribute has been updated. Again."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/capturestream/index.md
--- title: "HTMLMediaElement: captureStream() method" short-title: captureStream() slug: Web/API/HTMLMediaElement/captureStream page-type: web-api-instance-method browser-compat: api.HTMLMediaElement.captureStream --- {{APIRef("Media Capture and Streams")}} The **`captureStream()`** method of the {{domxref("HTMLMediaElement")}} interface returns a {{domxref('MediaStream')}} object which is streaming a real-time capture of the content being rendered in the media element. This can be used, for example, as a source for a [WebRTC](/en-US/docs/Web/API/WebRTC_API) {{domxref("RTCPeerConnection")}}. ## Syntax ```js-nolint captureStream() ``` ### Parameters None. ### Return value A {{domxref('MediaStream')}} object which can be used as a source for audio and/or video data by other media processing code, or as a source for [WebRTC](/en-US/docs/Glossary/WebRTC). ## Examples In this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the ID `"playback"` into a {{domxref("MediaStream")}}. The stream can then be used for other purposes—like a source for streaming over WebRTC, to allow sharing prerecorded videos with another person during a video call. ```js document.querySelector(".playAndRecord").addEventListener("click", () => { const playbackElement = document.getElementById("playback"); const captureStream = playbackElement.captureStream(); playbackElement.play(); }); ``` See [Recording a media element](/en-US/docs/Web/API/MediaStream_Recording_API/Recording_a_media_element) for a longer and more intricate example and explanation. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### Firefox-specific notes Prior to Firefox 51, you couldn't use `captureStream()` on a media element whose source is, itself, a {{domxref("MediaStream")}} (like a {{HTMLElement("video")}} element which is presenting a stream being received over a {{domxref("RTCPeerConnection")}}). Beginning in Firefox 51, this works. This means you can capture a stream from the video element and use {{domxref("MediaRecorder")}} to record it. See [Firefox bug 1259788](https://bugzil.la/1259788) for details. However, `captureStream()` is still prefixed as `mozCaptureStream()` on Firefox for good reason: there are some quirks in the present implementation which are worth noting: - The Firefox implementation currently only works as described in the specification when the media element's source is, itself, a {{domxref("MediaStream")}}. - If the media element's source isn't a `MediaStream`, the output from this method isn't compatible with the spec, and if you change the source after starting capture, the output capture stream can't accept the new source data due to that incompatibility, so no {{domxref("MediaStreamTrack")}}s from the new source `MediaStream` are added to the captured stream, resulting in output that doesn't capture the updated source. - Switching the source back to a `MediaStream` adds tracks back to the stream and it works again as expected. - Calling `mozCaptureMediaStream()` on an element with a `MediaStream` source returns a stream that only contains tracks while the element is playing a `MediaStream`. - If you call `mozCaptureMediaStream()` on a media element with no source media, its compatibility mode will be based on the first source that's added; for example, if it's a `MediaStream`, then the capture stream will only work with MediaStream sources from then on. - This special behavior will be removed once the non-`MediaStream` source support is brought up to specification and the method is unprefixed. See [Firefox bug 1259788](https://bugzil.la/1259788) for details. ## See also - [Recording a media element](/en-US/docs/Web/API/MediaStream_Recording_API/Recording_a_media_element) - [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API) - {{domxref("HTMLCanvasElement.captureStream()")}} - {{domxref("MediaStream")}} - [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/controls/index.md
--- title: "HTMLMediaElement: controls property" short-title: controls slug: Web/API/HTMLMediaElement/controls page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.controls --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.controls`** property reflects the [`controls`](/en-US/docs/Web/HTML/Element/video#controls) HTML attribute, which controls whether user interface controls for playing the media item will be displayed. ## Value A boolean value. A value of `true` means controls will be displayed. ## Examples ```js const obj = document.createElement("video"); obj.controls = true; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.controls` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/playbackrate/index.md
--- title: "HTMLMediaElement: playbackRate property" short-title: playbackRate slug: Web/API/HTMLMediaElement/playbackRate page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.playbackRate --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.playbackRate`** property sets the rate at which the media is being played back. This is used to implement user controls for fast forward, slow motion, and so forth. The normal playback rate is multiplied by this value to obtain the current rate, so a value of 1.0 indicates normal speed. If `playbackRate` is negative, the media is played backwards. The audio is muted when the fast forward or slow motion is outside a useful range (for example, Gecko mutes the sound outside the range `0.25` to `4.0`). The pitch of the audio is corrected by default. You can disable pitch correction using the {{domxref("HTMLMediaElement.preservesPitch")}} property. ## Value A [`double`](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). `1.0` is "normal speed," values lower than `1.0` make the media play slower than normal, higher values make it play faster. (**Default:** `1.0`) ## Examples ```js const obj = document.createElement("video"); console.log(obj.playbackRate); // Expected Output: 1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.playbackRate` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/autoplay/index.md
--- title: "HTMLMediaElement: autoplay property" short-title: autoplay slug: Web/API/HTMLMediaElement/autoplay page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.autoplay --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.autoplay`** property reflects the [`autoplay`](/en-US/docs/Web/HTML/Element/video#autoplay) HTML attribute, indicating whether playback should automatically begin as soon as enough media is available to do so without interruption. A media element whose source is a {{domxref("MediaStream")}} and whose `autoplay` property is `true` will begin playback when it becomes active (that is, when {{domxref("MediaStream.active")}} becomes `true`). > **Note:** Sites which automatically play audio (or videos with an audio > track) can be an unpleasant experience for users, so it should be avoided when > possible. If you must offer autoplay functionality, you should make it opt-in > (requiring a user to specifically enable it). However, autoplay can be useful when > creating media elements whose source will be set at a later time, under user control. For a much more in-depth look at autoplay, autoplay blocking, and how to respond when autoplay is blocked by the user's browser, see our article [Autoplay guide for media and Web Audio APIs](/en-US/docs/Web/Media/Autoplay_guide). ## Value A boolean value which is `true` if the media element will begin playback as soon as enough content has loaded to allow it to do so without interruption. > **Note:** Some browsers offer users the ability to override > `autoplay` in order to prevent disruptive audio or video from playing > without permission or in the background. Do not rely on `autoplay` actually > starting playback and instead use {{domxref("HTMLMediaElement.play_event", 'play')}} > event. ## Examples ```html <video id="video" controls> <source src="https://player.vimeo.com/external/250688977.sd.mp4?s=d14b1f1a971dde13c79d6e436b88a6a928dfe26b&profile_id=165" /> </video> ``` ```js // Disable autoplay (recommended) // false is the default value document.querySelector("#video").autoplay = false; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.autoplay` property - {{HTMLElement("audio")}}, {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/networkstate/index.md
--- title: "HTMLMediaElement: networkState property" short-title: networkState slug: Web/API/HTMLMediaElement/networkState page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.networkState --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.networkState`** property indicates the current state of the fetching of media over the network. ## Value An `unsigned short`. Possible values are: | Constant | Value | Description | | ------------------- | ----- | ------------------------------------------------------------------------------------- | | `NETWORK_EMPTY` | 0 | There is no data yet. Also, `readyState` is `HAVE_NOTHING`. | | `NETWORK_IDLE` | 1 | HTMLMediaElement is active and has selected a resource, but is not using the network. | | `NETWORK_LOADING` | 2 | The browser is downloading HTMLMediaElement data. | | `NETWORK_NO_SOURCE` | 3 | No HTMLMediaElement src found. | ## Examples This example will listen for the audio element to begin playing and then check if it is still loading data. ```html <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> ``` ```js const obj = document.getElementById("example"); obj.addEventListener("playing", () => { if (obj.networkState === 2) { // Still loading… } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.networkState` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/volume/index.md
--- title: "HTMLMediaElement: volume property" short-title: volume slug: Web/API/HTMLMediaElement/volume page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.volume --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.volume`** property sets the volume at which the media will be played. ## Value A double values must fall between 0 and 1, where 0 is effectively muted and 1 is the loudest possible value. ## Examples ```js const obj = document.createElement("audio"); console.log(obj.volume); // 1 obj.volume = 0.75; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.volume` property - {{domxref("HTMLMediaElement.muted")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/loadedmetadata_event/index.md
--- title: "HTMLMediaElement: loadedmetadata event" short-title: loadedmetadata slug: Web/API/HTMLMediaElement/loadedmetadata_event page-type: web-api-event browser-compat: api.HTMLMediaElement.loadedmetadata_event --- {{APIRef("HTMLMediaElement")}} The `loadedmetadata` event is fired when the metadata has been loaded. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("loadedmetadata", (event) => {}); onloadedmetadata = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `loadedmetadata` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("loadedmetadata", (event) => { console.log( "The duration and dimensions of the media and tracks are now known.", ); }); ``` Using the `onloadedmetadata` event handler property: ```js const video = document.querySelector("video"); video.onloadedmetadata = (event) => { console.log( "The duration and dimensions of the media and tracks are now known.", ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/texttracks/index.md
--- title: "HTMLMediaElement: textTracks property" short-title: textTracks slug: Web/API/HTMLMediaElement/textTracks page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.textTracks --- {{APIRef("HTML DOM")}} The read-only **`textTracks`** property on {{DOMxRef("HTMLMediaElement")}} objects returns a {{DOMxRef("TextTrackList")}} object listing all of the {{DOMxRef("TextTrack")}} objects representing the media element's text tracks, in the same order as in the list of text tracks. You can detect when tracks are added to and removed from an [`<audio>`](/en-US/docs/Web/HTML/Element/audio) or [`<video>`](/en-US/docs/Web/HTML/Element/video) element using the `addtrack` and `removetrack` events. However, these events aren't sent directly to the media element itself. Instead, they're sent to the track list object of the [`HTMLMediaElement`](/en-US/docs/Web/API/HTMLMediaElement) that corresponds to the type of track that was added to the element The returned list is _live_; that is, as tracks are added to and removed from the media element, the list's contents change dynamically. Once you have a reference to the list, you can monitor it for changes to detect when new text tracks are added or existing ones removed. See [TextTrackList events](/en-US/docs/Web/API/TextTrackList#events) to learn more about watching for changes to a media element's track list. ## Value A {{DOMxRef("TextTrackList")}} object representing the list of text tracks included in the media element. The list of tracks can be accessed using `textTracks[n]` to get the n-th text track from the object's list of text tracks, or using the `textTracks`.[`getTrackById()`](/en-US/docs/Web/API/TextTrackList/getTrackById) method. Each track is represented by a {{DOMxRef("TextTrack")}} object which provides information about the track. ## Examples We start with a [`<video>`](/en-US/docs/Web/HTML/Element/video) that has several [`<track>`](/en-US/docs/Web/HTML/Element/track) children ```html <video controls poster="/images/sample.gif"> <source src="sample.mp4" type="video/mp4" /> <source src="sample.ogv" type="video/ogv" /> <track kind="captions" src="sampleCaptions.vtt" srclang="en" /> <track kind="descriptions" src="sampleDescriptions.vtt" srclang="en" /> <track kind="chapters" src="sampleChapters.vtt" srclang="en" /> <track kind="subtitles" src="sampleSubtitles_de.vtt" srclang="de" /> <track kind="subtitles" src="sampleSubtitles_en.vtt" srclang="en" /> <track kind="subtitles" src="sampleSubtitles_ja.vtt" srclang="ja" /> <track kind="subtitles" src="sampleSubtitles_oz.vtt" srclang="oz" /> <track kind="metadata" src="keyStage1.vtt" srclang="en" label="Key Stage 1" /> <track kind="metadata" src="keyStage2.vtt" srclang="en" label="Key Stage 2" /> <track kind="metadata" src="keyStage3.vtt" srclang="en" label="Key Stage 3" /> </video> ``` The `HTMLMediaElement.textTracks` returns a `textTracksList` through which we can iterate. Here we print all the properties of each English track to the console. ```js const tracks = document.querySelector("video").textTracks; for (const track of tracks) { if (track.language === "en") { console.dir(track); } } ``` {{EmbedLiveSample("Examples", "100%", 155)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.textTracks` property - {{HTMLElement("audio")}}, {{HTMLElement("video")}} - {{DOMxRef("AudioTrack")}}, {{DOMxRef("AudioTrackList")}} - {{DOMxRef("VideoTrack")}}, {{DOMxRef("VideoTrackList")}} - [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_event), [`change`](/en-US/docs/Web/API/VideoTrackList/change_event), [`removetrack`](/en-US/docs/Web/API/VideoTrackList/removetrack_event): AudioTrackList events - [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_event), [`change`](/en-US/docs/Web/API/VideoTrackList/change_event), [`removetrack`](/en-US/docs/Web/API/VideoTrackList/removetrack_event): VideoTrackList events
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/muted/index.md
--- title: "HTMLMediaElement: muted property" short-title: muted slug: Web/API/HTMLMediaElement/muted page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.muted --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.muted`** property indicates whether the media element is muted. ## Value A boolean value. `true` means muted and `false` means not muted. ## Examples ```js const obj = document.createElement("video"); console.log(obj.muted); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.muted` property - {{domxref("HTMLMediaElement.defaultMuted")}} - {{domxref("HTMLMediaElement.volume")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/play_event/index.md
--- title: "HTMLMediaElement: play event" short-title: play slug: Web/API/HTMLMediaElement/play_event page-type: web-api-event browser-compat: api.HTMLMediaElement.play_event --- {{APIRef("HTMLMediaElement")}} The `play` event is fired when the `paused` property is changed from `true` to `false`, as a result of the `play` method, or the `autoplay` attribute. 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("play", (event) => {}); onplay = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `play` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("play", (event) => { console.log( "The Boolean paused property is now 'false'. Either the play() method was called or the autoplay attribute was toggled.", ); }); ``` Using the `onplay` event handler property: ```js const video = document.querySelector("video"); video.onplay = (event) => { console.log( "The Boolean paused property is now 'false'. Either the play() method was called or the autoplay attribute was toggled.", ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/disableremoteplayback/index.md
--- title: "HTMLMediaElement: disableRemotePlayback property" short-title: disableRemotePlayback slug: Web/API/HTMLMediaElement/disableRemotePlayback page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.disableRemotePlayback --- {{APIRef("Remote Playback API")}} The **`disableRemotePlayback`** property of the {{domxref("HTMLMediaElement")}} interface determines whether the media element is allowed to have a remote playback UI. ## Value A boolean value indicating whether the media element may have a remote playback UI. (false means "not disabled", which means "enabled") ## Example ```js const obj = document.createElement("audio"); obj.disableRemotePlayback = true; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/fastseek/index.md
--- title: "HTMLMediaElement: fastSeek() method" short-title: fastSeek() slug: Web/API/HTMLMediaElement/fastSeek page-type: web-api-instance-method browser-compat: api.HTMLMediaElement.fastSeek --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.fastSeek()`** method quickly seeks the media to the new time with precision tradeoff. > **Note:** If you need to seek with precision, you should set [`HTMLMediaElement.currentTime`](/en-US/docs/Web/API/HTMLMediaElement/currentTime) > instead. ## Syntax ```js-nolint fastSeek(time) ``` ### Parameters - `time` - : A double. ### Return value None ({{jsxref("undefined")}}). ## Examples This example quickly seeks to 20-second position of the video element. ```js let myVideo = document.getElementById("myVideoElement"); myVideo.fastSeek(20); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTMLMediaElement.currentTime](/en-US/docs/Web/API/HTMLMediaElement/currentTime) for seeking without precision tradeoff
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/loadeddata_event/index.md
--- title: "HTMLMediaElement: loadeddata event" short-title: loadeddata slug: Web/API/HTMLMediaElement/loadeddata_event page-type: web-api-event browser-compat: api.HTMLMediaElement.loadeddata_event --- {{APIRef("HTMLMediaElement")}} The **`loadeddata`** event is fired when the frame at the current playback position of the media has finished loading; often the first frame. > **Note:** This event will not fire in mobile/tablet devices if data-saver is on in browser settings. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("loadeddata", (event) => {}); onloadeddata = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `loadeddata` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("loadeddata", (event) => { console.log( "Yay! The readyState just increased to " + "HAVE_CURRENT_DATA or greater for the first time.", ); }); ``` Using the `onloadeddata` event handler property: ```js const video = document.querySelector("video"); video.onloadeddata = (event) => { console.log( "Yay! The readyState just increased to " + "HAVE_CURRENT_DATA or greater for the first time.", ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/buffered/index.md
--- title: "HTMLMediaElement: buffered property" short-title: buffered slug: Web/API/HTMLMediaElement/buffered page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.buffered --- {{APIRef("HTML DOM")}} The **`buffered`** read-only property of {{domxref("HTMLMediaElement")}} objects returns a new static [normalized `TimeRanges` object](/en-US/docs/Web/API/TimeRanges#normalized_timeranges_objects) that represents the ranges of the media resource, if any, that the user agent has buffered at the moment the `buffered` property is accessed. ## Value A new static [normalized TimeRanges object](/en-US/docs/Web/API/TimeRanges#normalized_timeranges_objects) that represents the ranges of the media resource, if any, that the user agent has buffered at the moment the `buffered` property is accessed. ## Examples ```js const obj = document.createElement("video"); console.log(obj.buffered); // TimeRanges { length: 0 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.buffered` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/preservespitch/index.md
--- title: "HTMLMediaElement: preservesPitch property" short-title: preservesPitch slug: Web/API/HTMLMediaElement/preservesPitch page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.preservesPitch --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.preservesPitch`** property determines whether or not the browser should adjust the pitch of the audio to compensate for changes to the playback rate made by setting {{domxref("HTMLMediaElement.playbackRate")}}. ## Value A boolean value defaulting to `true`. ## Examples ### Setting the preservesPitch property In this example, we have an {{HTMLElement("audio")}} element, a range control that adjusts the playback rate, and a checkbox that sets `preservesPitch`. Try playing the audio, then adjusting the playback rate, then enabling and disabling the checkbox. ```html <audio controls src="https://mdn.github.io/webaudio-examples/audio-basics/outfoxing.mp3"></audio> <div> <label for="rate">Adjust playback rate:</label> <input id="rate" type="range" min="0.25" max="3" step="0.05" value="1" /> </div> <div> <label for="pitch">Preserve pitch:</label> <input type="checkbox" id="pitch" name="pitch" checked /> </div> ``` ```css hidden div { margin: 0.5rem 0; } ``` ```js const audio = document.querySelector("audio"); document.getElementById("rate").addEventListener("change", (e) => { audio.playbackRate = e.target.value; }); document.getElementById("pitch").addEventListener("change", (e) => { audio.preservesPitch = e.target.checked; }); ``` {{EmbedLiveSample("Setting the preservesPitch property")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement.playbackRate")}} - [Web Audio playbackRate explained](/en-US/docs/Web/Media/Audio_and_video_delivery/WebAudio_playbackRate_explained)
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/controller/index.md
--- title: "HTMLMediaElement: controller property" short-title: controller slug: Web/API/HTMLMediaElement/controller page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.HTMLMediaElement.controller --- {{APIRef("HTML DOM")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`HTMLMediaElement.controller`** property represents the media controller assigned to the element. ## Value A `MediaController` object or `null` if no media controller is assigned to the element. The default is `null`. ## Specifications In 2016, the whole Media Controller feature was [removed from the HTML specification](https://github.com/w3c/html/issues/246). It is no longer on track to become a standard. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/defaultmuted/index.md
--- title: "HTMLMediaElement: defaultMuted property" short-title: defaultMuted slug: Web/API/HTMLMediaElement/defaultMuted page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.defaultMuted --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.defaultMuted`** property reflects the [`muted`](/en-US/docs/Web/HTML/Element/video#muted) HTML attribute, which indicates whether the media element's audio output should be muted by default. This property has no dynamic effect. To mute and unmute the audio output, use the {{domxref("HTMLMediaElement.muted", "muted")}} property. ## Value A boolean value. A value of `true` means that the audio output will be muted by default. ## Examples ```js const videoEle = document.createElement("video"); videoEle.defaultMuted = true; console.log(videoEle.outerHTML); // <video muted=""></video> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.defaultMuted` property - {{domxref("HTMLMediaElement.muted")}} - {{domxref("HTMLMediaElement.volume")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/suspend_event/index.md
--- title: "HTMLMediaElement: suspend event" short-title: suspend slug: Web/API/HTMLMediaElement/suspend_event page-type: web-api-event browser-compat: api.HTMLMediaElement.suspend_event --- {{APIRef("HTMLMediaElement")}} The `suspend` event is fired when media data loading has been suspended. 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("suspend", (event) => {}); onsuspend = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `suspend` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("suspend", (event) => { console.log("Data loading has been suspended."); }); ``` Using the `onsuspend` event handler property: ```js const video = document.querySelector("video"); video.onsuspend = (event) => { console.log("Data loading has been suspended."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}} - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/controlslist/index.md
--- title: "HTMLMediaElement: controlsList property" short-title: controlsList slug: Web/API/HTMLMediaElement/controlsList page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.controlsList --- {{APIRef("HTML DOM")}} The **`controlsList`** property of the {{domxref("HTMLMediaElement")}} interface returns a DOMTokenList that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The DOMTokenList takes one or more of three possible values: `nodownload`, `nofullscreen`, and `noremoteplayback`. ## Value A {{domxref("DOMTokenList")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Chrome HTMLMediaElement controlsList Sample](https://googlechrome.github.io/samples/media/controlslist.html)
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/abort_event/index.md
--- title: "HTMLMediaElement: abort event" short-title: abort slug: Web/API/HTMLMediaElement/abort_event page-type: web-api-event browser-compat: api.HTMLMediaElement.abort_event --- {{APIRef}} The **`abort`** event is fired when the resource was not fully loaded, but not as the result of an error. 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("abort", (event) => {}); onabort = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js const video = document.querySelector("video"); const videoSrc = "https://example.org/path/to/video.webm"; video.addEventListener("abort", () => { console.log(`Abort loading: ${videoSrc}`); }); const source = document.createElement("source"); source.setAttribute("src", videoSrc); source.setAttribute("type", "video/webm"); video.appendChild(source); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/pause/index.md
--- title: "HTMLMediaElement: pause() method" short-title: pause() slug: Web/API/HTMLMediaElement/pause page-type: web-api-instance-method browser-compat: api.HTMLMediaElement.pause --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.pause()`** method will pause playback of the media, if the media is already in a paused state this method will have no effect. ## Syntax ```js-nolint pause() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions None. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/waiting_event/index.md
--- title: "HTMLMediaElement: waiting event" short-title: waiting slug: Web/API/HTMLMediaElement/waiting_event page-type: web-api-event browser-compat: api.HTMLMediaElement.waiting_event --- {{APIRef("HTMLMediaElement")}} The `waiting` event is fired when playback has stopped because of a temporary lack of data. 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("waiting", (event) => {}); onwaiting = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `waiting` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("waiting", (event) => { console.log("Video is waiting for more data."); }); ``` Using the `onwaiting` event handler property: ```js const video = document.querySelector("video"); video.onwaiting = (event) => { console.log("Video is waiting for more data."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/error/index.md
--- title: "HTMLMediaElement: error property" short-title: error slug: Web/API/HTMLMediaElement/error page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.error --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.error`** property is the {{domxref("MediaError")}} object for the most recent error, or `null` if there has not been an error. When an {{domxref("HTMLMediaElement/error_event", "error")}} event is received by the element, you can determine details about what happened by examining this object. ## Value A {{domxref("MediaError")}} object describing the most recent error to occur on the media element or `null` if no errors have occurred. ## Examples This example establishes a video element and adds an error handler to it; the error handler logs the details to console. ```js const videoElement = document.createElement("video"); videoElement.onerror = () => { console.error( `Error ${videoElement.error.code}; details: ${videoElement.error.message}`, ); }; videoElement.src = "https://example.com/bogusvideo.mp4"; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.error` property - {{HTMLElement("audio")}} and {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/audiotracks/index.md
--- title: "HTMLMediaElement: audioTracks property" short-title: audioTracks slug: Web/API/HTMLMediaElement/audioTracks page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.audioTracks --- {{APIRef("HTML DOM")}} The read-only **`audioTracks`** property on {{domxref("HTMLMediaElement")}} objects returns an {{domxref("AudioTrackList")}} object listing all of the {{domxref("AudioTrack")}} objects representing the media element's audio tracks. The media element may be either an {{HTMLElement("audio")}} element or a {{HTMLElement("video")}} element. The returned list is _live_; that is, as tracks are added to and removed from the media element, the list's contents change dynamically. Once you have a reference to the list, you can monitor it for changes to detect when new audio tracks are added or existing ones removed. See [AudioTrackList events](/en-US/docs/Web/API/AudioTrackList#events) to learn more about watching for changes to a media element's track list. ## Value An {{domxref("AudioTrackList")}} object representing the list of audio tracks included in the media element. The list of tracks can be accessed using array notation, or using the object's {{domxref("AudioTrackList.getTrackById", "getTrackById()")}} method. Each track is represented by an {{domxref("AudioTrack")}} object which provides information about the track. ## Examples In this example, all of the audio tracks on a given element are muted. ### HTML The HTML establishes the element itself. ```html <video id="video" src="somevideo.mp4"></video> ``` ### JavaScript The JavaScript code handles muting the video element's audio tracks. ```js const video = document.getElementById("video"); for (let i = 0; i < video.audioTracks.length; i += 1) { video.audioTracks[i].enabled = false; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.audioTracks` property - {{HTMLElement("audio")}}, {{HTMLElement("video")}} - {{domxref("AudioTrack")}}, {{domxref("AudioTrackList")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/canplaytype/index.md
--- title: "HTMLMediaElement: canPlayType() method" short-title: canPlayType() slug: Web/API/HTMLMediaElement/canPlayType page-type: web-api-instance-method browser-compat: api.HTMLMediaElement.canPlayType --- {{APIRef("HTML DOM")}} The {{domxref("HTMLMediaElement")}} method **`canPlayType()`** reports how likely it is that the current browser will be able to play media of a given MIME type. ## Syntax ```js-nolint canPlayType(type) ``` ### Parameters - `type` - : A string specifying the MIME type of the media and (optionally) a [`codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter) containing a comma-separated list of the supported codecs. ### Return value A string indicating how likely it is that the media can be played. The string will be one of the following values: - `""` (empty string) - : The media cannot be played on the current device. - `probably` - : The media is probably playable on this device. - `maybe` - : There is not enough information to determine whether the media can play (until playback is actually attempted). ## Examples ```js let obj = document.createElement("video"); console.log(obj.canPlayType("video/mp4")); // "maybe" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.canPlayType()` method - {{domxref("MediaCapabilities")}} - [Handling media support issues in web content](/en-US/docs/Web/Media/Formats/Support_issues) - [Media type and format guide](/en-US/docs/Web/Media/Formats) - [Codecs in common media types](/en-US/docs/Web/Media/Formats/codecs_parameter)
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/mediagroup/index.md
--- title: "HTMLMediaElement: mediaGroup property" short-title: mediaGroup slug: Web/API/HTMLMediaElement/mediaGroup page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.HTMLMediaElement.mediaGroup --- {{APIRef("HTML DOM")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`HTMLMediaElement.mediaGroup`** property reflects the [`mediaGroup`](/en-US/docs/Web/HTML/Element/video#mediagroup) HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common `controller`. ## Value A string. ## Specifications In 2016, the whole Media Controller feature was [removed from the HTML specification](https://github.com/w3c/html/issues/246). It is no longer on track to become a standard. ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.mediaGroup` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/durationchange_event/index.md
--- title: "HTMLMediaElement: durationchange event" short-title: durationchange slug: Web/API/HTMLMediaElement/durationchange_event page-type: web-api-event browser-compat: api.HTMLMediaElement.durationchange_event --- {{APIRef("HTMLMediaElement")}} The `durationchange` event is fired when the `duration` attribute has been updated. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("durationchange", (event) => {}); ondurationchange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `durationchange` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("durationchange", (event) => { console.log("Not sure why, but the duration of the video has changed."); }); ``` Using the `ondurationchange` event handler property: ```js const video = document.querySelector("video"); video.ondurationchange = (event) => { console.log("Not sure why, but the duration of the video has changed."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/progress_event/index.md
--- title: "HTMLMediaElement: progress event" short-title: progress slug: Web/API/HTMLMediaElement/progress_event page-type: web-api-event browser-compat: api.HTMLMediaElement.progress_event --- {{APIRef}} The **`progress`** event is fired periodically as the browser loads a resource. 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("progress", (event) => {}); onprogress = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ### Live example #### HTML ```html <div class="example"> <button type="button">Load video</button> <video controls width="250"></video> <div class="event-log"> <label for="eventLog">Event log:</label> <textarea readonly class="event-log-contents" id="eventLog"></textarea> </div> </div> ``` ```css hidden .event-log-contents { width: 18rem; height: 5rem; border: 1px solid black; margin: 0.2rem; padding: 0.2rem; } .example { display: grid; grid-template-areas: "button log" "video log"; } button { grid-area: button; width: 10rem; margin: 0.5rem 0; } video { grid-area: video; } .event-log { grid-area: log; } .event-log > label { display: block; } ``` #### JavaScript ```js const loadVideo = document.querySelector("button"); const video = document.querySelector("video"); const eventLog = document.querySelector(".event-log-contents"); let source = null; function handleEvent(event) { eventLog.textContent += `${event.type}\n`; } video.addEventListener("loadstart", handleEvent); video.addEventListener("progress", handleEvent); video.addEventListener("canplay", handleEvent); video.addEventListener("canplaythrough", handleEvent); loadVideo.addEventListener("click", () => { if (source) { document.location.reload(); } else { loadVideo.textContent = "Reset example"; source = document.createElement("source"); source.setAttribute( "src", "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4", ); source.setAttribute("type", "video/mp4"); video.appendChild(source); } }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '250px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/setsinkid/index.md
--- title: "HTMLMediaElement: setSinkId() method" short-title: setSinkId() slug: Web/API/HTMLMediaElement/setSinkId page-type: web-api-instance-method browser-compat: api.HTMLMediaElement.setSinkId --- {{APIRef("Audio Output Devices API")}}{{securecontext_header}} The **`HTMLMediaElement.setSinkId()`** method of the [Audio Output Devices API](/en-US/docs/Web/API/Audio_Output_Devices_API) sets the ID of the audio device to use for output and returns a {{jsxref("Promise")}}. This only works when the application is permitted to use the specified device. For more information see the [security requirements](#security_requirements) below. ## Syntax ```js-nolint setSinkId(sinkId) ``` ### Parameters - `sinkId` - : The {{domxref("MediaDeviceInfo.deviceId")}} of the audio output device. ### Return value A {{jsxref("Promise")}} that resolves to {{jsxref("undefined")}}. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Returned if a [`speaker-selection`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/speaker-selection) [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) is used to block use of audio outputs. - `NotFoundError` {{domxref("DOMException")}} - : Returned if the `deviceId` does not match any audio output device. - `AbortError` {{domxref("DOMException")}} - : Returned if switching the audio output device to the new audio device failed. ## Security requirements Access to the API is subject to the following constraints: - The method must be called in a [secure context](/en-US/docs/Web/Security/Secure_Contexts). - Access may be gated by the [`speaker-selection`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/speaker-selection) HTTP [Permission Policy](/en-US/docs/Web/HTTP/Permissions_Policy). - User permission is required to access a non-default device. The user grants permission by selecting the device associated with the ID in the prompt displayed by {{domxref("MediaDevices.selectAudioOutput()")}}. ## Examples This example shows how to select an audio output device from the array returned by {{domxref("MediaDevices.enumerateDevices()")}}, and set it as the sink for audio. Note that the result of `enumerateDevices()` only includes devices for which user permission is not required or has already been granted. ```js const devices = await navigator.mediaDevices.enumerateDevices(); const audioDevice = devices.find((device) => device.kind === "audiooutput"); const audio = document.createElement("audio"); await audio.setSinkId(audioDevice.deviceId); console.log(`Audio is being output on ${audio.sinkId}`); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaDevices.selectAudioOutput()")}} - {{domxref("HTMLMediaElement.sinkId")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/seeked_event/index.md
--- title: "HTMLMediaElement: seeked event" short-title: seeked slug: Web/API/HTMLMediaElement/seeked_event page-type: web-api-event browser-compat: api.HTMLMediaElement.seeked_event --- {{APIRef("HTMLMediaElement")}} The `seeked` event is fired when a seek operation completed, the current playback position has changed, and the Boolean `seeking` attribute is changed to `false`. 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("seeked", (event) => {}); onseeked = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `seeked` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("seeked", (event) => { console.log("Video found the playback position it was looking for."); }); ``` Using the `onseeked` event handler property: ```js const video = document.querySelector("video"); video.onseeked = (event) => { console.log("Video found the playback position it was looking for."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/play/index.md
--- title: "HTMLMediaElement: play() method" short-title: play() slug: Web/API/HTMLMediaElement/play page-type: web-api-instance-method browser-compat: api.HTMLMediaElement.play --- {{APIRef("HTML DOM")}} The {{domxref("HTMLMediaElement")}} **`play()`** method attempts to begin playback of the media. It returns a {{jsxref("Promise")}} which is resolved when playback has been successfully started. Failure to begin playback for any reason, such as permission issues, result in the promise being rejected. ## Syntax ```js-nolint play() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} which is resolved when playback has been started, or is rejected if for any reason playback cannot be started. > **Note:** Browsers released before 2019 may not return a value from > `play()`. ### Exceptions The promise's **rejection handler** is called with a {{domxref("DOMException")}} object passed in as its sole input parameter (as opposed to a traditional exception being thrown). Possible errors include: - `NotAllowedError` {{domxref("DOMException")}} - : Provided if the user agent (browser) or operating system doesn't allow playback of media in the current context or situation. The browser may require the user to explicitly start media playback by clicking a "play" button, for example because of a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). - `NotSupportedError` {{domxref("DOMException")}} - : Provided if the media source (which may be specified as a {{domxref("MediaStream")}}, {{domxref("MediaSource")}}, {{domxref("Blob")}}, or {{domxref("File")}}, for example) doesn't represent a supported media format. Other exceptions may be reported, depending on browser implementation details, media player implementation, and so forth. ## Usage notes Although the term "autoplay" is usually thought of as referring to pages that immediately begin playing media upon being loaded, web browsers' autoplay policies also apply to any script-initiated playback of media, including calls to `play()`. If the {{Glossary("user agent")}} is configured not to allow automatic or script-initiated playback of media, calling `play()` will cause the returned promise to be immediately rejected with a `NotAllowedError`. Websites should be prepared to handle this situation. For example, a site should not present a user interface that assumes playback has begun automatically, but should instead update their UI based on whether the returned promise is fulfilled or rejected. See the [example](#examples) below for more information. > **Note:** The `play()` method may cause the user to be asked > to grant permission to play the media, resulting in a possible delay before the > returned promise is resolved. Be sure your code doesn't expect an immediate response. For even more in-depth information about autoplay and autoplay blocking, see our article [Autoplay guide for media and Web Audio APIs](/en-US/docs/Web/Media/Autoplay_guide). ## Examples This example demonstrates how to confirm that playback has begun and how to gracefully handle blocked automatic playback: ```js let videoElem = document.getElementById("video"); let playButton = document.getElementById("playbutton"); playButton.addEventListener("click", handlePlayButton, false); playVideo(); async function playVideo() { try { await videoElem.play(); playButton.classList.add("playing"); } catch (err) { playButton.classList.remove("playing"); } } function handlePlayButton() { if (videoElem.paused) { playVideo(); } else { videoElem.pause(); playButton.classList.remove("playing"); } } ``` In this example, playback of video is toggled off and on by the [`async`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) `playVideo()` function. It tries to play the video, and if successful sets the class name of the `playButton` element to `"playing"`. If playback fails to start, the `playButton` element's class is cleared, restoring its default appearance. This ensures that the play button matches the actual state of playback by watching for the resolution or rejection of the {{jsxref("Promise")}} returned by `play()`. When this example is executed, it begins by collecting references to the {{HTMLElement("video")}} element as well as the {{HTMLElement("button")}} used to toggle playback on and off. It then sets up an event handler for the {{domxref("Element/click_event", "click")}} event on the play toggle button and attempts to automatically begin playback by calling `playVideo()`. You can [try out or remix this example in real time on Glitch](https://media-play-promise.glitch.me/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web media technologies](/en-US/docs/Web/Media) - Learning: [Video and audio content](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) - [Autoplay guide for media and Web Audio APIs](/en-US/docs/Web/Media/Autoplay_guide) - [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/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/loop/index.md
--- title: "HTMLMediaElement: loop property" short-title: loop slug: Web/API/HTMLMediaElement/loop page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.loop --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.loop`** property reflects the [`loop`](/en-US/docs/Web/HTML/Element/video#loop) HTML attribute, which controls whether the media element should start over when it reaches the end. ## Value A boolean value. ## Examples ```js const obj = document.createElement("video"); obj.loop = true; // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.loop` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/canplaythrough_event/index.md
--- title: "HTMLMediaElement: canplaythrough event" short-title: canplaythrough slug: Web/API/HTMLMediaElement/canplaythrough_event page-type: web-api-event browser-compat: api.HTMLMediaElement.canplaythrough_event --- {{APIRef("HTMLMediaElement")}} The `canplaythrough` event is fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content. 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("canplaythrough", (event) => {}); oncanplaythrough = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `canplaythrough` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("canplaythrough", (event) => { console.log( "I think I can play through the entire video without having to stop to buffer.", ); }); ``` Using the `oncanplaythrough` event handler property: ```js const video = document.querySelector("video"); video.oncanplaythrough = (event) => { console.log( "I think I can play through the entire video without having to stop to buffer.", ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/loadstart_event/index.md
--- title: "HTMLMediaElement: loadstart event" short-title: loadstart slug: Web/API/HTMLMediaElement/loadstart_event page-type: web-api-event browser-compat: api.HTMLMediaElement.loadstart_event --- {{APIRef}} The **`loadstart`** event is fired when the browser has started to load a resource. ## 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 generic {{domxref("Event")}}. ## Examples ### Live example #### HTML ```html <div class="example"> <button type="button">Load video</button> <video controls width="250"></video> <div class="event-log"> <label for="eventLog">Event log:</label> <textarea readonly class="event-log-contents" id="eventLog"></textarea> </div> </div> ``` ```css hidden .event-log-contents { width: 18rem; height: 5rem; border: 1px solid black; margin: 0.2rem; padding: 0.2rem; } .example { display: grid; grid-template-areas: "button log" "video log"; } button { grid-area: button; width: 10rem; margin: 0.5rem 0; } video { grid-area: video; } .event-log { grid-area: log; } .event-log > label { display: block; } ``` #### JavaScript ```js const loadVideo = document.querySelector("button"); const video = document.querySelector("video"); const eventLog = document.querySelector(".event-log-contents"); let source = null; function handleEvent(event) { eventLog.textContent += `${event.type}\n`; } video.addEventListener("loadstart", handleEvent); video.addEventListener("progress", handleEvent); video.addEventListener("canplay", handleEvent); video.addEventListener("canplaythrough", handleEvent); loadVideo.addEventListener("click", () => { if (source) { document.location.reload(); } else { loadVideo.textContent = "Reset example"; source = document.createElement("source"); source.setAttribute( "src", "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm", ); source.setAttribute("type", "video/webm"); video.appendChild(source); } }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '200px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/ended/index.md
--- title: "HTMLMediaElement: ended property" short-title: ended slug: Web/API/HTMLMediaElement/ended page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.ended --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.ended`** property indicates whether the media element has ended playback. ## Value A boolean value which is `true` if the media contained in the element has finished playing. If the source of the media is a {{domxref("MediaStream")}}, this value is `true` if the value of the stream's {{domxref("MediaStream.active", "active")}} property is `false`. ## Examples ```js const obj = document.createElement("video"); console.log(obj.ended); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.ended` property - {{domxref("MediaStream")}} - {{domxref("MediaStream.active")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/src/index.md
--- title: "HTMLMediaElement: src property" short-title: src slug: Web/API/HTMLMediaElement/src page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.src --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.src`** property reflects the value of the HTML media element's `src` attribute, which indicates the URL of a media resource to use in the element. > **Note:** The best way to know the URL of the media resource currently > in active use in this element is to look at the value of the > {{domxref("HTMLMediaElement.currentSrc", "currentSrc")}} attribute, which also takes > into account selection of a best or preferred media resource from a list provided in > an {{domxref("HTMLSourceElement")}} (which represents a {{HTMLElement("source")}} > element). ## Value A string object containing the URL of a media resource to use in the element; this property reflects the value of the HTML element's `src` attribute. ## Examples ```js const obj = document.createElement("video"); console.log(obj.src); // "" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.src` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/readystate/index.md
--- title: "HTMLMediaElement: readyState property" short-title: readyState slug: Web/API/HTMLMediaElement/readyState page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.readyState --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.readyState`** property indicates the readiness state of the media. ## Value An `unsigned short`. Possible values are: <table class="no-markdown"> <thead> <tr> <th scope="col">Constant</th> <th scope="col">Value</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>HAVE_NOTHING</code></td> <td>0</td> <td>No information is available about the media resource.</td> </tr> <tr> <td><code>HAVE_METADATA</code></td> <td>1</td> <td> Enough of the media resource has been retrieved that the metadata attributes are initialized. Seeking will no longer raise an exception. </td> </tr> <tr> <td><code>HAVE_CURRENT_DATA</code></td> <td>2</td> <td> Data is available for the current playback position, but not enough to actually play more than one frame. </td> </tr> <tr> <td><code>HAVE_FUTURE_DATA</code></td> <td>3</td> <td> Data for the current playback position as well as for at least a little bit of time into the future is available (in other words, at least two frames of video, for example). </td> </tr> <tr> <td><code>HAVE_ENOUGH_DATA</code></td> <td>4</td> <td> Enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption. </td> </tr> </tbody> </table> ## Examples This example will listen for audio data to be loaded for the element `example`. It will then check if at least the current playback position has been loaded. If it has, the audio will play. ```html <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> ``` ```js const obj = document.getElementById("example"); obj.addEventListener("loadeddata", () => { if (obj.readyState >= 2) { obj.play(); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.readyState` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/ended_event/index.md
--- title: "HTMLMediaElement: ended event" short-title: ended slug: Web/API/HTMLMediaElement/ended_event page-type: web-api-event browser-compat: api.HTMLMediaElement.ended_event --- {{APIRef("HTMLMediaElement")}} The `ended` event is fired when playback or streaming has stopped because the end of the media was reached or because no further data is available. This event occurs based upon {{domxref("HTMLMediaElement")}} ({{HTMLElement("audio")}} and {{HTMLElement("video")}}) fire `ended` when playback reaches the end of the media. 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("ended", (event) => {}); onended = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `ended` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("ended", (event) => { console.log( "Video stopped either because it has finished playing or no further data is available.", ); }); ``` Using the `onended` event handler property: ```js const video = document.querySelector("video"); video.onended = (event) => { console.log( "Video stopped either because it has finished playing or no further data is available.", ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}} - [Media Capture and Streams](/en-US/docs/Web/API/Media_Capture_and_Streams_API) - [Media Capture and Streams](/en-US/docs/Web/API/Media_Capture_and_Streams_API)[: ended event](/en-US/docs/Web/API/MediaStreamTrack/ended_event) - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) - [Web audio API: ended event](/en-US/docs/Web/API/AudioScheduledSourceNode/ended_event)
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/load/index.md
--- title: "HTMLMediaElement: load() method" short-title: load() slug: Web/API/HTMLMediaElement/load page-type: web-api-instance-method browser-compat: api.HTMLMediaElement.load --- {{APIRef("HTML DOM")}} The {{domxref("HTMLMediaElement")}} method **`load()`** resets the media element to its initial state and begins the process of selecting a media source and loading the media in preparation for playback to begin at the beginning. The amount of media data that is prefetched is determined by the value of the element's [`preload`](/en-US/docs/Web/HTML/Element/video#preload) attribute. This method is generally only useful when you've made dynamic changes to the set of sources available for the media element, either by changing the element's [`src`](/en-US/docs/Web/HTML/Element/video#src) attribute or by adding or removing {{HTMLElement("source")}} elements nested within the media element itself. `load()` will reset the element and rescan the available sources, thereby causing the changes to take effect. ## Syntax ```js-nolint load() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Usage notes Calling `load()` aborts all ongoing operations involving this media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the {{HTMLElement("audio")}} or {{HTMLElement("video")}} element and its [`src`](/en-US/docs/Web/HTML/Element/video#src) attribute or child {{HTMLElement("source")}} element(s). This is described in more detail in the [Video and audio content](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content#using_multiple_source_formats_to_improve_compatibility) page. The process of aborting any ongoing activities will cause any outstanding {{jsxref("Promise")}}s returned by {{domxref("HTMLMediaElement.play", "play()")}} being fulfilled or rejected as appropriate based on their status before the loading of new media can begin. Pending play promises are aborted with an `"AbortError"` {{domxref("DOMException")}}. Appropriate events will be sent to the media element itself as the load process proceeds: - If the element is already in the process of loading media, that load process is aborted and the **{{domxref("HTMLMediaElement/abort_event", "abort")}}** event is sent. - If the element has already been initialized with media, the **{{domxref("HTMLMediaElement/emptied_event", "emptied")}}** event is sent. - If resetting the playback position to the beginning of the media actually changes the playback position (that is, it was not already at the beginning), a **{{domxref("HTMLMediaElement/timeupdate_event", "timeupdate")}}** event is sent. - Once media has been selected and loading is ready to begin, the **{{domxref("HTMLMediaElement/loadstart_event", "loadstart")}}** event is delivered. - From this point onward, events are sent just like any media load. ## Examples This example finds a {{HTMLElement("video")}} element in the document and resets it by calling `load()`. ```js const mediaElem = document.querySelector("video"); mediaElem.load(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/setmediakeys/index.md
--- title: "HTMLMediaElement: setMediaKeys() method" short-title: setMediaKeys() slug: Web/API/HTMLMediaElement/setMediaKeys page-type: web-api-instance-method browser-compat: api.HTMLMediaElement.setMediaKeys --- {{APIRef("HTML DOM")}}{{SecureContext_Header}} The **`setMediaKeys()`** method of the {{domxref("HTMLMediaElement")}} interface returns a {{jsxref("Promise")}} that resolves to the passed {{domxref("MediaKeys")}}, which are those used to decrypt media during playback. ## Syntax ```js-nolint setMediaKeys(mediaKeys) ``` ### Parameters - `mediaKeys` - : A reference to a {{domxref("MediaKeys")}} object that the {{domxref("HTMLMediaElement")}} can use for decryption of media data during playback. ### Return value A {{jsxref("Promise")}} that resolves to the passed instance of `MediaKeys`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/encrypted_event/index.md
--- title: "HTMLMediaElement: encrypted event" short-title: encrypted slug: Web/API/HTMLMediaElement/encrypted_event page-type: web-api-event browser-compat: api.HTMLMediaElement.encrypted_event --- {{APIRef("EncryptedMediaExtensions")}} The `encrypted` event is fired when the media encounters some initialization data indicating it is encrypted. 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("encrypted", (event) => {}); onencrypted = (event) => {}; ``` ## Event type A {{domxref("MediaEncryptedEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MediaEncryptedEvent")}} ## Event properties - {{domxref("MediaEncryptedEvent.initDataType")}} {{ReadOnlyInline}} - : Returns a case-sensitive string with the _type_ of the format of the initialization data found. - {{domxref("MediaEncryptedEvent.initData")}} {{ReadOnlyInline}} - : Returns an {{jsxref("ArrayBuffer")}} containing the initialization data found. If there is no initialization data associated with the format, it returns `null`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}} - {{domxref("MediaEncryptedEvent")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/mediakeys/index.md
--- title: "HTMLMediaElement: mediaKeys property" short-title: mediaKeys slug: Web/API/HTMLMediaElement/mediaKeys page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.mediaKeys --- {{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}} The read-only **`HTMLMediaElement.mediaKeys`** property returns a {{domxref("MediaKeys")}} object, that is a set of keys that the element can use for decryption of media data during playback. ## Value A {{domxref("MediaKeys")}} object, or `null` if no key is available. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaKeys")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/seeking_event/index.md
--- title: "HTMLMediaElement: seeking event" short-title: seeking slug: Web/API/HTMLMediaElement/seeking_event page-type: web-api-event browser-compat: api.HTMLMediaElement.seeking_event --- {{APIRef("HTMLMediaElement")}} The `seeking` event is fired when a seek operation starts, meaning the Boolean `seeking` attribute has changed to `true` and the media is seeking a new position. 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("seeking", (event) => {}); onseeking = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `seeking` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("seeking", (event) => { console.log("Video is seeking a new position."); }); ``` Using the `onseeking` event handler property: ```js const video = document.querySelector("video"); video.onseeking = (event) => { console.log("Video is seeking a new position."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/duration/index.md
--- title: "HTMLMediaElement: duration property" short-title: duration slug: Web/API/HTMLMediaElement/duration page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.duration --- {{APIRef("HTML DOM")}} The _read-only_ {{domxref("HTMLMediaElement")}} property **`duration`** indicates the length of the element's media in seconds. ## Value A double-precision floating-point value indicating the duration of the media in seconds. If no media data is available, the value `NaN` is returned. If the element's media doesn't have a known duration—such as for live media streams—the value of `duration` is `+Infinity`. ## Examples ```js const obj = document.createElement("video"); console.log(obj.duration); // NaN ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web media technologies](/en-US/docs/Web/Media) - {{domxref("HTMLMediaElement.currentTime")}}: The current playback position of the media - The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/paused/index.md
--- title: "HTMLMediaElement: paused property" short-title: paused slug: Web/API/HTMLMediaElement/paused page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.paused --- {{APIRef("HTML DOM")}} The read-only **`HTMLMediaElement.paused`** property tells whether the media element is paused. ## Value A boolean value. `true` is paused and `false` is not paused. ## Examples ```js const obj = document.createElement("video"); console.log(obj.paused); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.paused` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/ratechange_event/index.md
--- title: "HTMLMediaElement: ratechange event" short-title: ratechange slug: Web/API/HTMLMediaElement/ratechange_event page-type: web-api-event browser-compat: api.HTMLMediaElement.ratechange_event --- {{APIRef("HTMLMediaElement")}} The `ratechange` event is fired when the playback rate has changed. 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("ratechange", (event) => {}); onratechange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `ratechange` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("ratechange", (event) => { console.log("The playback rate changed."); }); ``` Using the `onratechange` event handler property: ```js const video = document.querySelector("video"); video.onratechange = (event) => { console.log("The playback rate changed."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/seektonextframe/index.md
--- title: "HTMLMediaElement: seekToNextFrame() method" short-title: seekToNextFrame() slug: Web/API/HTMLMediaElement/seekToNextFrame page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.HTMLMediaElement.seekToNextFrame --- {{APIRef("HTML DOM")}}{{Deprecated_Header}}{{non-standard_header}} The **`HTMLMediaElement.seekToNextFrame()`** method asynchronously advances the current play position to the next frame in the media. > **Warning:** This non-standard method is part of an experimentation process around support for > non-real-time access to media for tasks including filtering, editing, and so forth. > You should _not_ use this method in production code, because its implementation > may change—or be removed outright—without notice. You are, however, invited to > experiment with it. This method lets you access frames of video media without the media being performed in real time. This also lets you access media using frames as a seek unit rather than timecodes (albeit only by seeking one frame at a time until you get to the frame you want). Possible uses for this method include filtering and editing of video content. This method returns immediately, returning a {{jsxref("Promise")}}, whose fulfillment handler is called when the seek operation is complete. In addition, a {{domxref("HTMLMediaElement/seeked_event", "seeked")}} event is sent to let interested parties know that a seek has taken place. If the seek fails because the media is already at the last frame, a {{domxref("HTMLMediaElement/seeked_event", "seeked")}} event occurs, followed immediately by an {{domxref("HTMLMediaElement/ended_event", "ended")}} event. If there is no video on the media element, or the media isn't seekable, nothing happens. ## Syntax ```js-nolint seekToNextFrame() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} which is fulfilled once the seek operation has completed. ## Specifications Not part of any specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/sinkid/index.md
--- title: "HTMLMediaElement: sinkId property" short-title: sinkId slug: Web/API/HTMLMediaElement/sinkId page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.sinkId --- {{APIRef("Audio Output Devices API")}}{{securecontext_header}} The **`HTMLMediaElement.sinkId`** read-only property of the [Audio Output Devices API](/en-US/docs/Web/API/Audio_Output_Devices_API) returns a string that is the unique ID of the device to be used for playing audio output. This ID should be one of the {{domxref("MediaDeviceInfo.deviceId")}} values returned from {{domxref("MediaDevices.enumerateDevices()")}}, `id-multimedia`, or `id-communications`. If the user agent default device is being used, it returns an empty string. ## Value A string indicating the current audio output device, or the empty string if the default user agent output device is being used. ## Security requirements Access to the property is subject to the following constraints: - The property must be called in a [secure context](/en-US/docs/Web/Security/Secure_Contexts). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaDevices.selectAudioOutput()")}} - {{domxref("HTMLMediaElement.setSinkId()")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/playing_event/index.md
--- title: "HTMLMediaElement: playing event" short-title: playing slug: Web/API/HTMLMediaElement/playing_event page-type: web-api-event browser-compat: api.HTMLMediaElement.playing_event --- {{APIRef("HTMLMediaElement")}} The `playing` event is fired after playback is first started, and whenever it is restarted. For example it is fired when playback resumes after having been paused or delayed due to lack of data. 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("playing", (event) => {}); onplaying = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `playing` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("playing", (event) => { console.log("Video is no longer paused"); }); ``` Using the `onplaying` event handler property: ```js const video = document.querySelector("video"); video.onplaying = (event) => { console.log("Video is no longer paused."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/videotracks/index.md
--- title: "HTMLMediaElement: videoTracks property" short-title: videoTracks slug: Web/API/HTMLMediaElement/videoTracks page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.videoTracks --- {{APIRef("HTML DOM")}} The read-only **`videoTracks`** property on {{DOMxRef("HTMLMediaElement")}} objects returns a {{DOMxRef("VideoTrackList")}} object listing all of the {{DOMxRef("VideoTrack")}} objects representing the media element's video tracks. The returned list is _live_; that is, as tracks are added to and removed from the media element, the list's contents change dynamically. Once you have a reference to the list, you can monitor it for changes to detect when new video tracks are added or existing ones removed. See [VideoTrackList events](/en-US/docs/Web/API/VideoTrackList#events) to learn more about watching for changes to a media element's track list. ## Value A {{DOMxRef("VideoTrackList")}} object representing the list of video tracks included in the media element. The list of tracks can be accessed using array notation, or using the object's {{domxref("VideoTrackList.getTrackById", "getTrackById()")}} method. Each track is represented by a {{DOMxRef("VideoTrack")}} object which provides information about the track. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.videoTracks` property - {{HTMLElement("video")}} - {{DOMxRef("VideoTrack")}}, {{DOMxRef("VideoTrackList")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/currentsrc/index.md
--- title: "HTMLMediaElement: currentSrc property" short-title: currentSrc slug: Web/API/HTMLMediaElement/currentSrc page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.currentSrc --- {{APIRef("HTML DOM")}} The **`HTMLMediaElement.currentSrc`** property contains the absolute URL of the chosen media resource. This could happen, for example, if the web server selects a media file based on the resolution of the user's display. The value is an empty string if the `networkState` property is `EMPTY`. ## Value A string object containing the absolute URL of the chosen media source; this may be an empty string if `networkState` is `EMPTY`; otherwise, it will be one of the resources listed by the {{domxref("HTMLSourceElement")}} contained within the media element, or the value or src if no {{HTMLElement("source")}} element is provided. ## Examples ```js const obj = document.createElement("video"); console.log(obj.currentSrc); // "" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLMediaElement")}}: Interface used to define the `HTMLMediaElement.currentSrc` property
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/error_event/index.md
--- title: "HTMLMediaElement: error event" short-title: error slug: Web/API/HTMLMediaElement/error_event page-type: web-api-event browser-compat: api.HTMLMediaElement.error_event --- {{APIRef}} The **`error`** event is fired when the resource could not be loaded due to an error (for example, a network connectivity problem). 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("error", (event) => {}); onerror = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js const video = document.querySelector("video"); const videoSrc = "https://path/to/video.webm"; video.addEventListener("error", () => { console.error(`Error loading: ${videoSrc}`); }); video.setAttribute("src", videoSrc); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/volumechange_event/index.md
--- title: "HTMLMediaElement: volumechange event" short-title: volumechange slug: Web/API/HTMLMediaElement/volumechange_event page-type: web-api-event browser-compat: api.HTMLMediaElement.volumechange_event --- {{APIRef("HTMLMediaElement")}} The `volumechange` event is fired when either the {{domxref("HTMLMediaElement.volume", "volume")}} attribute or the {{domxref("HTMLMediaElement.muted", "muted")}} attribute has changed. 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("volumechange", (event) => {}); onvolumechange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLMediaElement's `volumechange` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("video"); video.addEventListener("volumechange", (event) => { console.log("The volume changed."); }); ``` Using the `onvolumechange` event handler property: ```js const video = document.querySelector("video"); video.onvolumechange = (event) => { console.log("The volume changed."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related Events - The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.play_event", 'play')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.pause_event", 'pause')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} event - The HTMLMediaElement {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} event ## See also - {{domxref("HTMLAudioElement")}} - {{domxref("HTMLVideoElement")}} - {{HTMLElement("audio")}} - {{HTMLElement("video")}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/remote/index.md
--- title: "HTMLMediaElement: remote property" short-title: remote slug: Web/API/HTMLMediaElement/remote page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.remote --- {{APIRef("Remote Playback API")}} The **`remote`** read-only property of the {{domxref("HTMLMediaElement")}} interface returns the {{domxref("RemotePlayback")}} object associated with the media element. The `RemotePlayback` object allow the control of remote devices playing the media. ## Value The associated {{domxref("RemotePlayback")}} object. ## Example ```js const el = document.createElement("audio"); const remotePlayback = el.remote; remotePlayback.watchAvailability((availability) => { // Do something when the availability changes }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlmediaelement
data/mdn-content/files/en-us/web/api/htmlmediaelement/srcobject/index.md
--- title: "HTMLMediaElement: srcObject property" short-title: srcObject slug: Web/API/HTMLMediaElement/srcObject page-type: web-api-instance-property browser-compat: api.HTMLMediaElement.srcObject --- {{APIRef("HTML DOM")}} The **`srcObject`** property of the {{domxref("HTMLMediaElement")}} interface sets or returns the object which serves as the source of the media associated with the {{domxref("HTMLMediaElement")}}. The object can be a {{domxref("MediaStream")}}, a {{domxref("MediaSource")}}, a {{domxref("Blob")}}, or a {{domxref("File")}} (which inherits from `Blob`). > **Note:** As of March 2020, only Safari has full support for `srcObject`, i.e. using `MediaSource`, `MediaStream`, `Blob`, and `File` objects as values. Other browsers support `MediaStream` objects; until they catch up, consider falling back to creating a URL with {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}} and assigning it to {{domxref("HTMLMediaElement.src")}} (see below for an example). In addition, as of version 108 Chromium supports attaching a dedicated worker `MediaSource` object by assigning that object's {{domxref("MediaSourceHandle")}} instance (transferred from the worker) to `srcObject`. ## Value A {{domxref('MediaStream')}}, {{domxref('MediaSource')}}, {{domxref('Blob')}}, or {{domxref('File')}} object (though see the compatibility table for what is actually supported). ## Usage notes Older versions of the Media Source specification required using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}} to create an object URL then setting {{domxref("HTMLMediaElement.src", "src")}} to that URL. Now you can just set `srcObject` to the {{domxref("MediaStream")}} directly. ## Examples ### Basic example In this example, a {{domxref("MediaStream")}} from a camera is assigned to a newly-created {{HTMLElement("video")}} element. ```js const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true }); const video = document.createElement("video"); video.srcObject = mediaStream; ``` In this example, a new {{domxref('MediaSource')}} is assigned to a newly-created {{HTMLElement("video")}} element. ```js const mediaSource = new MediaSource(); const video = document.createElement("video"); video.srcObject = mediaSource; ``` ### Supporting fallback to the src property The examples below support older browser versions that require you to create an object URL and assign it to `src` if `srcObject` isn't supported. First, a {{domxref("MediaStream")}} from a camera is assigned to a newly-created {{HTMLElement("video")}} element, with fallback for older browsers. ```js const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true }); const video = document.createElement("video"); if ("srcObject" in video) { video.srcObject = mediaStream; } else { // Avoid using this in new browsers, as it is going away. video.src = URL.createObjectURL(mediaStream); } ``` Second, a new {{domxref('MediaSource')}} is assigned to a newly-created {{HTMLElement("video")}} element, with fallback for older browsers and browsers that don't yet support assignment of {{domxref('MediaSource')}} directly. ```js const mediaSource = new MediaSource(); const video = document.createElement("video"); // Older browsers may not have srcObject if ("srcObject" in video) { try { video.srcObject = mediaSource; } catch (err) { if (err.name !== "TypeError") { throw err; } // Even if they do, they may only support MediaStream video.src = URL.createObjectURL(mediaSource); } } else { video.src = URL.createObjectURL(mediaSource); } ``` ### Constructing a `MediaSource` in a worker and passing it to the main thread to play The {{domxref("MediaSource.handle")}} property can be accessed inside a dedicated worker and the resulting {{domxref("MediaSourceHandle")}} object is then transferred over to the thread that created the worker (in this case the main thread) via a {{domxref("DedicatedWorkerGlobalScope.postMessage()", "postMessage()")}} call: ```js // Inside dedicated worker let mediaSource = new MediaSource(); let handle = mediaSource.handle; // Transfer the handle to the context that created the worker postMessage({ arg: handle }, [handle]); mediaSource.addEventListener("sourceopen", () => { // Await sourceopen on MediaSource before creating SourceBuffers // and populating them with fetched media — MediaSource won't // accept creation of SourceBuffers until it is attached to the // HTMLMediaElement and its readyState is "open" }); ``` Over in the main thread, we receive the handle via a {{domxref("Worker.message_event", "message")}} event handler, attach it to a {{htmlelement("video")}} via its {{domxref("HTMLMediaElement.srcObject")}} property, and {{domxref("HTMLMediaElement.play()", "play")}} the video: ```js worker.addEventListener("message", (msg) => { let mediaSourceHandle = msg.data.arg; video.srcObject = mediaSourceHandle; video.play(); }); ``` > **Note:** {{domxref("MediaSourceHandle")}}s cannot be successfully transferred into or via a shared worker or service worker. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/geolocationpositionerror/index.md
--- title: GeolocationPositionError slug: Web/API/GeolocationPositionError page-type: web-api-interface browser-compat: api.GeolocationPositionError --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`GeolocationPositionError`** interface represents the reason of an error occurring when using the geolocating device. ## Instance properties _The `GeolocationPositionError` interface doesn't inherit any property._ - {{domxref("GeolocationPositionError.code")}} {{ReadOnlyInline}} - : Returns an `unsigned short` representing the error code. The following values are possible: | Value | Associated constant | Description | | ----- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `1` | `PERMISSION_DENIED` | The acquisition of the geolocation information failed because the page didn't have the necessary permissions, for example because it is blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) | | `2` | `POSITION_UNAVAILABLE` | The acquisition of the geolocation failed because at least one internal source of position returned an internal error. | | `3` | `TIMEOUT` | The time allowed to acquire the geolocation was reached before the information was obtained. | - {{domxref("GeolocationPositionError.message")}} {{ReadOnlyInline}} - : Returns a human-readable string describing the details of the error. Specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface. ## Instance methods _The `GeolocationPositionError` interface neither implements nor inherits any method._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Geolocation API](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - {{domxref("Geolocation")}}
0
data/mdn-content/files/en-us/web/api/geolocationpositionerror
data/mdn-content/files/en-us/web/api/geolocationpositionerror/message/index.md
--- title: "GeolocationPositionError: message property" short-title: message slug: Web/API/GeolocationPositionError/message page-type: web-api-instance-property browser-compat: api.GeolocationPositionError.message --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`message`** read-only property of the {{domxref("GeolocationPositionError")}} interface returns a human-readable string describing the details of the error. ## Value A human-readable string describing the details of the error. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Geolocation API](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - {{domxref("GeolocationPositionError")}}
0
data/mdn-content/files/en-us/web/api/geolocationpositionerror
data/mdn-content/files/en-us/web/api/geolocationpositionerror/code/index.md
--- title: "GeolocationPositionError: code property" short-title: code slug: Web/API/GeolocationPositionError/code page-type: web-api-instance-property browser-compat: api.GeolocationPositionError.code --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`code`** read-only property of the {{domxref("GeolocationPositionError")}} interface is an `unsigned short` representing the error code. The following values are possible: <table class="no-markdown"> <thead> <tr> <th scope="col">Value</th> <th scope="col">Associated constant</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>1</code></td> <td><code>PERMISSION_DENIED</code></td> <td> The acquisition of the geolocation information failed because the page didn't have the permission to do it. </td> </tr> <tr> <td><code>2</code></td> <td><code>POSITION_UNAVAILABLE</code></td> <td> The acquisition of the geolocation failed because one or several internal sources of position returned an internal error. </td> </tr> <tr> <td><code>3</code></td> <td><code>TIMEOUT</code></td> <td>Geolocation information was not obtained in the allowed time.</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using geolocation](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - {{domxref("GeolocationPositionError")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/performance_property/index.md
--- title: performance global property short-title: performance slug: Web/API/performance_property page-type: web-api-global-property browser-compat: api.performance --- {{APIRef("Performance API")}}{{AvailableInWorkers}} The global **`performance`** property returns a {{domxref("Performance")}} object, which can be used to gather performance information about the context it is called in (window or worker). Performance entries are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa. ## Value A {{domxref("Performance")}} object offering access to performance and timing-related information for the context it is called on (window or worker). ## Performance API availability The following table provides an overview about the availability of the performance APIs in window and worker contexts. | API | Window | Worker | | ---------------------------------------------------------- | ------ | ------ | | {{domxref("LargestContentfulPaint")}} | x | | | {{domxref("LayoutShift")}} | x | | | {{domxref("LayoutShiftAttribution")}} | x | | | {{domxref("Performance")}} | x | x | | {{domxref("PerformanceElementTiming")}} | x | | | {{domxref("PerformanceEntry")}} | x | x | | {{domxref("PerformanceEventTiming")}} | x | | | {{domxref("PerformanceLongTaskTiming")}} | x | | | {{domxref("PerformanceMark")}} | x | x | | {{domxref("PerformanceMeasure")}} | x | x | | {{domxref("PerformanceNavigation")}} {{deprecated_inline}} | x | | | {{domxref("PerformanceNavigationTiming")}} | x | | | {{domxref("PerformanceObserver")}} | x | x | | {{domxref("PerformanceObserverEntryList")}} | x | x | | {{domxref("PerformancePaintTiming")}} | x | | | {{domxref("PerformanceResourceTiming")}} | x | x | | {{domxref("PerformanceServerTiming")}} | x | x | | {{domxref("PerformanceTiming")}} {{deprecated_inline}} | x | | | {{domxref("TaskAttributionTiming")}} | x | | | {{domxref("VisibilityStateEntry")}} | x | | ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpucompilationmessage/index.md
--- title: GPUCompilationMessage slug: Web/API/GPUCompilationMessage page-type: web-api-interface status: - experimental browser-compat: api.GPUCompilationMessage --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPUCompilationMessage`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a single informational, warning, or error message generated by the GPU shader module compiler. An array of `GPUCompilationMessage` objects is available in the `messages` property of the {{domxref("GPUCompilationInfo")}} object accessed via {{domxref("GPUShaderModule.getCompilationInfo()")}}. {{InheritanceDiagram}} ## Instance properties - {{domxref("GPUCompilationMessage.length", "length")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A number representing the length of the substring that the message corresponds to. - {{domxref("GPUCompilationMessage.lineNum", "lineNum")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A number representing the line number in the shader code that the message corresponds to. - {{domxref("GPUCompilationMessage.linePos", "linePos")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A number representing the position in the code line that the message corresponds to. This could be an exact point, or the start of the relevant substring. - {{domxref("GPUCompilationMessage.message", "message")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A string representing human-readable message text. - {{domxref("GPUCompilationMessage.offset", "offset")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A number representing the offset from the start of the shader code to the exact point, or the start of the relevant substring, that the message corresponds to. - {{domxref("GPUCompilationMessage.type", "type")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : An enumerated value representing the type of the message — `"error"`, `"info"`, or `"warning"`. ## Examples See the main [`GPUCompilationInfo` page](/en-US/docs/Web/API/GPUCompilationInfo#examples) for an example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0