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/cssmathsum
data/mdn-content/files/en-us/web/api/cssmathsum/cssmathsum/index.md
--- title: "CSSMathSum: CSSMathSum() constructor" short-title: CSSMathSum() slug: Web/API/CSSMathSum/CSSMathSum page-type: web-api-constructor status: - experimental browser-compat: api.CSSMathSum.CSSMathSum --- {{APIRef("CSS Typed Object Model API")}}{{SeeCompatTable}} The **`CSSMathSum()`** constructor creates a new {{domxref("CSSMathSum")}} object which creates a new {{domxref('CSSKeywordValue')}} object which represents the result obtained by calling {{domxref('CSSNumericValue.add','add()')}}, {{domxref('CSSNumericValue.sub','sub()')}}, or {{domxref('CSSNumericValue.toSum','toSum()')}} on {{domxref('CSSNumericValue')}}. ## Syntax ```js-nolint new CSSMathSum(values) ``` ### Parameters - `values` - : One or more double integers or {{domxref('CSSNumericValue')}} objects. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/canvaspattern/index.md
--- title: CanvasPattern slug: Web/API/CanvasPattern page-type: web-api-interface browser-compat: api.CanvasPattern --- {{APIRef("Canvas API")}} The **`CanvasPattern`** interface represents an [opaque object](https://en.wikipedia.org/wiki/Opaque_data_type) describing a pattern, based on an image, a canvas, or a video, created by the {{domxref("CanvasRenderingContext2D.createPattern()")}} method. It can be used as a {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} or {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}}. ## Instance properties _As an opaque object, this has no exposed property._ ## Instance methods _There are no inherited method._ - {{domxref("CanvasPattern.setTransform()")}} - : Applies a {{domxref("DOMMatrix")}} representing a linear transform to the pattern. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("CanvasRenderingContext2D.createPattern()")}} - The {{HTMLElement("canvas")}} element and its associated interface, {{domxref("HTMLCanvasElement")}}
0
data/mdn-content/files/en-us/web/api/canvaspattern
data/mdn-content/files/en-us/web/api/canvaspattern/settransform/index.md
--- title: "CanvasPattern: setTransform() method" short-title: setTransform() slug: Web/API/CanvasPattern/setTransform page-type: web-api-instance-method browser-compat: api.CanvasPattern.setTransform --- {{APIRef("Canvas API")}} The **`CanvasPattern.setTransform()`** method uses a {{domxref("DOMMatrix")}} object as the pattern's transformation matrix and invokes it on the pattern. ## Syntax ```js-nolint setTransform(matrix) ``` ### Parameters - `matrix` - : A {{domxref("DOMMatrix")}} to use as the pattern's transformation matrix. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Using the `setTransform` method This is just a simple code snippet which uses the `setTransform` method to create a {{domxref("CanvasPattern")}} with the specified pattern transformation from a {{domxref("DOMMatrix")}}. The pattern gets applied if you set it as the current {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} and gets drawn onto the canvas when using the {{domxref("CanvasRenderingContext2D.fillRect", "fillRect()")}} method, for example. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const matrix = new DOMMatrix([1, 0.2, 0.8, 1, 0, 0]); const img = new Image(); img.src = "canvas_createpattern.png"; img.onload = () => { const pattern = ctx.createPattern(img, "repeat"); pattern.setTransform(matrix.rotate(-45).scale(1.5)); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 400, 400); }; ``` #### Editable demo Here's an editable demo of the code snippet above. Try changing the argument to `SetTransform()` to see the effect it had. ```html hidden <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code" style="height:120px"> const img = new Image(); img.src = 'canvas_createpattern.png'; img.onload = () => { const pattern = ctx.createPattern(img, 'repeat'); pattern.setTransform(matrix.rotate(-45).scale(1.5)); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 400, 400); }; </textarea> ``` ```js hidden const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const textarea = document.getElementById("code"); const reset = document.getElementById("reset"); const edit = document.getElementById("edit"); const code = textarea.value; const matrix = new DOMMatrix([1, 0.2, 0.8, 1, 0, 0]); function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", () => { textarea.value = code; drawCanvas(); }); edit.addEventListener("click", () => { textarea.focus(); }); textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas); ``` {{ EmbedLiveSample('Editable_demo', 700, 400) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasPattern")}} - {{domxref("DOMMatrix")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/path2d/index.md
--- title: Path2D slug: Web/API/Path2D page-type: web-api-interface browser-compat: api.Path2D --- {{APIRef("Canvas API")}} The **`Path2D`** interface of the Canvas 2D API is used to declare a path that can then be used on a {{domxref("CanvasRenderingContext2D")}} object. The [path methods](/en-US/docs/Web/API/CanvasRenderingContext2D#paths) of the `CanvasRenderingContext2D` interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. ## Constructors - {{domxref("Path2D.Path2D", "Path2D()")}} - : `Path2D` constructor. Creates a new `Path2D` object. ## Instance methods - {{domxref("Path2D.addPath()")}} - : Adds a path to the current path. - {{domxref("CanvasRenderingContext2D.closePath", "Path2D.closePath()")}} - : Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing. - {{domxref("CanvasRenderingContext2D.moveTo()", "Path2D.moveTo()")}} - : Moves the starting point of a new sub-path to the (`x, y`) coordinates. - {{domxref("CanvasRenderingContext2D.lineTo()", "Path2D.lineTo()")}} - : Connects the last point in the subpath to the (`x, y`) coordinates with a straight line. - {{domxref("CanvasRenderingContext2D.bezierCurveTo()", "Path2D.bezierCurveTo()")}} - : Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using `moveTo()` before creating the Bézier curve. - {{domxref("CanvasRenderingContext2D.quadraticCurveTo()", "Path2D.quadraticCurveTo()")}} - : Adds a quadratic Bézier curve to the current path. - {{domxref("CanvasRenderingContext2D.arc()", "Path2D.arc()")}} - : Adds an arc to the path which is centered at (`x, y`) position with radius `r` starting at `startAngle` and ending at `endAngle` going in the given direction by `counterclockwise` (defaulting to clockwise). - {{domxref("CanvasRenderingContext2D.arcTo()", "Path2D.arcTo()")}} - : Adds a circular arc to the path with the given control points and radius, connected to the previous point by a straight line. - {{domxref("CanvasRenderingContext2D.ellipse()", "Path2D.ellipse()")}} - : Adds an elliptical arc to the path which is centered at (`x, y`) position with the radii `radiusX` and `radiusY` starting at `startAngle` and ending at `endAngle` going in the given direction by `counterclockwise` (defaulting to clockwise). - {{domxref("CanvasRenderingContext2D.rect()", "Path2D.rect()")}} - : Creates a path for a rectangle at position (`x, y`) with a size that is determined by `width` and `height`. - {{domxref("CanvasRenderingContext2D.roundRect()", "Path2D.roundRect()")}} - : Creates a path for a rounded rectangle at position (`x, y`) with a size that is determined by `width` and `height` and the radii of the circular arc to be used for the corners of the rectangle is determined by `radii`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/path2d
data/mdn-content/files/en-us/web/api/path2d/addpath/index.md
--- title: "Path2D: addPath() method" short-title: addPath() slug: Web/API/Path2D/addPath page-type: web-api-instance-method browser-compat: api.Path2D.addPath --- {{APIRef("Canvas API")}} The **`Path2D.addPath()`** method of the Canvas 2D API adds one {{domxref("Path2D")}} object to another `Path2D` object. ## Syntax ```js-nolint addPath(path) addPath(path, transform) ``` ### Parameters - `path` - : A {{domxref("Path2D")}} path to add. - `transform` {{optional_inline}} - : A {{domxref("DOMMatrix")}} to be used as the transformation matrix for the path that is added. (Technically a `DOMMatrixInit` object). ### Return value None ({{jsxref("undefined")}}). ## Examples ### Adding a path to an existing path This example adds one path to another. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript First, we create two separate {{domxref("Path2D")}} objects, each of which contains a rectangle made using the {{domxref("CanvasRenderingContext2D.rect()", "rect()")}} method. We then create a matrix using {{Domxref("DOMMatrix.DOMMatrix", "DOMMatrix()")}}. We then add the second path to the first using `addPath()`, also applying the matrix to move the second path to the right. Finally, we draw the first path (which now contains both rectangles) using {{domxref("CanvasRenderingContext2D.fill()", "fill()")}}. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create first path and add a rectangle let p1 = new Path2D(); p1.rect(0, 0, 100, 150); // Create second path and add a rectangle let p2 = new Path2D(); p2.rect(0, 0, 100, 75); // Create transformation matrix that moves 200 points to the right let m = new DOMMatrix(); m.a = 1; m.b = 0; m.c = 0; m.d = 1; m.e = 200; m.f = 0; // Add second path to the first path p1.addPath(p2, m); // Draw the first path ctx.fill(p1); ``` #### Result {{ EmbedLiveSample('Adding_a_path_to_an_existing_path', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("Path2D")}}
0
data/mdn-content/files/en-us/web/api/path2d
data/mdn-content/files/en-us/web/api/path2d/path2d/index.md
--- title: "Path2D: Path2D() constructor" short-title: Path2D() slug: Web/API/Path2D/Path2D page-type: web-api-constructor browser-compat: api.Path2D.Path2D --- {{APIRef("Canvas API")}} The **`Path2D()`** constructor returns a newly instantiated `Path2D` object, optionally with another path as an argument (creates a copy), or optionally with a string consisting of [SVG path](/en-US/docs/Web/SVG/Tutorial/Paths) data. ## Syntax ```js-nolint new Path2D() new Path2D(path) new Path2D(d) ``` ### Parameters - `path` {{optional_inline}} - : When invoked with another `Path2D` object, a copy of the `path` argument is created. - `d` {{optional_inline}} - : When invoked with a string consisting of [SVG path](/en-US/docs/Web/SVG/Tutorial/Paths) data, a new path is created from that description. ## Examples ### Creating and copying paths This example creates and copies a `Path2D` path. ```html hidden <canvas id="canvas"></canvas> ``` ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let path1 = new Path2D(); path1.rect(10, 10, 100, 100); let path2 = new Path2D(path1); path2.moveTo(220, 60); path2.arc(170, 60, 50, 0, 2 * Math.PI); ctx.stroke(path2); ``` {{ EmbedLiveSample('Creating_and_copying_paths', 700, 180) }} ### Using SVG paths This example creates a `Path2D` path using [SVG path data](/en-US/docs/Web/SVG/Tutorial/Paths). The path will move to point (`M10 10`) and then move horizontally 80 points to the right (`h 80`), then 80 points down (`v 80`), then 80 points to the left (`h -80`), and then back to the start (`Z`). ```html hidden <canvas id="canvas"></canvas> ``` ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let p = new Path2D("M10 10 h 80 v 80 h -80 Z"); ctx.fill(p); ``` {{ EmbedLiveSample('Using_SVG_paths', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Path2D")}}, the interface this constructor belongs to
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/force_touch_events/index.md
--- title: Force Touch events slug: Web/API/Force_Touch_events page-type: web-api-overview status: - non-standard --- {{DefaultAPISidebar("Force Touch Events")}}{{Non-standard_header}} **Force Touch Events** are a proprietary, Apple-specific feature which makes possible (where supported by the input hardware) new interactions based on how hard the user clicks or presses down on the touchscreen or trackpad. ## Events - {{domxref("Element/webkitmouseforcewillbegin_event", "webkitmouseforcewillbegin")}} {{non-standard_inline}} - : This event is fired before the {{domxref("Element/mousedown_event", "mousedown")}} event. Its main use is that it can be {{domxref("Event.preventDefault()")}}ed. - {{domxref("Element/webkitmouseforcedown_event", "webkitmouseforcedown")}} {{non-standard_inline}} - : This event is fired after the {{domxref("Element/mousedown_event", "mousedown")}} event as soon as sufficient pressure has been applied for it to qualify as a "force click". - {{domxref("Element/webkitmouseforceup_event", "webkitmouseforceup")}} {{non-standard_inline}} - : This event is fired after the {{domxref("Element/webkitmouseforcedown_event", "webkitmouseforcedown")}} event as soon as the pressure has been reduced sufficiently to end the "force click". - {{domxref("Element/webkitmouseforcechanged_event", "webkitmouseforcechanged")}} {{non-standard_inline}} - : This event is fired each time the amount of pressure changes. This event first fires after the {{domxref("Element/mousedown_event", "mousedown")}} event and stops firing before the {{domxref("Element/mouseup_event", "mouseup")}} event. ## Event properties The following property is known to be available on the {{domxref("Element/webkitmouseforcewillbegin_event", "webkitmouseforcewillbegin")}}, {{domxref("Element/mousedown_event", "mousedown")}}, {{domxref("Element/webkitmouseforcechanged_event", "webkitmouseforcechanged")}}, {{domxref("Element/webkitmouseforcedown_event", "webkitmouseforcedown")}}, {{domxref("Element/webkitmouseforceup_event", "webkitmouseforceup")}}, {{domxref("Element/mousemove_event", "mousemove")}}, and {{domxref("Element/mouseup_event", "mouseup")}} event objects: - {{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The amount of pressure currently being applied to the trackpad/touchscreen. ## Constants These constants are useful for determining the relative intensity of the pressure indicated by {{domxref("MouseEvent.webkitForce")}}: - {{domxref("MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN_static", "MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN")}} {{non-standard_inline}} {{ReadOnlyInline}} - : Minimum force necessary for a normal click. - {{domxref("MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN_static", "MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN")}} {{non-standard_inline}} {{ReadOnlyInline}} - : Minimum force necessary for a force click. ## Specifications _Not part of any specification._ Apple has [a description at the Mac Developer Library](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/SafariJSProgTopics/RespondingtoForceTouchEventsfromJavaScript.html).
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/mediaquerylist/index.md
--- title: MediaQueryList slug: Web/API/MediaQueryList page-type: web-api-interface browser-compat: api.MediaQueryList --- {{APIRef("CSSOM")}} A **`MediaQueryList`** object stores information on a [media query](/en-US/docs/Web/CSS/CSS_media_queries) applied to a document, with support for both immediate and event-driven matching against the state of the document. You can create a `MediaQueryList` by calling {{DOMxRef("Window.matchMedia", "matchMedia()")}} on the {{DOMxRef("window")}} object. The resulting object handles sending notifications to listeners when the media query state changes (i.e. when the media query test starts or stops evaluating to `true`). This is very useful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status. {{InheritanceDiagram}} ## Instance properties _The `MediaQueryList` interface inherits properties from its parent interface, {{DOMxRef("EventTarget")}}._ - {{DOMxRef("MediaQueryList.matches", "matches")}} {{ReadOnlyInline}} - : A boolean value that returns `true` if the {{DOMxRef("document")}} currently matches the media query list, or `false` if not. - {{DOMxRef("MediaQueryList.media", "media")}} {{ReadOnlyInline}} - : A string representing a serialized media query. ## Instance methods _The `MediaQueryList` interface inherits methods from its parent interface, {{DOMxRef("EventTarget")}}._ - {{DOMxRef("MediaQueryList.addListener", "addListener()")}} {{deprecated_inline}} - : Adds to the `MediaQueryList` a callback which is invoked whenever the media query status—whether or not the document matches the media queries in the list—changes. This method exists primarily for backward compatibility; if possible, you should instead use {{domxref("EventTarget.addEventListener", "addEventListener()")}} to watch for the {{domxref("MediaQueryList.change_event", "change")}} event. - {{DOMxRef("MediaQueryList.removeListener", "removeListener()")}} {{deprecated_inline}} - : Removes the specified listener callback from the callbacks to be invoked when the `MediaQueryList` changes media query status, which happens any time the document switches between matching and not matching the media queries listed in the `MediaQueryList`. This method has been kept for backward compatibility; if possible, you should generally use {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} to remove change notification callbacks (which should have previously been added using `addEventListener()`). ## Events _The following events are delivered to `MediaQueryList` objects:_ - {{DOMxRef("MediaQueryList.change_event", "change")}} - : Sent to the `MediaQueryList` when the result of running the media query against the document changes. For example, if the media query is `(min-width: 400px)`, the `change` event is fired any time the width of the document's {{Glossary("viewport")}} changes such that its width moves across the 400px boundary in either direction. ## Examples This simple example creates a `MediaQueryList` and then sets up a listener to detect when the media query status changes, running a custom function when it does to change the appearance of the page. ```js const para = document.querySelector("p"); const mql = window.matchMedia("(max-width: 600px)"); function screenTest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textContent = "This is a narrow screen — less than 600px wide."; document.body.style.backgroundColor = "red"; } else { /* the viewport is more than 600 pixels wide */ para.textContent = "This is a wide screen — more than 600px wide."; document.body.style.backgroundColor = "blue"; } } mql.addEventListener("change", screenTest); ``` > **Note:** You can find this example on GitHub (see the [source code](https://github.com/mdn/dom-examples/blob/main/mediaquerylist/index.html), and also see it [running live](https://mdn.github.io/dom-examples/mediaquerylist/index.html)). You can find other examples on the individual property and method pages. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) - {{DOMxRef("window.matchMedia()")}} - {{DOMxRef("MediaQueryListEvent")}} - The article {{DOMxRef("Window.devicePixelRatio")}} also has a useful example
0
data/mdn-content/files/en-us/web/api/mediaquerylist
data/mdn-content/files/en-us/web/api/mediaquerylist/media/index.md
--- title: "MediaQueryList: media property" short-title: media slug: Web/API/MediaQueryList/media page-type: web-api-instance-property browser-compat: api.MediaQueryList.media --- {{APIRef("CSSOM")}} The **`media`** read-only property of the {{DOMxRef("MediaQueryList")}} interface is a string representing a serialized media query. ## Value A string representing a serialized media query. ## Examples This example runs the media query `(max-width: 600px)` and displays the value of the resulting `MediaQueryList`'s `media` property in a {{HTMLElement("span")}}. ### JavaScript ```js let mql = window.matchMedia("(max-width: 600px)"); document.querySelector(".mq-value").innerText = mql.media; ``` The JavaScript code passes the media query to match into {{DOMxRef("Window.matchMedia", "matchMedia()")}} to compile it, then sets the `<span>`'s {{DOMxRef("HTMLElement.innerText", "innerText")}} to the value of the result's {{DOMxRef("MediaQueryList.media", "media")}} property. ### HTML ```html <span class="mq-value"></span> ``` A simple `<span>` to receive the output. ```css hidden .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde; } ``` ### Result {{EmbedLiveSample("Examples", "100%", "60")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) - {{DOMxRef("window.matchMedia()")}} - {{DOMxRef("MediaQueryList")}} - {{DOMxRef("MediaQueryListEvent")}}
0
data/mdn-content/files/en-us/web/api/mediaquerylist
data/mdn-content/files/en-us/web/api/mediaquerylist/removelistener/index.md
--- title: "MediaQueryList: removeListener() method" short-title: removeListener() slug: Web/API/MediaQueryList/removeListener page-type: web-api-instance-method status: - deprecated browser-compat: api.MediaQueryList.removeListener --- {{APIRef("CSSOM")}}{{Deprecated_Header}} The **`removeListener()`** method of the {{DOMxRef("MediaQueryList")}} interface removes a listener from the `MediaQueryListener`. In older browsers `MediaQueryList` did not yet inherit from {{DOMxRef("EventTarget")}}, so this method was provided as an alias of {{DOMxRef("EventTarget.removeEventListener()")}}. Use `removeEventListener()` instead of `removeListener()` if it is available in the browsers you need to support. ## Syntax ```js-nolint removeListener(func) ``` ### Parameters - `func` - : A function or function reference representing the callback function you want to remove. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const paragraph = document.querySelector("p"); const mediaQueryList = window.matchMedia("(max-width: 600px)"); function screenTest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ paragraph.textContent = "This is a narrow screen — 600px wide or less."; document.body.style.backgroundColor = "pink"; } else { /* the viewport is more than 600 pixels wide */ paragraph.textContent = "This is a wide screen — more than 600px wide."; document.body.style.backgroundColor = "aquamarine"; } } mediaQueryList.addListener(screenTest); // Later on, when it is no longer needed mediaQueryList.removeListener(screenTest); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) - {{DOMxRef("window.matchMedia()")}} - {{DOMxRef("MediaQueryList")}} - {{DOMxRef("MediaQueryListEvent")}}
0
data/mdn-content/files/en-us/web/api/mediaquerylist
data/mdn-content/files/en-us/web/api/mediaquerylist/change_event/index.md
--- title: "MediaQueryList: change event" short-title: change slug: Web/API/MediaQueryList/change_event page-type: web-api-event browser-compat: api.MediaQueryList.change_event --- {{APIRef("CSSOM")}} The **`change`** event of the {{DOMxRef("MediaQueryList")}} interface fires when the status of media query support changes. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("change", (event) => {}); onchange = (event) => {}; ``` ## Event type A {{domxref("MediaQueryListEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MediaQueryListEvent")}} ## Event properties _The `MediaQueryListEvent` interface inherits properties from its parent interface, {{DOMxRef("Event")}}._ - {{DOMxRef("MediaQueryListEvent.matches")}} {{ReadOnlyInline}} - : A boolean value that is `true` if the {{DOMxRef("document")}} currently matches the media query list, or `false` if not. - {{DOMxRef("MediaQueryListEvent.media")}} {{ReadOnlyInline}} - : A string representing a serialized media query. ## Example ```js const mql = window.matchMedia("(max-width: 600px)"); mql.onchange = (e) => { if (e.matches) { /* the viewport is 600 pixels wide or less */ console.log("This is a narrow screen — less than 600px wide."); } else { /* the viewport is more than 600 pixels wide */ console.log("This is a wide screen — more than 600px wide."); } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) - {{DOMxRef("window.matchMedia()")}} - {{DOMxRef("MediaQueryList")}} - {{DOMxRef("MediaQueryListEvent")}}
0
data/mdn-content/files/en-us/web/api/mediaquerylist
data/mdn-content/files/en-us/web/api/mediaquerylist/addlistener/index.md
--- title: "MediaQueryList: addListener() method" short-title: addListener() slug: Web/API/MediaQueryList/addListener page-type: web-api-instance-method status: - deprecated browser-compat: api.MediaQueryList.addListener --- {{APIRef("CSSOM")}}{{Deprecated_Header}} The deprecated **`addListener()`** method of the {{DOMxRef("MediaQueryList")}} interface adds a listener to the `MediaQueryListener` that will run a custom callback function in response to the media query status changing. In older browsers `MediaQueryList` did not yet inherit from {{DOMxRef("EventTarget")}}, so this method was provided as an alias of {{DOMxRef("EventTarget.addEventListener()")}}. Use `addEventListener()` instead of `addListener()` if it is available in the browsers you need to support. ## Syntax ```js-nolint addListener(func) ``` ### Parameters - `func` - : A function or function reference representing the callback function you want to run when the media query status changes. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const paragraph = document.querySelector("p"); const mediaQueryList = window.matchMedia("(max-width: 600px)"); function screenTest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ paragraph.textContent = "This is a narrow screen — 600px wide or less."; document.body.style.backgroundColor = "pink"; } else { /* the viewport is more than 600 pixels wide */ paragraph.textContent = "This is a wide screen — more than 600px wide."; document.body.style.backgroundColor = "aquamarine"; } } mediaQueryList.addListener(screenTest); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) - {{DOMxRef("window.matchMedia()")}} - {{DOMxRef("MediaQueryList")}} - {{DOMxRef("MediaQueryListEvent")}}
0
data/mdn-content/files/en-us/web/api/mediaquerylist
data/mdn-content/files/en-us/web/api/mediaquerylist/matches/index.md
--- title: "MediaQueryList: matches property" short-title: matches slug: Web/API/MediaQueryList/matches page-type: web-api-instance-property browser-compat: api.MediaQueryList.matches --- {{APIRef("CSSOM")}} The **`matches`** read-only property of the {{DOMxRef("MediaQueryList")}} interface is a boolean value that returns `true` if the {{DOMxRef("document")}} currently matches the media query list, or `false` if not. You can be notified when the value of `matches` changes by watching for the {{domxref("MediaQueryList.change_event", "change")}} event to be fired at the `MediaQueryList`. ## Value A boolean value that is `true` if the {{DOMxRef("document")}} currently matches the media query list; otherwise, it's `false`. ## Examples This example detects viewport orientation changes by creating a media query using the [`orientation`](/en-US/docs/Web/CSS/@media/orientation) media feature: ```js const mql = window.matchMedia("(orientation:landscape)"); mql.addEventListener("change", (event) => { if (event.matches) { console.log("Now in landscape orientation"); } else { console.log("Now in portrait orientation"); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) - {{DOMxRef("window.matchMedia()")}} - {{DOMxRef("MediaQueryList")}} - {{DOMxRef("MediaQueryListEvent")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/csspropertyrule/index.md
--- title: CSSPropertyRule slug: Web/API/CSSPropertyRule page-type: web-api-interface browser-compat: api.CSSPropertyRule --- {{APIRef("CSS Properties and Values API")}} The **`CSSPropertyRule`** interface of the [CSS Properties and Values API](/en-US/docs/Web/API/CSS_Properties_and_Values_API) represents a single CSS {{cssxref("@property")}} rule. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its ancestor {{domxref("CSSRule")}}._ - {{domxref("CSSPropertyRule.inherits")}} {{ReadOnlyInline}} - : Returns the inherit flag of the custom property. - {{domxref("CSSPropertyRule.initialvalue")}} {{ReadOnlyInline}} - : Returns the initial value of the custom property. - {{domxref("CSSPropertyRule.name")}} {{ReadOnlyInline}} - : Returns the name of the custom property. - {{domxref("CSSPropertyRule.syntax")}} {{ReadOnlyInline}} - : Returns the literal syntax of the custom property. ## Instance methods _No specific methods; inherits methods from its ancestor {{domxref("CSSRule")}}._ ## Examples This stylesheet contains a single {{cssxref("@property")}} rule. The first {{domxref("CSSRule")}} returned will be a `CSSPropertyRule` with the properties and values as defined by the rule in CSS. ```css @property --property-name { syntax: "<color>"; inherits: false; initial-value: #c0ffee; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0]); //a CSSPropertyRule ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csspropertyrule
data/mdn-content/files/en-us/web/api/csspropertyrule/name/index.md
--- title: "CSSPropertyRule: name property" short-title: name slug: Web/API/CSSPropertyRule/name page-type: web-api-instance-property browser-compat: api.CSSPropertyRule.name --- {{APIRef("CSS Properties and Values API")}} The read-only **`name`** property of the {{domxref("CSSPropertyRule")}} interface represents the property name, this being the serialization of the name given to the custom property in the {{cssxref("@property")}} rule's prelude. ## Value A string. ## Examples This stylesheet contains a single {{cssxref("@property")}} rule. The first {{domxref("CSSRule")}} returned will be a `CSSPropertyRule` representing this rule. The `name` property returns the string `"--property-name"`, which is the name given to the custom property in CSS. ```css @property --property-name { syntax: "<color>"; inherits: false; initial-value: #c0ffee; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].name); //the string "--property-name" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csspropertyrule
data/mdn-content/files/en-us/web/api/csspropertyrule/initialvalue/index.md
--- title: "CSSPropertyRule: initialValue property" short-title: initialValue slug: Web/API/CSSPropertyRule/initialvalue page-type: web-api-instance-property browser-compat: api.CSSPropertyRule.initialValue --- {{APIRef("CSS Properties and Values API")}} The read-only **`initialValue`** nullable property of the {{domxref("CSSPropertyRule")}} interface returns the initial value of the custom property registration represented by the {{cssxref("@property")}} rule, controlling the property's initial value. ## Value A string which is a {{CSSXref("&lt;declaration-value&gt;")}} as defined in [CSS Syntax 3](https://www.w3.org/TR/css-syntax-3/#typedef-declaration-value). ## Examples This stylesheet contains a single {{cssxref("@property")}} rule. The first {{domxref("CSSRule")}} returned will be a `CSSPropertyRule` representing this rule. The `initialValue` property returns the string `"#c0ffee"` this being the value of the `initial-value` property in the CSS. ```css @property --property-name { syntax: "<color>"; inherits: false; initial-value: #c0ffee; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].initialValue); //the string "#c0ffee" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csspropertyrule
data/mdn-content/files/en-us/web/api/csspropertyrule/syntax/index.md
--- title: "CSSPropertyRule: syntax property" short-title: syntax slug: Web/API/CSSPropertyRule/syntax page-type: web-api-instance-property browser-compat: api.CSSPropertyRule.syntax --- {{APIRef("CSS Properties and Values API")}} The read-only **`syntax`** property of the {{domxref("CSSPropertyRule")}} interface returns the literal syntax of the custom property registration represented by the {{cssxref("@property")}} rule, controlling how the property's value is parsed at computed-value time. ## Value A string. ## Examples This stylesheet contains a single {{cssxref("@property")}} rule. The first {{domxref("CSSRule")}} returned will be a `CSSPropertyRule` representing this rule. The `syntax` property returns the literal string `"<color>"`. ```css @property --property-name { syntax: "<color>"; inherits: false; initial-value: #c0ffee; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].syntax); //the string "<color>" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csspropertyrule
data/mdn-content/files/en-us/web/api/csspropertyrule/inherits/index.md
--- title: "CSSPropertyRule: inherits property" short-title: inherits slug: Web/API/CSSPropertyRule/inherits page-type: web-api-instance-property browser-compat: api.CSSPropertyRule.inherits --- {{APIRef("CSS Properties and Values API")}} The read-only **`inherits`** property of the {{domxref("CSSPropertyRule")}} interface returns the inherit flag of the custom property registration represented by the {{cssxref("@property")}} rule, a boolean describing whether or not the property inherits by default. ## Value A boolean. ## Examples This stylesheet contains a single {{cssxref("@property")}} rule. The first {{domxref("CSSRule")}} returned will be a `CSSPropertyRule` representing this rule. The `inherits` property returns the boolean `false`, this being the value of the `inherits` property in the CSS. ```css @property --property-name { syntax: "<color>"; inherits: false; initial-value: #c0ffee; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].inherits); //returns false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpusupportedfeatures/index.md
--- title: GPUSupportedFeatures slug: Web/API/GPUSupportedFeatures page-type: web-api-interface status: - experimental browser-compat: api.GPUSupportedFeatures --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPUSupportedFeatures`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} is a [`Set`-like object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_browser_apis) that describes additional functionality supported by a {{domxref("GPUAdapter")}}. The `GPUSupportedFeatures` object for the current adapter is accessed via the {{domxref("GPUAdapter.features")}} property. You should note that not all features will be available to WebGPU in all browsers that support it, even if the features are supported by the underlying hardware. This could be due to constraints in the underlying system, browser, or adapter. For example: - The underlying system might not be able to guarantee exposure of a feature in a way that is compatible with a certain browser. - The browser vendor might not have found a secure way to implement support for that feature, or might just not have gotten round to it yet. If you are hoping to take advantage of a specific additional feature in a WebGPU app, thorough testing is advised. {{InheritanceDiagram}} ## Available features We have not listed the exact set of additional features available to be used in WebGPU, as it will vary between implementations and physical devices, and will change over time. For a list, refer to the [Feature Index](https://gpuweb.github.io/gpuweb/#feature-index) in the specification. ## Instance properties The following properties are available to all read-only [`Set`-like objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_browser_apis) (the links below are to the {{jsxref("Set")}} global object reference page). - {{jsxref("Set.prototype.size", "size")}} {{Experimental_Inline}} - : Returns the number of values in the set. ## Instance methods The following methods are available to all read-only [`Set`-like objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_browser_apis) (the below links are to the {{jsxref("Set")}} global object reference page). - {{jsxref("Set.prototype.has()", "has()")}} {{Experimental_Inline}} - : Returns a boolean asserting whether an element is present with the given value in the set or not. - {{jsxref("Set.prototype.values()", "values()")}} {{Experimental_Inline}} - : Returns a new iterator object that yields the **values** for each element in the set in insertion order. - {{jsxref("Set.prototype.keys()", "keys()")}} {{Experimental_Inline}} - : An alias for {{jsxref("Set.prototype.values()", "values()")}}. - {{jsxref("Set.prototype.entries()", "entries()")}} {{Experimental_Inline}} - : Returns a new iterator object that contains **an array of `[value, value]`** for each element in the set, in insertion order. - {{jsxref("Set.prototype.forEach()", "forEach()")}} {{Experimental_Inline}} - : Calls a provided callback function once for each value present in the set, in insertion order. ## Examples ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const adapterFeatures = adapter.features; // Return the size of the set console.log(adapterFeatures.size); // Check whether a feature is supported by the adapter console.log(adapterFeatures.has("texture-compression-astc")); // Iterate through all the set values using values() const valueIterator = adapterFeatures.values(); for (const value of valueIterator) { console.log(value); } // Iterate through all the set values using keys() const keyIterator = adapterFeatures.keys(); for (const value of keyIterator) { console.log(value); } // Iterate through all the set values using entries() const entryIterator = adapterFeatures.entries(); for (const entry of entryIterator) { console.log(entry[0]); } // Iterate through all the set values using forEach() adapterFeatures.forEach((value) => { console.log(value); }); //... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrsystem/index.md
--- title: XRSystem slug: Web/API/XRSystem page-type: web-api-interface status: - experimental browser-compat: api.XRSystem --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}}{{SeeCompatTable}} The [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) interface **`XRSystem`** provides methods which let you get access to an {{domxref("XRSession")}} object representing a WebXR session. With that `XRSession` in hand, you can use it to interact with the Augmented Reality (AR) or Virtual Reality (VR) device. {{InheritanceDiagram}} ## Instance properties _While `XRSystem` directly offers no properties, it does inherit properties from its parent interface, {{domxref("EventTarget")}}._ ## Instance methods _In addition to inheriting methods from its parent interface, {{domxref("EventTarget")}}, the `XRSystem` interface includes the following methods:_ - {{DOMxRef("XRSystem.isSessionSupported", "isSessionSupported()")}} {{Experimental_Inline}} - : Returns a promise which resolves to `true` if the browser supports the given session mode. Resolves to `false` if the specified mode isn't supported. - {{DOMxRef("XRSystem.requestSession", "requestSession()")}} {{Experimental_Inline}} - : Returns a promise that resolves to a new {{DOMxRef("XRSession")}} with the specified session mode. ## Events - {{domxref("XRSystem.devicechange_event", "devicechange")}} {{Experimental_Inline}} - : Sent when the set of available XR devices has changed. Also available using the `ondevicechange` event handler. ## Usage notes This interface was previously known as `XR` in earlier versions of the specification; if you see references to `XR` in code or documentation, replace that with `XRSystem`. ## Examples The following example shows how to use both {{domxref("XRSystem.isSessionSupported", "isSessionSupported()")}} and {{domxref("XRSystem.requestSession", "requestSession()")}}. ```js if (navigator.xr) { immersiveButton.addEventListener("click", onButtonClicked); navigator.xr.isSessionSupported("immersive-vr").then((isSupported) => { immersiveButton.disabled = !isSupported; }); } function onButtonClicked() { if (!xrSession) { navigator.xr.requestSession("immersive-vr").then((session) => { // onSessionStarted() not shown for reasons of brevity and clarity. onSessionStarted(session); }); } else { // Shut down the already running XRSession xrSession.end().then(() => { // Since there are cases where the end event is not sent, call the handler here as well. onSessionEnded(); }); } } ``` This code starts by checking to see if WebXR is available by looking for the {{domxref("navigator.xr")}} property. If it's found, we know WebXR is present, so we proceed by establishing a handler for the button which the user can click to toggle immersive VR mode on and off. However, we don't yet know if the desired immersive mode is available. To determine this, we call `isSessionSupported()`, passing it the desired session option before enabling the button, `immersiveButton`, which the user can then use to switch to immersive mode only if immersive VR mode is available. If immersive VR isn't available, the button is disabled to prevent its use. The `onButtonClicked()` function checks to see if there's already a session running. If there isn't, we use `requestSession()` to start one and, once the returned promise resolves, we call a function `onSessionStarted()` to set up our session for rendering and so forth. If, on the other hand, there is already an ongoing XR session, we instead call {{domxref("XRSession.end", "end()")}} to end the current session. When the current session ends, the {{domxref("XRSession.end_event", "end")}} event is sent, so set `xrSession` to `null` in its handler to record the fact that we no longer have an ongoing session. That way, if the user clicks the button again, a new session will start. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrsystem
data/mdn-content/files/en-us/web/api/xrsystem/devicechange_event/index.md
--- title: "XRSystem: devicechange event" short-title: devicechange slug: Web/API/XRSystem/devicechange_event page-type: web-api-event status: - experimental browser-compat: api.XRSystem.devicechange_event --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} A **`devicechange`** event is fired on an {{DOMxRef("XRSystem")}} object whenever the availability of immersive XR devices has changed; for example, a VR headset or AR goggles have been connected or disconnected. It's a generic {{DOMxRef("Event")}} with no added properties. > **Note:** Not to be confused with the {{domxref("MediaDevices")}} {{DOMxRef("MediaDevices.devicechange_event", "devicechange")}} event. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("devicechange", (event) => {}); ondevicechange = (event) => {}; ``` If the use of WebXR has been blocked by an `xr-spatial-tracking` [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy), `devicechange` events will not fire. ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Description ### Trigger Triggered whenever the availability of immersive XR devices has changed. For example, when a VR headset or AR goggles have been connected or disconnected. ### Use cases You can use this event to, for example, monitor for the availability of a WebXR-compatible device so that you can enable a UI element which the user can use to activate immersive mode. This is shown in the [example](#examples) below. ## Examples The example shown here handles the `devicechange` event by toggling the availability of the "Enter XR" button based on whether or not any immersive devices are currently available. ```js if (navigator.xr) { navigator.xr.addEventListener("devicechange", (event) => { navigator.xr.isSessionSupported("immersive-vr").then((immersiveOK) => { enableXRButton.disabled = !immersiveOK; }); }); } ``` When `devicechange` is received, the handler set up in this code calls the `XR` method {{domxref("XRSystem.isSessionSupported", "isSessionSupported()")}} to find out if there's a device available that can handle immersive VR presentations. If there is, the button to enter XR mode is enabled; otherwise it's disabled. You can also use the `ondevicechange` event handler property to set a single handler for `devicechange` events: ```js if (navigator.xr) { navigator.xr.ondevicechange = (event) => { // … }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrsystem
data/mdn-content/files/en-us/web/api/xrsystem/requestsession/index.md
--- title: "XRSystem: requestSession() method" short-title: requestSession() slug: Web/API/XRSystem/requestSession page-type: web-api-instance-method status: - experimental browser-compat: api.XRSystem.requestSession --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **{{domxref("XRSystem")}}** interface's **`requestSession()`** method returns a {{jsxref("promise")}} which resolves to an {{domxref("XRSession")}} object through which you can manage the requested type of WebXR session. While only one immersive VR session can be active at a time, multiple inline sessions can be in progress at once. ## Syntax ```js-nolint requestSession(mode) requestSession(mode, options) ``` ### Parameters - `mode` - : A {{jsxref("String")}} defining the XR session mode. The supported modes are: - {{Experimental_Inline}} `immersive-ar`: The session's output will be given exclusive access to the immersive device, but the rendered content will be blended with the real-world environment. The session's {{DOMxRef("XRSession.environmentBlendMode", "environmentBlendMode")}} indicates the method to be used to blend the content together. - `immersive-vr`: Indicates that the rendered session will be displayed using an immersive XR device in VR mode; it is not intended to be overlaid or integrated into the surrounding environment. The {{DOMxRef("XRSession.environmentBlendMode", "environmentBlendMode")}} is expected to be `opaque` if possible, but might be `additive` if the hardware requires it. - `inline`: The output is presented inline within the context of an element in a standard HTML document, rather than occupying the full visual space. Inline sessions can be presented in either mono or stereo mode, and may or may not have viewer tracking available. Inline sessions don't require special hardware and should be available on any {{Glossary("user agent")}} offering WebXR API support. - `options` {{Optional_Inline}} - : An object to configure the {{domxref("XRSession")}}. If none are included, the device will use a default feature configuration for all options. - `requiredFeatures` {{Optional_Inline}}: An array of values which the returned {{domxref("XRSession")}} _must_ support. See [Session features](#session_features) below. - `optionalFeatures` {{Optional_Inline}}: An array of values identifying features which the returned {{domxref("XRSession")}} may optionally support. See [Session features](#session_features) below. - `domOverlay` {{Optional_Inline}}: An object with a required `root` property that specifies the overlay element that will be displayed to the user as the content of the DOM overlay. See the [example below](#requesting_a_session_with_a_dom_overlay). - `depthSensing` {{Optional_Inline}}: An object with two required properties {{domxref("XRSession.depthUsage", "usagePreference")}} and {{domxref("XRSession.depthDataFormat", "dataFormatPreference")}} to configure how to perform depth sensing. See the [example below](#requesting_a_depth-sensing_session). ### Return value A {{jsxref("Promise")}} that resolves with an {{domxref("XRSession")}} object if the device and user agent support the requested mode and features. ### Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a {{domxref("DOMException")}} whose `name` is one of the following: - `InvalidStateError` {{domxref("DOMException")}} - : Returned if the requested session mode is `immersive-vr` but there is already an immersive VR session either currently active or in the process of being set up. There can only be one immersive VR session at a time. - `NotSupportedError` {{domxref("DOMException")}} - : Returned if there is no WebXR-compatible device available, or the device does not support the specified `sessionMode`; this can also be thrown if any of the _required_ options are unsupported. - `SecurityError` {{domxref("DOMException")}} - : Returned if permission to enter the specified XR mode is denied. This can happen for several reasons, which are covered in more detail in [Permissions and security](/en-US/docs/Web/API/WebXR_Device_API/Permissions_and_security). ## Session features The following session features and reference spaces can be requested, either as `optionalFeatures` or `requiredFeatures`. - `anchors` - : Enable use of {{domxref("XRAnchor")}} objects. - `bounded-floor` - : Similar to the `local` type, except the user is not expected to move outside a predetermined boundary, given by the {{domxref("XRBoundedReferenceSpace.boundsGeometry", "boundsGeometry")}} in the returned object. - `depth-sensing` - : Enable the ability to obtain depth information using {{domxref("XRDepthInformation")}} objects. - `dom-overlay` - : Enable allowing to specify a DOM overlay element that will be displayed to the user. - `hand-tracking` - : Enable articulated hand pose information from hand-based input controllers (see {{domxref("XRHand")}} and {{domxref("XRInputSource.hand")}}). - `hit-test` - : Enable hit testing features for performing hit tests against real-world geometry. - `layers` - : Enable the ability to create various layer types (other than {{domxref("XRProjectionLayer")}}). - `light-estimation` - : Enable the ability to estimate environmental lighting conditions using {{domxref("XRLightEstimate")}} objects. - `local` - : Enable a tracking space whose native origin is located near the viewer's position at the time the session was created. The exact position depends on the underlying platform and implementation. The user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. - `local-floor` - : Similar to the `local` type, except the starting position is placed in a safe location for the viewer to stand, where the value of the y axis is 0 at floor level. If that floor level isn't known, the {{Glossary("user agent")}} will estimate the floor level. If the estimated floor level is non-zero, the browser is expected to round it such a way as to avoid [fingerprinting](/en-US/docs/Glossary/Fingerprinting) (likely to the nearest centimeter). - `secondary-views` - : Enable {{domxref("XRView")}} objects to be secondary views. This can be used for first-person observer views used for video capture, or "quad views" where there are two views per eye, with differing resolution and fields of view. - `unbounded` - : Enable a tracking space which allows the user total freedom of movement, possibly over extremely long distances from their origin point. The viewer isn't tracked at all; tracking is optimized for stability around the user's current position, so the native origin may drift as needed to accommodate that need. - `viewer` - : Enable a tracking space whose native origin tracks the viewer's position and orientation. ## Security Several session features and the various reference spaces have minimum security and privacy requirements, like asking for user consent and/or requiring the {{HTTPHeader("Permissions-Policy")}}: [`xr-spatial-tracking`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/xr-spatial-tracking) directive to be set. See also [Permissions and security](/en-US/docs/Web/API/WebXR_Device_API/Permissions_and_security) for more details. | Session feature | User consent requirement | Permissions policy requirement | | --------------- | ----------------------------------- | ------------------------------ | | `bounded-floor` | Always required | `xr-spatial-tracking` | | `depth-sensing` | — | `xr-spatial-tracking` | | `hand-tracking` | Always required | — | | `hit-test` | — | `xr-spatial-tracking` | | `local` | Always required for inline sessions | `xr-spatial-tracking` | | `local-floor` | Always required | `xr-spatial-tracking` | | `unbounded` | Always required | `xr-spatial-tracking` | | `viewer` | Always required | — | See also [transient user activation](/en-US/docs/Web/Security/User_activation). ## Examples ### Creating an immersive VR session The following example calls `requestSession()` requesting an `"immersive-vr"` session. If the {{jsxref("Promise")}} resolves, it sets up a session and initiates the animation loop. ```js navigator.xr .requestSession("immersive-vr") .then((xrSession) => { xrSession.addEventListener("end", onXRSessionEnded); // Do necessary session setup here. // Begin the session's animation loop. xrSession.requestAnimationFrame(onXRAnimationFrame); }) .catch((error) => { // "immersive-vr" sessions are not supported console.error( "'immersive-vr' isn't supported, or an error occurred activating VR!", ); }); ``` ### Verifying WebXR support and using a button to start VR mode The following example shows how to use both `isSessionSupported()` and `requestSession()`. First, it checks to see if WebXR is available by verifying the existence of {{domxref("navigator.xr")}}. Next, it calls `isSessionSupported()`, passing it the desired session option before enabling controls for entering XR. Adding controls is a necessary step because entering XR requires a user action. Finally, the `onButtonClicked()` method calls `requestSession()` using the same session option passed to `isSessionSupported()`. ```js if (navigator.xr) { navigator.xr.isSessionSupported("immersive-vr").then((isSupported) => { if (isSupported) { immersiveButton.addEventListener("click", onButtonClicked); immersiveButton.textContent = "Enter XR"; immersiveButton.disabled = false; } else { console.error("WebXR doesn't support immersive-vr mode!"); } }); } else { console.error("WebXR is not available!"); } function onButtonClicked() { if (!xrSession) { navigator.xr.requestSession("immersive-vr").then((session) => { xrSession = session; // onSessionStarted() not shown for reasons of brevity and clarity. onSessionStarted(xrSession); }); } else { // Button is a toggle button. xrSession.end().then(() => (xrSession = null)); } } ``` ### Requesting a session with required features Require an unbounded experience in which the user is able to freely move around their physical environment: ```js navigator.xr.requestSession("immersive-vr", { requiredFeatures: ["unbounded"], }); ``` ### Requesting a session with a DOM overlay ```js navigator.xr.requestSession("immersive-ar", { optionalFeatures: ["dom-overlay"], domOverlay: { root: document.getElementById("xr-overlay"), }, }); ``` ### Requesting a depth-sensing session Here, the caller is able to handle both CPU- and GPU-optimized usage, as well as both "luminance-alpha" and "float32" formats. The order indicates preference for CPU and "luminance-alpha": ```js navigator.xr.requestSession("immersive-ar", { requiredFeatures: ["depth-sensing"], depthSensing: { usagePreference: ["cpu-optimized", "gpu-optimized"], dataFormatPreference: ["luminance-alpha", "float32"], }, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrsystem
data/mdn-content/files/en-us/web/api/xrsystem/issessionsupported/index.md
--- title: "XRSystem: isSessionSupported() method" short-title: isSessionSupported() slug: Web/API/XRSystem/isSessionSupported page-type: web-api-instance-method status: - experimental browser-compat: api.XRSystem.isSessionSupported --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The {{domxref("XRSystem")}} method **`isSessionSupported()`** returns a promise which resolves to `true` if the specified WebXR session mode is supported by the user's WebXR device. Otherwise, the promise resolves with `false`. If no devices are available or the browser doesn't have permission to use the XR device, the promise is rejected with an appropriate {{domxref("DOMException")}}. ## Syntax ```js-nolint isSessionSupported(mode) ``` ### Parameters - `mode` - : A {{jsxref("String")}} specifying the WebXR session mode for which support is to be checked. Possible modes to check for: - `immersive-ar` {{Experimental_Inline}} - `immersive-vr` - `inline` ### Return value A {{jsxref("Promise")}} that resolves to `true` if the specified session mode is supported; otherwise the promise resolves to `false`. ### Exceptions Rather than throwing true exceptions, `isSessionSupported()` rejects the returned promise, passing to the rejection handler a {{domxref("DOMException")}} whose `name` is one of the following strings. - `SecurityError` - : Use of this feature is blocked by an `xr-spatial-tracking` [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). ## Examples In this example, we see `isSessionSupported()` used to detect whether or not the device supports VR mode by checking to see if an `immersive-vr` session is supported. If it is, we set up a button to read "Enter XR", to call a method `onButtonClicked()`, and enable the button. If no session is already underway, we request the VR session and, if successful, set up the session in a method called `onSessionStarted()`, not shown. If a session _is_ already underway when the button is clicked, we call the `xrSession` object's {{domxref("XRSession.end", "end()")}} method to shut down the WebXR session. ```js if (navigator.xr) { navigator.xr.isSessionSupported("immersive-vr").then((isSupported) => { if (isSupported) { userButton.addEventListener("click", onButtonClicked); userButton.textContent = "Enter XR"; userButton.disabled = false; } }); } function onButtonClicked() { if (!xrSession) { navigator.xr.requestSession("immersive-vr").then((session) => { xrSession = session; // onSessionStarted() not shown for reasons of brevity and clarity. onSessionStarted(xrSession); }); } else { // Button is a toggle button. xrSession.end(); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/domhighrestimestamp/index.md
--- title: DOMHighResTimeStamp slug: Web/API/DOMHighResTimeStamp page-type: web-api-interface browser-compat: api.DOMHighResTimestamp --- {{APIRef("Performance API")}} The **`DOMHighResTimeStamp`** type is a `double` and is used to store a time value in milliseconds. This type can be used to describe a discrete point in time or a time interval (the difference in time between two discrete points in time). The starting time can be either a specific time determined by the script for a site or app, or the [time origin](/en-US/docs/Web/API/Performance/timeOrigin). The time, given in milliseconds, should be accurate to 5 µs (microseconds), with the fractional part of the number indicating fractions of a millisecond. However, if the browser is unable to provide a time value accurate to 5 µs (due, for example, to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond. Also note the section below on reduced time precision controlled by browser preferences to avoid timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting). Further, if the device or operating system the user agent is running on doesn't have a clock accurate to the microsecond level, they may only be accurate to the millisecond. ## Security requirements To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting), `DOMHighResTimeStamp` types are coarsened based on site isolation status. - Resolution in isolated contexts: 5 microseconds - Resolution in non-isolated contexts: 100 microseconds Cross-origin isolate your site using the {{HTTPHeader("Cross-Origin-Opener-Policy")}} and {{HTTPHeader("Cross-Origin-Embedder-Policy")}} headers: ```http Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp ``` These headers ensure a top-level document does not share a browsing context group with cross-origin documents. COOP process-isolates your document and potential attackers can't access to your global object if they were opening it in a popup, preventing a set of cross-origin attacks dubbed [XS-Leaks](https://github.com/xsleaks/xsleaks). ## See also - [`performance.now()`](/en-US/docs/Web/API/Performance/now) - [`performance.timeOrigin`](/en-US/docs/Web/API/Performance/timeOrigin)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/vttregion/index.md
--- title: VTTRegion slug: Web/API/VTTRegion page-type: web-api-interface browser-compat: api.VTTRegion --- {{APIRef("WebVTT")}} The `VTTRegion` interface—part of the API for handling WebVTT (text tracks on media presentations)—describes a portion of the video to render a {{domxref("VTTCue")}} onto. ## Constructor - {{domxref("VTTRegion.VTTRegion", "VTTRegion()")}} - : Returns a newly created `VTTRegion` object. ## Instance properties - {{domxref("VTTRegion.id")}} - : A string that identifies the region. - {{domxref("VTTRegion.width")}} - : A `double` representing the width of the region, as a percentage of the video. - {{domxref("VTTRegion.lines")}} - : A `double` representing the height of the region, in number of lines. - {{domxref("VTTRegion.regionAnchorX")}} - : A `double` representing the region anchor X offset, as a percentage of the region. - {{domxref("VTTRegion.regionAnchorY")}} - : A `double` representing the region anchor Y offset, as a percentage of the region. - {{domxref("VTTRegion.viewportAnchorX")}} - : A `double` representing the viewport anchor X offset, as a percentage of the video. - {{domxref("VTTRegion.viewportAnchorY")}} - : A `double` representing the viewport anchor Y offset, as a percentage of the video. - {{domxref("VTTRegion.scroll")}} - : An enum representing how adding new cues will move existing cues. ## Examples ```js const region = new VTTRegion(); region.width = 50; // Use 50% of the video width region.lines = 4; // Use 4 lines of height. region.viewportAnchorX = 25; // Have the region start at 25% from the left. const cue = new VTTCue(2, 3, "Cool text to be displayed"); cue.region = region; // This cue will be drawn only within this region. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrcpudepthinformation/index.md
--- title: XRCPUDepthInformation slug: Web/API/XRCPUDepthInformation page-type: web-api-interface status: - experimental browser-compat: api.XRCPUDepthInformation --- {{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}} The **`XRCPUDepthInformation`** interface contains depth information from the CPU (returned by {{domxref("XRFrame.getDepthInformation()")}}). {{InheritanceDiagram}} This interface inherits properties from its parent, {{domxref("XRDepthInformation")}}. ## Instance properties - {{domxref("XRCPUDepthInformation.data")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : An {{jsxref("ArrayBuffer")}} containing depth-buffer information in raw format. - {{domxref("XRDepthInformation.height")}} {{ReadOnlyInline}} - : Contains the height of the depth buffer (number of rows). - {{domxref("XRDepthInformation.normDepthBufferFromNormView")}} {{ReadOnlyInline}} - : An {{domxref("XRRigidTransform")}} that needs to be applied when indexing into the depth buffer. The transformation that the matrix represents changes the coordinate system from normalized view coordinates to normalized depth-buffer coordinates that can then be scaled by depth buffer's `width` and `height` to obtain the absolute depth-buffer coordinates. - {{domxref("XRDepthInformation.rawValueToMeters")}} {{ReadOnlyInline}} - : Contains the scale factor by which the raw depth values must be multiplied in order to get the depths in meters. - {{domxref("XRDepthInformation.width")}} {{ReadOnlyInline}} - : Contains the width of the depth buffer (number of columns). ## Instance methods - {{domxref("XRCPUDepthInformation.getDepthInMeters()")}} {{Experimental_Inline}} - : Returns the depth in meters at (x, y) in normalized view coordinates. ## Examples ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRDepthInformation")}} - {{domxref("XRWebGLDepthInformation")}} - {{domxref("XRFrame.getDepthInformation()")}}
0
data/mdn-content/files/en-us/web/api/xrcpudepthinformation
data/mdn-content/files/en-us/web/api/xrcpudepthinformation/data/index.md
--- title: "XRCPUDepthInformation: data property" short-title: data slug: Web/API/XRCPUDepthInformation/data page-type: web-api-instance-property status: - experimental browser-compat: api.XRCPUDepthInformation.data --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The _read-only_ **`data`** property of the {{DOMxRef("XRCPUDepthInformation")}} interface is an {{jsxref("ArrayBuffer")}} containing depth-buffer information in raw format. The data is stored in row-major format, without padding, with each entry corresponding to distance from the view's near plane to the users' environment, in unspecified units. The size of each data entry and the type is determined by {{domxref("XRSession.depthDataFormat", "depthDataFormat")}}. The values can be converted from unspecified units to meters by multiplying them by {{domxref("XRDepthInformation.rawValueToMeters", "rawValueToMeters")}}. The {{domxref("XRDepthInformation.normDepthBufferFromNormView", "normDepthBufferFromNormView")}} property can be used to transform from normalized view coordinates (an origin in the top left corner of the view, with X axis growing to the right, and Y axis growing downward) into the depth buffer's coordinate system. ## Value An {{jsxref("ArrayBuffer")}}. ## Examples Use {{domxref("XRFrame.getDepthInformation()")}} to obtain depth information. The returned `XRCPUDepthInformation` object will contain the `data` buffer. For CPU depth information and a buffer that has "luminance-alpha" format: ```js const uint16 = new Uint16Array(depthInfo.data); const index = column + row * depthInfo.width; const depthInMeters = uint16[index] * depthInfo.rawValueToMeters; ``` (Use {{jsxref("Float32Array")}} for a "float32" data format.) Note that the depth in meters is in depth-buffer coordinates. Additional steps are needed to convert them to normalized view coordinates, or the {{domxref("XRCPUDepthInformation.getDepthInMeters()")}} method can be used. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrcpudepthinformation
data/mdn-content/files/en-us/web/api/xrcpudepthinformation/getdepthinmeters/index.md
--- title: "XRCPUDepthInformation: getDepthInMeters() method" short-title: getDepthInMeters() slug: Web/API/XRCPUDepthInformation/getDepthInMeters page-type: web-api-instance-method status: - experimental browser-compat: api.XRCPUDepthInformation.getDepthInMeters --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`getDepthInMeters()`** method of the {{DOMxRef("XRCPUDepthInformation")}} interface returns the depth in meters at (x, y) in normalized view coordinates (origin in the top left corner). ## Syntax ```js-nolint getDepthInMeters(x, y) ``` ### Parameters - `x` - : X coordinate (origin at the left, grows to the right). - `y` - : Y coordinate (origin at the top, grows downward). ### Return value None ({{jsxref("undefined")}}). ### Exceptions - A {{jsxref("RangeError")}} is thrown if `x` or `y` are greater than 1.0 or less than 0.0. ## Examples ```js const distance = depthInfo.getDepthInMeters(x, y); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmllegendelement/index.md
--- title: HTMLLegendElement slug: Web/API/HTMLLegendElement page-type: web-api-interface browser-compat: api.HTMLLegendElement --- {{ APIRef("HTML DOM") }} The **`HTMLLegendElement`** is an interface allowing to access properties of the {{HTMLElement("legend")}} elements. It inherits properties and methods from the {{domxref("HTMLElement")}} interface. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLLegendElement.align")}} {{deprecated_inline}} - : A string representing the alignment relative to the form set. - {{domxref("HTMLLegendElement.form")}} {{ReadOnlyInline}} - : A {{domxref("HTMLFormElement")}} representing the form that this legend belongs to. If the legend has a fieldset element as its parent, then this attribute returns the same value as the **form** attribute on the parent fieldset element. Otherwise, it returns `null`. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{HTMLElement("legend")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgglyphrefelement/index.md
--- title: SVGGlyphRefElement slug: Web/API/SVGGlyphRefElement page-type: web-api-interface status: - deprecated browser-compat: api.SVGGlyphRefElement --- {{APIRef("SVG")}}{{Deprecated_Header}} The **`SVGGlyphRefElement`** interface corresponds to the {{SVGElement("glyphRef")}} elements. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGGlyphRefElement.glyphRef")}} {{Deprecated_Inline}} - : A string corresponding to the {{SVGAttr("glyphRef")}} attribute of the given element. - {{domxref("SVGGlyphRefElement.format")}} {{Deprecated_Inline}} - : A string corresponding to the {{SVGAttr("format")}} attribute of the given element. - {{domxref("SVGGlyphRefElement.x")}} {{Deprecated_Inline}} - : A float corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGGlyphRefElement.y")}} {{Deprecated_Inline}} - : A float corresponding to the {{SVGAttr("y")}} attribute of the given element. - {{domxref("SVGGlyphRefElement.dx")}} {{Deprecated_Inline}} - : A float corresponding to the {{SVGAttr("dx")}} attribute of the given element. - {{domxref("SVGGlyphRefElement.dy")}} {{Deprecated_Inline}} - : A float corresponding to the {{SVGAttr("dy")}} attribute of the given element. ## Instance methods _This interface has no methods but inherits methods from its parent, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("glyphRef")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/writablestreamdefaultcontroller/index.md
--- title: WritableStreamDefaultController slug: Web/API/WritableStreamDefaultController page-type: web-api-interface browser-compat: api.WritableStreamDefaultController --- {{APIRef("Streams")}} The **`WritableStreamDefaultController`** interface of the [Streams API](/en-US/docs/Web/API/Streams_API) represents a controller allowing control of a {{domxref("WritableStream")}}'s state. When constructing a `WritableStream`, the underlying sink is given a corresponding `WritableStreamDefaultController` instance to manipulate. ## Constructor None. `WritableStreamDefaultController` instances are created automatically during `WritableStream` construction. ## Instance properties - {{domxref("WritableStreamDefaultController.signal")}} {{ReadOnlyInline}} - : Returns the {{domxref("AbortSignal")}} associated with the controller. ## Instance methods - {{domxref("WritableStreamDefaultController.error()")}} - : Causes any future interactions with the associated stream to error. ## Examples ```js const writableStream = new WritableStream({ start(controller) { // do stuff with controller // error stream if necessary controller.error("My stream is broken"); }, write(chunk, controller) { // ... }, close(controller) { // ... }, abort(err) { // ... }, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/writablestreamdefaultcontroller
data/mdn-content/files/en-us/web/api/writablestreamdefaultcontroller/signal/index.md
--- title: "WritableStreamDefaultController: signal property" short-title: signal slug: Web/API/WritableStreamDefaultController/signal page-type: web-api-instance-property browser-compat: api.WritableStreamDefaultController.signal --- {{APIRef("Streams")}} The read-only **`signal`** property of the {{domxref("WritableStreamDefaultController")}} interface returns the {{domxref("AbortSignal")}} associated with the controller. ## Value An {{domxref("AbortSignal")}} object. ## Examples ### Aborting a long write operation In this example, we simulate a slow operation using a local sink: We do nothing when some data is written but to wait for a second. This gives us enough time to call the `writer.abort()` method and to immediately reject the promise. ```js const writingStream = new WritableStream({ // Define the slow local sink to simulate a long operation write(controller) { return new Promise((resolve, reject) => { controller.signal.addEventListener("abort", () => reject(controller.signal.reason), ); // Do nothing but wait with the data: it is a local sink setTimeout(resolve, 1000); // Timeout to simulate a slow operation }); }, }); // Perform the write const writer = writingStream.getWriter(); writer.write("Lorem ipsum test data"); // Abort the write manually await writer.abort("Manual abort!"); ``` ### Transferring the `AbortSignal` to the underlying layer In this example, we use the [Fetch API](/en-US/docs/Web/API/Fetch_API) to actually send the message to a server. The Fetch API also support {{domxref("AbortSignal")}}: It is possible to use the same object for both the `fetch` method and the {{domxref("WritableStreamDefaultController")}}. ```js const endpoint = "https://www.example.com/api"; // Fake URL for example purpose const writingStream = new WritableStream({ async write(chunk, controller) { // Write to the server using the Fetch API const response = await fetch(endpoint, { signal: controller.signal, // We use the same object for both fetch and controller method: "POST", body: chunk, }); await response.text(); }, }); // Perform the write const writer = writingStream.getWriter(); writer.write("Lorem ipsum test data"); // Abort the write manually await writer.abort("Manual abort!"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/writablestreamdefaultcontroller
data/mdn-content/files/en-us/web/api/writablestreamdefaultcontroller/error/index.md
--- title: "WritableStreamDefaultController: error() method" short-title: error() slug: Web/API/WritableStreamDefaultController/error page-type: web-api-instance-method browser-compat: api.WritableStreamDefaultController.error --- {{APIRef("Streams")}} The **`error()`** method of the {{domxref("WritableStreamDefaultController")}} interface causes any future interactions with the associated stream to error. This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. ## Syntax ```js-nolint error(message) ``` ### Parameters - `message` - : A string representing the error you want future interactions to fail with. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("TypeError")}} - : The stream you are trying to error is not a {{domxref("WritableStream")}}. ## Examples ```js const writableStream = new WritableStream({ start(controller) { // do stuff with controller // error stream if necessary controller.error("My error is broken"); }, write(chunk, controller) { // ... }, close(controller) { // ... }, abort(err) { // ... }, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/networkinformation/index.md
--- title: NetworkInformation slug: Web/API/NetworkInformation page-type: web-api-interface status: - experimental browser-compat: api.NetworkInformation --- {{APIRef("Network Information API")}}{{SeeCompatTable}} The **`NetworkInformation`** interface of the [Network Information API](/en-US/docs/Web/API/Network_Information_API) provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes. The `NetworkInformation` interface cannot be instantiated. It is instead accessed through the `connection` property of the {{domxref("Navigator")}} interface. {{AvailableInWorkers}} {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties of its parent, {{domxref("EventTarget")}}._ - {{domxref("NetworkInformation.downlink")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds. - {{domxref("NetworkInformation.downlinkMax")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the maximum downlink speed, in megabits per second (Mbps), for the underlying connection technology. - {{domxref("NetworkInformation.effectiveType")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'. This value is determined using a combination of recently observed round-trip time and downlink values. - {{domxref("NetworkInformation.rtt")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds. - {{domxref("NetworkInformation.saveData")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns `true` if the user has set a reduced data usage option on the user agent. - {{domxref("NetworkInformation.type")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the type of connection a device is using to communicate with the network. It will be one of the following values: - `bluetooth` - `cellular` - `ethernet` - `none` - `wifi` - `wimax` - `other` - `unknown` ## Instance methods _This interface also inherits methods of its parent, {{domxref("EventTarget")}}._ ## Events - {{domxref("NetworkInformation.change_event", "change")}} {{Experimental_Inline}} - : The event that's fired when connection information changes. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Online and offline events](/en-US/docs/Web/API/Navigator/onLine)
0
data/mdn-content/files/en-us/web/api/networkinformation
data/mdn-content/files/en-us/web/api/networkinformation/savedata/index.md
--- title: "NetworkInformation: saveData property" short-title: saveData slug: Web/API/NetworkInformation/saveData page-type: web-api-instance-property status: - experimental browser-compat: api.NetworkInformation.saveData --- {{APIRef("Network Information API")}}{{SeeCompatTable}} The **`NetworkInformation.saveData`** read-only property of the {{domxref("NetworkInformation")}} interface returns `true` if the user has set a reduced data usage option on the user agent. ## Value A boolean value. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("Save-Data")}}
0
data/mdn-content/files/en-us/web/api/networkinformation
data/mdn-content/files/en-us/web/api/networkinformation/effectivetype/index.md
--- title: "NetworkInformation: effectiveType property" short-title: effectiveType slug: Web/API/NetworkInformation/effectiveType page-type: web-api-instance-property status: - experimental browser-compat: api.NetworkInformation.effectiveType --- {{SeeCompatTable}}{{APIRef("Network Information API")}} The **`effectiveType`** read-only property of the {{domxref("NetworkInformation")}} interface returns the effective type of the connection meaning one of `slow-2g`, `2g`, `3g`, or `4g`. This value is determined using a combination of recently observed, round-trip time and downlink values. ## Value A string that is either `slow-2g`, `2g`, `3g`, or `4g`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Effective Connection Type](/en-US/docs/Glossary/Effective_connection_type) - {{HTTPHeader("ECT")}}
0
data/mdn-content/files/en-us/web/api/networkinformation
data/mdn-content/files/en-us/web/api/networkinformation/downlink/index.md
--- title: "NetworkInformation: downlink property" short-title: downlink slug: Web/API/NetworkInformation/downlink page-type: web-api-instance-property status: - experimental browser-compat: api.NetworkInformation.downlink --- {{SeeCompatTable}}{{APIRef("Network Information API")}} The **`downlink`** read-only property of the {{domxref("NetworkInformation")}} interface returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds. This value is based on recently observed application layer throughput across recently active connections, excluding connections made to a private address space. In the absence of recent bandwidth measurement data, the attribute value is determined by the properties of the underlying connection technology. ## Value A number. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("Downlink")}}
0
data/mdn-content/files/en-us/web/api/networkinformation
data/mdn-content/files/en-us/web/api/networkinformation/change_event/index.md
--- title: "NetworkInformation: change event" short-title: change slug: Web/API/NetworkInformation/change_event page-type: web-api-event status: - experimental browser-compat: api.NetworkInformation.change_event --- {{apiref("Network Information API")}}{{SeeCompatTable}} The **`change`** event fires when connection information changes, and the event is received by the {{domxref("NetworkInformation")}} object. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("change", (event) => {}); onchange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js // Get the connection type. const type = navigator.connection.type; function changeHandler(e) { // Handle change of connection type here. } // Register for event changes: navigator.connection.onchange = changeHandler; // Another way: navigator.connection.addEventListener('change', changeHandler); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/networkinformation
data/mdn-content/files/en-us/web/api/networkinformation/downlinkmax/index.md
--- title: "NetworkInformation: downlinkMax property" short-title: downlinkMax slug: Web/API/NetworkInformation/downlinkMax page-type: web-api-instance-property status: - experimental browser-compat: api.NetworkInformation.downlinkMax --- {{APIRef("Network Information API")}}{{SeeCompatTable}} The **`NetworkInformation.downlinkMax`** read-only property returns the maximum downlink speed, in megabits per second (Mbps), for the underlying connection technology. {{AvailableInWorkers}} ## Value An `unrestricted double` representing the maximum downlink speed, in megabits per second (Mb/s), for the underlying connection technology. ## Examples The following example monitors the connection using the `change` event and logs changes as they occur. ```js function logConnectionType() { let connectionType = "not supported"; let downlinkMax = "not supported"; if ("connection" in navigator) { connectionType = navigator.connection.effectiveType; if ("downlinkMax" in navigator.connection) { downlinkMax = navigator.connection.downlinkMax; } } console.log( `Current connection type: ${connectionType} (downlink max: ${downlinkMax})`, ); } logConnectionType(); navigator.connection.addEventListener("change", logConnectionType); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/networkinformation
data/mdn-content/files/en-us/web/api/networkinformation/type/index.md
--- title: "NetworkInformation: type property" short-title: type slug: Web/API/NetworkInformation/type page-type: web-api-instance-property status: - experimental browser-compat: api.NetworkInformation.type --- {{apiref("Network Information API")}}{{SeeCompatTable}} The **`NetworkInformation.type`** read-only property returns the type of connection a device is using to communicate with the network. {{AvailableInWorkers}} ## Value An enumerated value that is one of the following values: - `"bluetooth"` - `"cellular"` - `"ethernet"` - `"none"` - `"wifi"` - `"wimax"` - `"other"` - `"unknown"` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/networkinformation
data/mdn-content/files/en-us/web/api/networkinformation/rtt/index.md
--- title: "NetworkInformation: rtt property" short-title: rtt slug: Web/API/NetworkInformation/rtt page-type: web-api-instance-property status: - experimental browser-compat: api.NetworkInformation.rtt --- {{apiref("Network Information API")}}{{SeeCompatTable}} The **`NetworkInformation.rtt`** read-only property returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds. This value is based on recently observed application-layer RTT measurements across recently active connections. It excludes connections made to a private address space. If no recent measurement data is available, the value is based on the properties of the underlying connection technology. {{AvailableInWorkers}} ## Value A number. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("RTT")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/customelementregistry/index.md
--- title: CustomElementRegistry slug: Web/API/CustomElementRegistry page-type: web-api-interface browser-compat: api.CustomElementRegistry --- {{APIRef("Web Components")}} The **`CustomElementRegistry`** interface provides methods for registering custom elements and querying registered elements. To get an instance of it, use the {{domxref("window.customElements")}} property. ## Instance methods - {{domxref("CustomElementRegistry.define()")}} - : Defines a new [custom element](/en-US/docs/Web/API/Web_components/Using_custom_elements). - {{domxref("CustomElementRegistry.get()")}} - : Returns the constructor for the named custom element, or {{jsxref("undefined")}} if the custom element is not defined. - {{domxref("CustomElementRegistry.getName()")}} - : Returns the name for the already-defined custom element, or `null` if the custom element is not defined. - {{domxref("CustomElementRegistry.upgrade()")}} - : Upgrades a custom element directly, even before it is connected to its shadow root. - {{domxref("CustomElementRegistry.whenDefined()")}} - : Returns an empty {{jsxref("Promise")}} that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled. ## Examples See the [Examples](/en-US/docs/Web/API/Web_components/Using_custom_elements#examples) section in our [guide to using custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/customelementregistry
data/mdn-content/files/en-us/web/api/customelementregistry/upgrade/index.md
--- title: "CustomElementRegistry: upgrade() method" short-title: upgrade() slug: Web/API/CustomElementRegistry/upgrade page-type: web-api-instance-method browser-compat: api.CustomElementRegistry.upgrade --- {{APIRef("Web Components")}} The **`upgrade()`** method of the {{domxref("CustomElementRegistry")}} interface upgrades all shadow-containing custom elements in a {{domxref("Node")}} subtree, even before they are connected to the main document. ## Syntax ```js-nolint upgrade(root) ``` ### Parameters - `root` - : A {{domxref("Node")}} instance with shadow-containing descendant elements to upgrade. If there are no descendant elements that can be upgraded, no error is thrown. ### Return value None ({{jsxref("undefined")}}). ## Examples Taken from the [HTML spec](https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-upgrade): ```js const el = document.createElement("spider-man"); class SpiderMan extends HTMLElement {} customElements.define("spider-man", SpiderMan); console.assert(!(el instanceof SpiderMan)); // not yet upgraded customElements.upgrade(el); console.assert(el instanceof SpiderMan); // upgraded! ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/customelementregistry
data/mdn-content/files/en-us/web/api/customelementregistry/get/index.md
--- title: "CustomElementRegistry: get() method" short-title: get() slug: Web/API/CustomElementRegistry/get page-type: web-api-instance-method browser-compat: api.CustomElementRegistry.get --- {{APIRef("Web Components")}} The **`get()`** method of the {{domxref("CustomElementRegistry")}} interface returns the constructor for a previously-defined custom element. ## Syntax ```js-nolint get(name) ``` ### Parameters - `name` - : The name of the custom element. ### Return value The constructor for the named custom element, or {{jsxref("undefined")}} if there is no custom element defined with the name. ## Examples ```js customElements.define( "my-paragraph", class extends HTMLElement { constructor() { let templateContent = document.getElementById("my-paragraph").content; super() // returns element this scope .attachShadow({ mode: "open" }) // sets AND returns this.shadowRoot .append(templateContent.cloneNode(true)); } }, ); // Return a reference to the my-paragraph constructor let ctor = customElements.get("my-paragraph"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/customelementregistry
data/mdn-content/files/en-us/web/api/customelementregistry/define/index.md
--- title: "CustomElementRegistry: define() method" short-title: define() slug: Web/API/CustomElementRegistry/define page-type: web-api-instance-method browser-compat: api.CustomElementRegistry.define --- {{APIRef("Web Components")}} The **`define()`** method of the {{domxref("CustomElementRegistry")}} interface adds a definition for a custom element to the custom element registry, mapping its name to the constructor which will be used to create it. ## Syntax ```js-nolint define(name, constructor) define(name, constructor, options) ``` ### Parameters - `name` - : Name for the new custom element. Must be a [valid custom element name](#valid_custom_element_names). - `constructor` - : Constructor for the new custom element. - `options` {{optional_inline}} - : Object that controls how the element is defined. One option is currently supported: - `extends` - : String specifying the name of a built-in element to extend. Used to create a customized built-in element. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if: - The {{domxref("CustomElementRegistry")}} already contains an entry with the same name or the same constructor (or is otherwise already defined). - The <code>extends</code> option is specified and it is a [valid custom element name](#valid_custom_element_names) - The <code>extends</code> option is specified but the element it is trying to extend is an unknown element. - `SyntaxError` {{domxref("DOMException")}} - : Thrown if the provided name is not a [valid custom element name](#valid_custom_element_names). - {{jsxref("TypeError")}} - : Thrown if the referenced constructor is not a constructor. ## Description The `define()` method adds a definition for a custom element to the custom element registry, mapping its name to the constructor which will be used to create it. There are two types of custom element you can create: - _Autonomous custom elements_ are standalone elements, that don't inherit from built-in HTML elements. - _Customized built-in elements_ are elements that inherit from, and extend, built-in HTML elements. To define an autonomous custom element, you should omit the `options` parameter. To define a customized built-in element, you must pass the `options` parameter with its `extends` property set to the name of the built-in element that you are extending, and this must correspond to the interface that your custom element class definition inherits from. For example, to customize the {{htmlelement("p")}} element, you must pass `{extends: "p"}` to `define()`, and the class definition for your element must inherit from {{domxref("HTMLParagraphElement")}}. ### Valid custom element names Custom element names must: - start with an ASCII lowercase letter (a-z) - contain a hyphen - not contain any ASCII uppercase letters - not contain certain other characters, as documented in the [valid custom element names](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name) section of the Web Components specification - not be any of: - "annotation-xml" - "color-profile" - "font-face" - "font-face-src" - "font-face-uri" - "font-face-format" - "font-face-name" - "missing-glyph" ## Examples ### Defining an autonomous custom element The following class implements a minimal autonomous custom element: ```js class MyAutonomousElement extends HTMLElement { constructor() { super(); } } ``` This element doesn't do anything: a real autonomous element would implement its functionality in its constructor and in the lifecycle callbacks provided by the standard. See [Implementing a custom element](/en-US/docs/Web/API/Web_components/Using_custom_elements) in our guide to working with custom elements. However, the above class definition satisfies the requirements of the `define()` method, so we can define it with the following code: ```js customElements.define("my-autonomous-element", MyAutonomousElement); ``` We could then use it in an HTML page like this: ```html <my-autonomous-element>Element contents</my-autonomous-element> ``` ### Defining a customized built-in element The following class implements a customized built-in element: ```js class MyCustomizedBuiltInElement extends HTMLParagraphElement { constructor() { super(); } } ``` This element extends the built-in {{htmlelement("p")}} element. In this minimal example the element doesn't implement any customization, so it will behave just like a normal `<p>` element. However, it does satisfy the requirements of `define()`, so we can define it like this: ```js customElements.define( "my-customized-built-in-element", MyCustomizedBuiltInElement, { extends: "p", }, ); ``` We could then use it in an HTML page like this: ```html <p is="my-customized-built-in-element"></p> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements)
0
data/mdn-content/files/en-us/web/api/customelementregistry
data/mdn-content/files/en-us/web/api/customelementregistry/whendefined/index.md
--- title: "CustomElementRegistry: whenDefined() method" short-title: whenDefined() slug: Web/API/CustomElementRegistry/whenDefined page-type: web-api-instance-method browser-compat: api.CustomElementRegistry.whenDefined --- {{APIRef("Web Components")}} The **`whenDefined()`** method of the {{domxref("CustomElementRegistry")}} interface returns a {{jsxref("Promise")}} that resolves when the named element is defined. ## Syntax ```js-nolint whenDefined(name) ``` ### Parameters - `name` - : The name of the custom element. ### Return value A {{jsxref("Promise")}} that fulfills with the [custom element](/en-US/docs/Web/API/Web_components/Using_custom_elements)'s constructor when a custom element becomes defined with the given name. If a custom element has already been defined with the name, the promise will immediately fulfill. The promise is rejected with a `SyntaxError` {{domxref("DOMException")}} if the name is not a [valid custom element name](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name). ## Examples This example uses `whenDefined()` to detect when the custom elements that make up a menu are defined. The menu displays placeholder content until the actual menu content is ready to display. ```html <nav id="menu-container"> <div class="menu-placeholder">Loading…</div> <nav-menu> <menu-item>Item 1</menu-item> <menu-item>Item 2</menu-item> … <menu-item>Item N</menu-item> </nav-menu> </nav> ``` ```js const container = document.getElementById("menu-container"); const placeholder = container.querySelector(".menu-placeholder"); // Fetch all the children of menu that are not yet defined. const undefinedElements = container.querySelectorAll(":not(:defined)"); async function removePlaceholder() { const promises = [...undefinedElements].map((button) => customElements.whenDefined(button.localName), ); // Wait for all the children to be upgraded await Promise.all(promises); // then remove the placeholder container.removeChild(placeholder); } removePlaceholder(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/customelementregistry
data/mdn-content/files/en-us/web/api/customelementregistry/getname/index.md
--- title: "CustomElementRegistry: getName() method" short-title: getName() slug: Web/API/CustomElementRegistry/getName page-type: web-api-instance-method browser-compat: api.CustomElementRegistry.getName --- {{APIRef("Web Components")}} The **`getName()`** method of the {{domxref("CustomElementRegistry")}} interface returns the name for a previously-defined custom element. ## Syntax ```js-nolint getName(constructor) ``` ### Parameters - `constructor` - : Constructor for the custom element. ### Return value The name for the previously defined custom element, or `null` if there is no custom element defined with the constructor. ## Examples ```js class MyParagraph extends HTMLElement { constructor() { let templateContent = document.getElementById("my-paragraph").content; super() // returns element this scope .attachShadow({ mode: "open" }) // sets AND returns this.shadowRoot .append(templateContent.cloneNode(true)); } } customElements.define("my-paragraph", MyParagraph); // Return a reference to the my-paragraph constructor customElements.getName(MyParagraph) === "my-paragraph"; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/metadata/index.md
--- title: Metadata slug: Web/API/Metadata page-type: web-api-interface status: - experimental - non-standard browser-compat: api.Metadata --- {{APIRef("File and Directory Entries API")}}{{Non-standard_Header}}{{SeeCompatTable}} The **`Metadata`** interface contains information about a file system entry. This metadata includes the file's size and modification date and time. > **Note:** This interface isn't available through the global scope; instead, you obtain a `Metadata` object describing a {{domxref("FileSystemEntry")}} using the method {{domxref("FileSystemEntry.getMetadata()")}}. ## Instance properties - {{domxref("Metadata.modificationTime", "modificationTime")}} {{ReadOnlyInline}} {{Experimental_Inline}} {{Non-standard_Inline}} - : A {{jsxref("Date")}} object indicating the date and time the entry was modified. - {{domxref("Metadata.size", "size")}} {{ReadOnlyInline}} {{Experimental_Inline}} {{Non-standard_Inline}} - : A 64-bit unsigned integer indicating the size of the entry in bytes. ## Specifications This feature has been removed from all specification and is not in the process of being standardized. ## Browser compatibility {{Compat}} ## See also - [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) - [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction) - {{domxref("FileSystemEntry")}} - {{domxref("FileSystemFileEntry")}} and {{domxref("FileSystemDirectoryEntry")}}
0
data/mdn-content/files/en-us/web/api/metadata
data/mdn-content/files/en-us/web/api/metadata/modificationtime/index.md
--- title: "Metadata: modificationTime property" short-title: modificationTime slug: Web/API/Metadata/modificationTime page-type: web-api-instance-property status: - experimental - non-standard browser-compat: api.Metadata.modificationTime --- {{APIRef("File and Directory Entries API")}}{{Non-standard_header}}{{SeeCompatTable}} The read-only **`modificationTime`** property of the {{domxref("Metadata")}} interface is a {{jsxref("Date")}} object which specifies the date and time the file system entry (or the data referenced by the entry) was last modified. A file system entry is considered to have been modified if the metadata or the contents of the referenced file (or directory, or whatever other kind of file system entry might exist on the platform in use) has changed. ## Value A {{jsxref("Date")}} timestamp indicating when the file system entry was last changed. ## Examples This example tries to get a particular working file at `tmp/workfile.json`. Once that file has been found, its metadata is obtained and the file's modification timestamp year is compared to the current year. If it was last modified in a year at least five prior to the current year, the file is removed and a new one is created. ```js workingDirectory.getFile( "tmp/workfile.json", { create: true }, (fileEntry) => { fileEntry.getMetadata((metadata) => { if ( new Date().getFullYear() - metadata.modificationTime.getFullYear() >= 5 ) { fileEntry.remove(() => { workingDirectory.getFile( "tmp/workfile.json", { create: true }, (newEntry) => { fileEntry = newEntry; }, ); }); } }); }, handleError, ); ``` ## Specifications This feature has been removed from all specification and is not in the process of being standardized. ## Browser compatibility {{Compat}} ## See also - [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) - [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction) - {{domxref("Metadata")}} - {{domxref("FileSystemEntry.getMetadata()")}} - {{domxref("FileSystemFileEntry")}}
0
data/mdn-content/files/en-us/web/api/metadata
data/mdn-content/files/en-us/web/api/metadata/size/index.md
--- title: "Metadata: size property" short-title: size slug: Web/API/Metadata/size page-type: web-api-instance-property status: - experimental - non-standard browser-compat: api.Metadata.size --- {{APIRef("File and Directory Entries API")}}{{Non-standard_header}}{{SeeCompatTable}} The read-only **`size`** property of the {{domxref("Metadata")}} interface specifies the size, in bytes, of the referenced file or other file system object on disk. ## Value A number indicating the size of the file in bytes. ## Examples This example checks the size of a log file and removes it if it's larger than a megabyte. ```js workingDirectory.getFile( "log/important.log", {}, (fileEntry) => { fileEntry.getMetadata((metadata) => { if (metadata.size > 1048576) { fileEntry.remove(() => { /* log file removed; do something clever here */ }); } }); }, handleError, ); ``` ## Specifications This feature has been removed from all specification and is not in the process of being standardized. ## Browser compatibility {{Compat}} ## See also - [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) - [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction) - {{domxref("Metadata")}} - {{domxref("FileSystemEntry.getMetadata()")}} - {{domxref("FileSystemFileEntry")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/plugin/index.md
--- title: Plugin slug: Web/API/Plugin page-type: web-api-interface status: - deprecated browser-compat: api.Plugin --- {{APIRef("HTML DOM")}}{{Deprecated_Header}} The `Plugin` interface provides information about a browser plugin. > **Note:** Own properties of `Plugin` objects are no longer enumerable in the latest browser versions. ## Instance properties - {{domxref("Plugin.description")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : A human-readable description of the plugin. - {{domxref("Plugin.filename")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : The filename of the plugin file. - {{domxref("Plugin.name")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : The name of the plugin. ## Instance methods - {{domxref("Plugin.item")}} {{Deprecated_Inline}} - : Returns the MIME type of a supported content type, given the index number into a list of supported types. - {{domxref("Plugin.namedItem")}} {{Deprecated_Inline}} - : Returns the MIME type of a supported item. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/ext_texture_compression_bptc/index.md
--- title: EXT_texture_compression_bptc extension short-title: EXT_texture_compression_bptc slug: Web/API/EXT_texture_compression_bptc page-type: webgl-extension browser-compat: api.EXT_texture_compression_bptc --- {{APIRef("WebGL")}} The `EXT_texture_compression_bptc` extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and exposes 4 BPTC compressed texture formats. These compression formats are called [BC7](https://docs.microsoft.com/windows/win32/direct3d11/bc7-format) and [BC6H](https://docs.microsoft.com/windows/win32/direct3d11/bc6h-format) in [Microsoft's DirectX API](https://docs.microsoft.com/windows/win32/direct3d11/texture-block-compression-in-direct3d-11). 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:** Support depends on the system's graphics driver. There is no support on Windows. > > This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts. ## Constants The compressed texture formats are exposed by 4 constants and can be used in two functions: {{domxref("WebGLRenderingContext.compressedTexImage2D", "compressedTexImage2D()")}} and {{domxref("WebGLRenderingContext.compressedTexSubImage2D", "compressedTexSubImage2D()")}}. - `ext.COMPRESSED_RGBA_BPTC_UNORM_EXT` - : Compresses 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of RGBA or image data. See also [BC7 format](https://docs.microsoft.com/windows/win32/direct3d11/bc7-format). - `ext.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT` - : Compresses 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of SRGB_ALPHA or image data. See also [BC7 format](https://docs.microsoft.com/windows/win32/direct3d11/bc7-format). - `ext.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT` - : Compresses high dynamic range signed floating point values. Each 4x4 block of texels consists of 128 bits of RGB data. It only contains RGB data, so the returned alpha value is 1.0. See also [BC6H format](https://docs.microsoft.com/windows/win32/direct3d11/bc6h-format). - `ext.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT` - : Compresses high dynamic range unsigned floating point values. Each 4x4 block of texels consists of 128 bits of RGB data. It only contains RGB data, so the returned alpha value is 1.0. See also [BC6H format](https://docs.microsoft.com/windows/win32/direct3d11/bc6h-format). ## Examples ```js const ext = gl.getExtension("EXT_texture_compression_bptc"); const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D( gl.TEXTURE_2D, 0, ext.COMPRESSED_RGBA_BPTC_UNORM_EXT, 128, 128, 0, textureData, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("WebGLRenderingContext.compressedTexImage2D()")}} - {{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}} - {{domxref("WebGLRenderingContext.getParameter()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlsourceelement/index.md
--- title: HTMLSourceElement slug: Web/API/HTMLSourceElement page-type: web-api-interface browser-compat: api.HTMLSourceElement --- {{APIRef("HTML DOM")}} The **`HTMLSourceElement`** interface provides special properties (beyond the regular {{domxref("HTMLElement")}} object interface it also has available to it by inheritance) for manipulating {{htmlelement("source")}} elements. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLSourceElement.height")}} - : A number that reflects the [`height`](/en-US/docs/Web/HTML/Element/source#height) HTML attribute, indicating the height of the image resource in CSS pixels. The property has a meaning only if the parent of the current {{HTMLElement("source")}} element is a {{HTMLElement("picture")}} element. - {{domxref("HTMLSourceElement.media")}} - : A string reflecting the [`media`](/en-US/docs/Web/HTML/Element/source#media) HTML attribute, containing the intended type of the media resource. - {{domxref("HTMLSourceElement.sizes")}} - : A string representing image sizes between breakpoints - {{domxref("HTMLSourceElement.src")}} - : A string reflecting the [`src`](/en-US/docs/Web/HTML/Element/source#src) HTML attribute, containing the URL for the media resource. The {{domxref("HTMLSourceElement.src")}} property has a meaning only when the associated {{HTMLElement("source")}} element is nested in a media element that is a {{htmlelement("video")}} or an {{htmlelement("audio")}} element. It has no meaning and is ignored when it is nested in a {{HTMLElement("picture")}} element. > **Note:** If the `src` property is updated (along with any siblings), the parent {{domxref("HTMLMediaElement")}}'s `load` method should be called when done, since `<source>` elements are not re-scanned automatically. - {{domxref("HTMLSourceElement.srcset")}} - : A string reflecting the [`srcset`](/en-US/docs/Web/HTML/Element/source#srcset) HTML attribute, containing a list of candidate images, separated by a comma (`',', U+002C COMMA`). A candidate image is a URL followed by a `'w'` with the width of the images, or an `'x'` followed by the pixel density. - {{domxref("HTMLSourceElement.type")}} - : A string reflecting the [`type`](/en-US/docs/Web/HTML/Element/source#type) HTML attribute, containing the type of the media resource. - {{domxref("HTMLSourceElement.width")}} - : A number that reflects the [`width`](/en-US/docs/Web/HTML/Element/source#width) HTML attribute, indicating the width of the image resource in CSS pixels. The property has a meaning only if the parent of the current {{HTMLElement("source")}} element is a {{HTMLElement("picture")}} element. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("source") }}. - The HTML DOM APIs of the elements that can contain a {{HTMLElement("source")}} element: {{domxref("HTMLVideoElement")}}, {{domxref("HTMLAudioElement")}}, {{domxref("HTMLPictureElement")}}.
0
data/mdn-content/files/en-us/web/api/htmlsourceelement
data/mdn-content/files/en-us/web/api/htmlsourceelement/width/index.md
--- title: "HTMLSourceElement: width property" short-title: width slug: Web/API/HTMLSourceElement/width page-type: web-api-instance-property browser-compat: api.HTMLSourceElement.width --- {{APIRef("HTML DOM")}} The **`width`** property of the {{domxref("HTMLSourceElement")}} interface is a non-negative number indicating the width of the image resource in CSS pixels. The property has an effect only if the parent of the current {{HTMLElement("source")}} element is a {{HTMLElement("picture")}} element. It reflects the `width` attribute of the {{HTMLElement("source")}} element. ## Value A non-negative number indicating the width of the image resource in CSS pixels. ## Examples ```html <picture id="img"> <source srcset="landscape.png" media="(min-width: 1000px)" width="1000" height="400" /> <source srcset="square.png" media="(min-width: 800px)" width="800" height="800" /> <source srcset="portrait.png" media="(min-width: 600px)" width="600" height="800" /> <img src="fallback.png" alt="Image used when the browser does not support the sources" width="500" height="400" /> </picture> ``` ```js const img = document.getElementById("img"); const sources = img.querySelectorAll("source"); console.log(Array.from(sources).map((el) => el.width)); // Output: [1000, 800, 600] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.width")}} - {{domxref("HTMLEmbedElement.width")}} - {{domxref("HTMLIFrameElement.width")}} - {{domxref("HTMLImageElement.width")}} - {{domxref("HTMLObjectElement.width")}} - {{domxref("HTMLVideoElement.width")}}
0
data/mdn-content/files/en-us/web/api/htmlsourceelement
data/mdn-content/files/en-us/web/api/htmlsourceelement/height/index.md
--- title: "HTMLSourceElement: height property" short-title: height slug: Web/API/HTMLSourceElement/height page-type: web-api-instance-property browser-compat: api.HTMLSourceElement.height --- {{APIRef("HTML DOM")}} The **`height`** property of the {{domxref("HTMLSourceElement")}} interface is a non-negative number indicating the height of the image resource in CSS pixels. The property has an effect only if the parent of the current {{HTMLElement("source")}} element is a {{HTMLElement("picture")}} element. It reflects the `height` attribute of the {{HTMLElement("source")}} element. ## Value A non-negative number indicating the height of the image resource in CSS pixels. ## Examples ```html <picture id="img"> <source srcset="landscape.png" media="(min-width: 1000px)" width="1000" height="400" /> <source srcset="square.png" media="(min-width: 800px)" width="800" height="800" /> <source srcset="portrait.png" media="(min-width: 600px)" width="600" height="800" /> <img src="fallback.png" alt="Image used when the browser does not support the sources" width="500" height="400" /> </picture> ``` ```js const img = document.getElementById("img"); const sources = img.querySelectorAll("source"); console.log(Array.from(sources).map((el) => el.height)); // Output: [400, 800, 800] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.height")}} - {{domxref("HTMLEmbedElement.height")}} - {{domxref("HTMLIFrameElement.height")}} - {{domxref("HTMLImageElement.height")}} - {{domxref("HTMLObjectElement.height")}} - {{domxref("HTMLVideoElement.height")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/index.md
--- title: RTCOutboundRtpStreamStats slug: Web/API/RTCOutboundRtpStreamStats page-type: web-api-interface browser-compat: api.RTCStatsReport.type_outbound-rtp --- {{APIRef("WebRTC")}} The **`RTCOutboundRtpStreamStats`** dictionary of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) is used to report metrics and statistics related to an outbound {{Glossary("RTP")}} stream being sent by an {{domxref("RTCRtpSender")}}. The statistics can be obtained by iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCPeerConnection.getStats()")}} or {{domxref("RTCRtpSender.getStats()")}} until you find a report with the [`type`](#type) of `outbound-rtp`. ## Instance properties <!-- he `RTCOutboundRtpStreamStats` dictionary includes the following properties in addition to those it inherits from {{domxref("RTCSentRtpStreamStats")}}, {{domxref("RTCRtpStreamStats")}}._ --> - {{domxref("RTCOutboundRtpStreamStats.averageRtcpInterval", "averageRtcpInterval")}} - : A floating-point value indicating the average {{Glossary("RTCP")}} interval between two consecutive compound RTCP packets. - {{domxref("RTCOutboundRtpStreamStats.firCount", "firCount")}} - : An integer value which indicates the total number of Full Intra Request (FIR) packets which this {{domxref("RTCRtpSender")}} has sent to the remote {{domxref("RTCRtpReceiver")}}. This is an indicator of how often the stream has lagged, requiring frames to be skipped in order to catch up. _Valid only for video streams._ - {{domxref("RTCOutboundRtpStreamStats.framesEncoded", "framesEncoded")}} - : The number of frames that have been successfully encoded so far for sending on this RTP stream. _Only valid for video streams._ - {{domxref("RTCOutboundRtpStreamStats.nackCount", "nackCount")}} - : An integer value indicating the total number of Negative ACKnolwedgement (NACK) packets this `RTCRtpSender` has received from the remote {{domxref("RTCRtpReceiver")}}. - {{domxref("RTCOutboundRtpStreamStats.perDscpPacketsSent", "perDscpPacketsSent")}} - : A record of key-value pairs with strings as the keys mapped to 32-bit integer values, each indicating the total number of packets this `RTCRtpSender` has transmitted for this source for each Differentiated Services Code Point (DSCP). - {{domxref("RTCOutboundRtpStreamStats.pliCount", "pliCount")}} - : An integer specifying the number of times the remote receiver has notified this `RTCRtpSender` that some amount of encoded video data for one or more frames has been lost, using Picture Loss Indication (PLI) packets. _Only available for video streams._ - {{domxref("RTCOutboundRtpStreamStats.qpSum", "qpSum")}} - : A 64-bit value containing the sum of the QP values for every frame encoded by this {{domxref("RTCRtpSender")}}. _Valid only for video streams._ - {{domxref("RTCOutboundRtpStreamStats.qualityLimitationDurations", "qualityLimitationDurations")}} - : A record mapping each of the quality limitation reasons in the {{domxref("RTCRemoteInboundRtpStreamStats")}} enumeration to a floating-point value indicating the number of seconds the stream has spent with its quality limited for that reason. - {{domxref("RTCOutboundRtpStreamStats.qualityLimitationReason", "qualityLimitationReason")}} - : One of the string `none`, `cpu`, `bandwidth`, or `other`, explaining why the resolution and/or frame rate is being limited for this RTP stream. _Valid only for video streams_. - {{domxref("RTCOutboundRtpStreamStats.remoteId", "remoteId")}} - : A string which identifies the {{domxref("RTCRemoteInboundRtpStreamStats")}} object that provides statistics for the remote peer for this same SSRC. This ID is stable across multiple calls to `getStats()`. - {{domxref("RTCOutboundRtpStreamStats.retransmittedBytesSent", "retransmittedBytesSent")}} - : The total number of bytes that have been retransmitted for this source as of the time the statistics were sampled. These retransmitted bytes comprise the packets included in the value returned by {{domxref("RTCInboundRtpStreamStats.retransmittedPacketsSent", "retransmittedPacketsSent")}}. - {{domxref("RTCOutboundRtpStreamStats.retransmittedPacketsSent", "retransmittedPacketsSent")}} - : The total number of packets that have needed to be retransmitted for this source as of the time the statistics were sampled. These retransmitted packets are included in the value returned by {{domxref("RTCInboundRtpStreamStats.packetsSent", "packetsSent")}}. - {{domxref("RTCOutboundRtpStreamStats.senderId", "senderId")}} - : The {{domxref("RTCOutboundRtpStreamStats.id", "id")}} of the {{domxref("RTCAudioSenderStats")}} or {{domxref("RTCVideoSenderStats")}} object containing statistics about this stream's {{domxref("RTCRtpSender")}}. - {{domxref("RTCOutboundRtpStreamStats.sliCount", "sliCount")}} - : An integer indicating the number of times this sender received a Slice Loss Indication (SLI) frame from the remote peer, indicating that one or more consecutive video macroblocks have been lost or corrupted. Available only for video streams. - {{domxref("RTCOutboundRtpStreamStats.targetBitrate", "targetBitrate")}} - : A value indicating the bit rate the `RTCRtpSender`'s codec is configured to attempt to achieve in its output media. - {{domxref("RTCOutboundRtpStreamStats.totalEncodedBytesTarget", "totalEncodedBytesTarget")}} - : A cumulative sum of the _target_ frame sizes (the targeted maximum size of the frame in bytes when the codec is asked to compress it) for all of the frames encoded so far. This will likely differ from the total of the _actual_ frame sizes. - {{domxref("RTCOutboundRtpStreamStats.totalEncodeTime", "totalEncodeTime")}} - : A floating-point value indicating the total number of seconds that have been spent encoding the frames encoded so far by this {{domxref("RTCRtpSender")}}. - {{domxref("RTCOutboundRtpStreamStats.trackId", "trackId")}} - : The {{domxref("RTCOutboundRtpStreamStats.id", "id")}} of the {{domxref("RTCSenderAudioTrackAttachmentStats")}} or {{domxref("RTCSenderVideoTrackAttachmentStats")}} object containing the current track attachment to the {{domxref("RTCRtpSender")}} responsible for this stream. ### Common instance properties The following properties are common to all WebRTC statistics objects. <!-- RTCStats --> - {{domxref("RTCOutboundRtpStreamStats.id", "id")}} - : A string that uniquely identifies the object that is being monitored to produce this set of statistics. - {{domxref("RTCOutboundRtpStreamStats.timestamp", "timestamp")}} - : A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object. - {{domxref("RTCOutboundRtpStreamStats.type", "type")}} - : A string with the value `"outbound-rtp"`, indicating the type of statistics that the object contains. ## Examples ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("RTCStatsReport")}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/slicount/index.md
--- title: "RTCOutboundRtpStreamStats: sliCount property" short-title: sliCount slug: Web/API/RTCOutboundRtpStreamStats/sliCount page-type: web-api-instance-property browser-compat: api.RTCOutboundRtpStreamStats.sliCount --- {{APIRef("WebRTC")}} The **`sliCount`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary indicates how many **Slice Loss Indication** (**SLI**) packets the {{domxref("RTCRtpSender")}} received from the remote {{domxref("RTCRtpReceiver")}} for the RTP stream described by this object. An SLI packet is used by a decoder to let the encoder (the sender) know that it's detected corruption of one or more consecutive macroblocks, in scan order, in the received media. In general, what's usually of interest is that the higher this number is, the more the stream data is becoming corrupted between the sender and the receiver, causing the receiver to request retransmits or to drop frames entirely. ## Value An unsigned integer indicating the number of SLI packets the sender received from the receiver due to lost runs of macroblocks. A high value of `sliCount` may be an indication of an unreliable network. This is a very technical part of how video codecs work. For details, see {{RFC(4585, "6.3.2")}}. > **Note:** This value is only present for video media. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{RFC(4585, "", "6.3.2")}}: Definition of "Slice Loss Indication" in the document _Extended RTP Profile for Real-time Transport Control Protocol (RTCP)-Based Feedback (RTP/AVPF)_.
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/plicount/index.md
--- title: "RTCOutboundRtpStreamStats: pliCount property" short-title: pliCount slug: Web/API/RTCOutboundRtpStreamStats/pliCount page-type: web-api-instance-property browser-compat: api.RTCOutboundRtpStreamStats.pliCount --- {{APIRef("WebRTC")}} The **`pliCount`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary states the number of times the remote peer's {{domxref("RTCRtpReceiver")}} sent a **Picture Loss Indication** (**PLI**) packet to the {{domxref("RTCRtpSender")}} for which this object provides statistics. A PLI packet indicates that some amount of encoded video data has been lost for one or more frames. ## Value An integer value indicating the number of times a PLI packet was sent to this sender by the remote peer's {{domxref("RTCRtpReceiver")}}. These are sent by the receiver's decoder to notify the sender's encoder that an undefined amount of coded video data, which may span frame boundaries, has been lost. > **Note:** This property is only used for video streams. ## Usage notes Upon receiving a PLI packet, the sender may have responded by sending a full frame to the remote peer to allow it to re-synchronize with the media. However, the primary purpose of a PLI packet is to allow the `RTCRtpSender` for which this `RTCOutboundRtpStreamStats` object provides statistics to consider techniques to mitigate network performance issues. This is often achieved by methods such as increasing the compression or lowering resolution, although the mechanisms available to reduce the bit rate of the stream vary from codec to codec. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{RFC(4585, "", "6.3.1")}}: Definition of "PLI messages" in the document _Extended RTP Profile for Real-time Transport Control Protocol (RTCP)-Based Feedback (RTP/AVPF)_.
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/trackid/index.md
--- title: "RTCOutboundRtpStreamStats: trackId property" short-title: trackId slug: Web/API/RTCOutboundRtpStreamStats/trackId page-type: web-api-instance-property browser-compat: api.RTCOutboundRtpStreamStats.trackId --- {{APIRef("WebRTC")}} The **`trackId`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary indicates the {{domxref("RTCOutboundRtpStreamStats.id", "id")}} of the {{domxref("RTCSenderAudioTrackAttachmentStats")}} or {{domxref("RTCSenderVideoTrackAttachmentStats")}} object representing the {{domxref("MediaStreamTrack")}} which is being sent on this stream. ## Value A string containing the ID of the {{domxref("RTCSenderAudioTrackAttachmentStats")}} or {{domxref("RTCSenderVideoTrackAttachmentStats")}} object representing the track which is the source of the media being sent on this stream. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/averagertcpinterval/index.md
--- title: "RTCOutboundRtpStreamStats: averageRtcpInterval property" short-title: averageRtcpInterval slug: Web/API/RTCOutboundRtpStreamStats/averageRtcpInterval page-type: web-api-instance-property browser-compat: api.RTCOutboundRtpStreamStats.averageRtcpInterval --- {{APIRef("WebRTC")}} The **`averageRtcpInterval`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary is a floating-point value indicating the average time that should pass between transmissions of {{Glossary("RTCP")}} packets on this stream. ## Value A floating-point value indicating the average interval, in seconds, between transmissions of RTCP packets. This interval is computed following the formula outlined in {{RFC(1889, "A.7")}}. Because the interval's value is determined in part by the number of active senders, it will be different for each user of a service. Since this value is also used to determine the number of seconds after a stream starts to flow before the first RTCP packet should be sent, the result is that if many users try to start using the service at the same time, the server won't be flooded with RTCP packets coming in all at once. The sending endpoint computes this value when sending compound RTCP packets, which must contain at least an RTCP RR or SR packet and an SDES packet with the CNAME item. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/fircount/index.md
--- title: "RTCOutboundRtpStreamStats: firCount property" short-title: firCount slug: Web/API/RTCOutboundRtpStreamStats/firCount page-type: web-api-instance-property browser-compat: api.RTCOutboundRtpStreamStats.firCount --- {{APIRef("WebRTC")}} The **`firCount`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary indicates the number of **Full Intra Request** (**FIR**) that the remote {{domxref("RTCRtpReceiver")}} has sent to this {{domxref("RTCRtpSender")}}. A FIR packet is sent when the receiver finds that it has fallen behind and needs to skip frames in order to catch up; the sender should respond by sending a full frame instead of a delta frame. Available only on video media. ## Value An integer value indicating how many FIR packets have been received by the sender during the current connection. This statistic is available only for video tracks. The receiver sends a FIR packet to the sender any time it falls behind or loses packets and cannot decode the incoming stream any longer because of the lost data. This tells the sender to send a full frame instead of a delta frame, so that the receiver can catch up. The higher `firCount` is, the more often frames were dropped, which may be an indication that the media's bit rate is too high for the available bandwidth, or that the receiving device is overburdened and is therefore unable to process the incoming data. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/framesencoded/index.md
--- title: "RTCOutboundRtpStreamStats: framesEncoded property" short-title: framesEncoded slug: Web/API/RTCOutboundRtpStreamStats/framesEncoded page-type: web-api-instance-property browser-compat: api.RTCOutboundRtpStreamStats.framesEncoded --- {{APIRef("WebRTC")}} The **`framesEncoded`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary indicates the total number of frames that have been encoded by this {{domxref("RTCRtpSender")}} for this media source. ## Value An integer value indicating the total number of video frames that this sender has encoded so far for this stream. > **Note:** This property is only valid for video streams. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/qualitylimitationreason/index.md
--- title: "RTCOutboundRtpStreamStats: qualityLimitationReason property" short-title: qualityLimitationReason slug: Web/API/RTCOutboundRtpStreamStats/qualityLimitationReason page-type: web-api-instance-property browser-compat: api.RTCOutboundRtpStreamStats.qualityLimitationReason --- {{APIRef("WebRTC")}} The **`qualityLimitationReason`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary is a string indicating the reason why the media quality in the stream is currently being reduced by the codec during encoding, or `none` if no quality reduction is being performed. This quality reduction may include changes such as reduced frame rate or resolution, or an increase in compression factor. The amount of time the encoded media has had its quality reduced in each of the potential ways that can be done can be found in {{domxref("RTCOutboundRtpStreamStats.qualityLimitationDurations", "qualityLimitationDurations")}}. ## Value A {{jsxref("Map")}} whose keys are strings whose values are `none`, `cpu`, `bandwidth`, or `other`, and whose values are the duration of the media, in seconds, whose quality was reduced for that reason. ## Examples ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/qpsum/index.md
--- title: "RTCOutboundRtpStreamStats: qpSum property" short-title: qpSum slug: Web/API/RTCOutboundRtpStreamStats/qpSum page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_outbound-rtp.qpSum --- {{APIRef("WebRTC")}} The **`qpSum`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary is a value generated by adding the **Quantization Parameter** (**QP**) values for every frame this sender has produced to date on the video track corresponding to this `RTCOutboundRtpStreamStats` object. In general, the higher this number is, the more heavily compressed the video data is. ## Value An unsigned 64-bit integer value which indicates the sum of the quantization parameter (QP) value for every frame sent so far on the track described by the {{domxref("RTCOutboundRtpStreamStats")}} object. Since the value of QP is typically larger to indicate higher compression factors, the larger this sum is, the more heavily compressed the stream generally has been. > **Note:** This value is only available for video media. ## Usage notes [Quantization](https://en.wikipedia.org/wiki/Quantization) is the process of applying lossy compression to a range of values, resulting in a single **quantum value**. This value takes the place of the range of values, thereby reducing the number of different values that appear in the overall data set, making the data more compressible. The quantization process and the amount of compression can be controlled using one or more parameters. It's important to keep in mind that the value of QP can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. The best you can do is make an estimate. You can use the value of {{domxref("RTCSentRtpStreamStats.framesEncoded")}} to get the number of frames that have been encoded so far, and compute an average from there. See [Calculating average quantization](#calculating_average_quantization) below for a function that does this. Also, the exact meaning of the QP value depends on the {{Glossary("codec")}} being used. For example, for the VP8 codec, the QP value can be anywhere from 1 to 127 and is found in the frame header element `"y_ac_qi"`, whose value is defined in {{RFC(6386, "", "19.2")}}. H.264 uses a QP which ranges from 0 to 51; in this case, it's an index used to derive a scaling matrix used during the quantization process. Additionally, QP is not likely to be the only parameter the codec uses to adjust the compression. See the individual codec specifications for details. ## Examples ### Calculating average quantization The `calculateAverageQP()` function shown below computes the average QP for the object that contains RTP stream statistics, returning 0 if the object doesn't describe an RTP stream. ```js function calculateAverageQP(stats) { let frameCount = 0; switch (stats.type) { case "inbound-rtp": case "remote-inbound-rtp": frameCount = stats.framesDecoded; break; case "outbound-rtp": case "remote-outbound-rtp": frameCount = stats.framesEncoded; break; default: return 0; } return status.qpSum / frameCount; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/id/index.md
--- title: "RTCOutboundRtpStreamStats: id property" short-title: id slug: Web/API/RTCOutboundRtpStreamStats/id page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_outbound-rtp.id --- {{APIRef("WebRTC")}} The **`id`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary is a string that uniquely identifies the object for which this object provides statistics. Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an {{domxref("RTCPeerConnection")}}, or an {{domxref("RTCDataChannel")}}. ## Value A string that uniquely identifies the object for which this `RTCOutboundRtpStreamStats` object provides statistics. The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/type/index.md
--- title: "RTCOutboundRtpStreamStats: type property" short-title: type slug: Web/API/RTCOutboundRtpStreamStats/type page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_outbound-rtp.type --- {{APIRef("WebRTC")}} The **`type`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary is a string with the value `"outbound-rtp"`. Different statistics are obtained by iterating the {{domxref("RTCStatsReport")}} object returned by a call to {{domxref("RTCPeerConnection.getStats()")}}. The type indicates the set of statistics available through the object in a particular iteration step. A value of `"outbound-rtp"` indicates that the statistics available in the current step are those defined in {{domxref("RTCOutboundRtpStreamStats")}}. ## Value A string with the value `"outbound-rtpp"`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/timestamp/index.md
--- title: "RTCOutboundRtpStreamStats: timestamp property" short-title: timestamp slug: Web/API/RTCOutboundRtpStreamStats/timestamp page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_outbound-rtp.timestamp --- {{APIRef("WebRTC")}} The **`timestamp`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary is a {{domxref("DOMHighResTimeStamp")}} object specifying the time at which the data in the object was sampled. ## Value A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC. The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of [fingerprinting](/en-US/docs/Glossary/Fingerprinting) protection in the form of reduced clock precision or accuracy. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/remoteid/index.md
--- title: "RTCOutboundRtpStreamStats: remoteId property" short-title: remoteId slug: Web/API/RTCOutboundRtpStreamStats/remoteId page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_outbound-rtp.remoteId --- {{APIRef("WebRTC")}} The **`remoteId`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary specifies the {{domxref("RTCOutboundRtpStreamStats.id", "id")}} of the {{domxref("RTCRemoteInboundRtpStreamStats")}} object representing the remote peer's {{domxref("RTCRtpReceiver")}} which is sending the media to the local peer for this SSRC. ## Value A string containing the ID of the {{domxref("RTCRemoteInboundRtpStreamStats")}} object that represents the remote peer's {{domxref("RTCRtpReceiver")}} for the synchronization source represented by this stats object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/perdscppacketssent/index.md
--- title: "RTCOutboundRtpStreamStats: perDscpPacketsSent property" short-title: perDscpPacketsSent slug: Web/API/RTCOutboundRtpStreamStats/perDscpPacketsSent page-type: web-api-instance-property browser-compat: api.RTCOutboundRtpStreamStats.perDscpPacketsSent --- {{APIRef("WebRTC")}} The **`perDscpPacketsSent`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary is a record comprised of key/value pairs in which each key is a string representation of a Differentiated Services Code Point and the value is the number of packets sent for that DCSP. > **Note:** Not all operating systems make data available on a per-DSCP > basis, so this property shouldn't be relied upon on those systems. ## Value A record comprised of string/value pairs. Each key is the string representation of a single Differentiated Services Code Point (DSCP)'s ID number. > **Note:** Due to network bleaching and remapping, the numbers seen on > this record are not necessarily going to match the values as they were when the data > was sent. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{RFC(2474)}}: The Differentiated Service field in IPv4 and IPv6 headers
0
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcoutboundrtpstreamstats/nackcount/index.md
--- title: "RTCOutboundRtpStreamStats: nackCount property" short-title: nackCount slug: Web/API/RTCOutboundRtpStreamStats/nackCount page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_outbound-rtp.nackCount --- {{APIRef("WebRTC")}} The **`nackCount`** property of the {{domxref("RTCOutboundRtpStreamStats")}} dictionary is a numeric value indicating the number of times the {{domxref("RTCRtpSender")}} described by this object received a **NACK** packet from the remote receiver. A NACK (Negative ACKnowledgement, also called "Generic NACK") packet is used by the {{domxref("RTCRtpReceiver")}} to inform the sender that one or more {{Glossary("RTP")}} packets it sent were lost in transport. ## Value An integer value indicating how many times the sender received a NACK packet from the receiver, indicating the loss of one or more packets. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/eventsource/index.md
--- title: EventSource slug: Web/API/EventSource page-type: web-api-interface browser-compat: api.EventSource --- {{APIRef("Server Sent Events")}} The **`EventSource`** interface is web content's interface to [server-sent events](/en-US/docs/Web/API/Server-sent_events). An `EventSource` instance opens a persistent connection to an [HTTP](/en-US/docs/Web/HTTP) server, which sends [events](/en-US/docs/Learn/JavaScript/Building_blocks/Events) in `text/event-stream` format. The connection remains open until closed by calling {{domxref("EventSource.close()")}}. {{InheritanceDiagram}} Once the connection is opened, incoming messages from the server are delivered to your code in the form of events. If there is an event field in the incoming message, the triggered event is the same as the event field value. If no event field is present, then a generic {{domxref("EventSource/message_event", "message")}} event is fired. Unlike [WebSockets](/en-US/docs/Web/API/WebSockets_API), server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send data from the client to the server in message form. For example, `EventSource` is a useful approach for handling things like social media status updates, news feeds, or delivering data into a [client-side storage](/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage) mechanism like [IndexedDB](/en-US/docs/Web/API/IndexedDB_API) or [web storage](/en-US/docs/Web/API/Web_Storage_API). > **Warning:** When **not used over HTTP/2**, SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is _per browser_ and set to a very low number (6). The issue has been marked as "Won't fix" in [Chrome](https://crbug.com/275955) and [Firefox](https://bugzil.la/906896). This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to `www.example1.com` and another 6 SSE connections to `www.example2.com`. (from [Stackoverflow](https://stackoverflow.com/questions/5195452/websockets-vs-server-sent-events-eventsource/5326159)). When using HTTP/2, the maximum number of simultaneous _HTTP streams_ is negotiated between the server and the client (defaults to 100). ## Constructor - {{domxref("EventSource.EventSource", "EventSource()")}} - : Creates a new `EventSource` to handle receiving server-sent events from a specified URL, optionally in credentials mode. ## Instance properties _This interface also inherits properties from its parent, {{domxref("EventTarget")}}._ - {{domxref("EventSource.readyState")}} {{ReadOnlyInline}} - : A number representing the state of the connection. Possible values are `CONNECTING` (`0`), `OPEN` (`1`), or `CLOSED` (`2`). - {{domxref("EventSource.url")}} {{ReadOnlyInline}} - : A string representing the URL of the source. - {{domxref("EventSource.withCredentials")}} {{ReadOnlyInline}} - : A boolean value indicating whether the `EventSource` object was instantiated with cross-origin ([CORS](/en-US/docs/Web/HTTP/CORS)) credentials set (`true`), or not (`false`, the default). ## Instance methods _This interface also inherits methods from its parent, {{domxref("EventTarget")}}._ - {{domxref("EventSource.close()")}} - : Closes the connection, if any, and sets the `readyState` attribute to `CLOSED`. If the connection is already closed, the method does nothing. ## Events - {{domxref("EventSource/error_event", "error")}} - : Fired when a connection to an event source failed to open. - {{domxref("EventSource/message_event", "message")}} - : Fired when data is received from an event source. - {{domxref("EventSource/open_event", "open")}} - : Fired when a connection to an event source has opened. Additionally, the event source itself may send messages with an event field, which will create ad hoc events keyed to that value. ## Examples In this basic example, an `EventSource` is created to receive unnamed events from the server; a page with the name `sse.php` is responsible for generating the events. ```js const evtSource = new EventSource("sse.php"); const eventList = document.querySelector("ul"); evtSource.onmessage = (e) => { const newElement = document.createElement("li"); newElement.textContent = `message: ${e.data}`; eventList.appendChild(newElement); }; ``` Each received event causes our `EventSource` object's `onmessage` event handler to be run. It, in turn, creates a new {{HTMLElement("li")}} element and writes the message's data into it, then appends the new element to the list element already in the document. > **Note:** You can find a full example on GitHub — see [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events). To listen to named events, you'll require a listener for each type of event sent. ```js const sse = new EventSource("/api/v1/sse"); /* * This will listen only for events * similar to the following: * * event: notice * data: useful data * id: someid */ sse.addEventListener("notice", (e) => { console.log(e.data); }); /* * Similarly, this will listen for events * with the field `event: update` */ sse.addEventListener("update", (e) => { console.log(e.data); }); /* * The event "message" is a special case, as it * will capture events without an event field * as well as events that have the specific type * `event: message` It will not trigger on any * other event type. */ sse.addEventListener("message", (e) => { console.log(e.data); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Server-sent events](/en-US/docs/Web/API/Server-sent_events) - [Using server-sent events](/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)
0
data/mdn-content/files/en-us/web/api/eventsource
data/mdn-content/files/en-us/web/api/eventsource/open_event/index.md
--- title: "EventSource: open event" short-title: open slug: Web/API/EventSource/open_event page-type: web-api-event browser-compat: api.EventSource.open_event --- {{APIRef}} The `open` event of the {{domxref("EventSource")}} API is fired when a connection with an event source is opened. 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("open", (event) => {}); onopen = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js const evtSource = new EventSource("sse.php"); // addEventListener version evtSource.addEventListener("open", (e) => { console.log("The connection has been established."); }); // onopen version evtSource.onopen = (e) => { console.log("The connection has been established."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using server-sent events](/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) - {{domxref("EventSource/open_event", "open")}} - {{domxref("EventSource/error_event", "error")}} - {{domxref("EventSource/message_event", "message")}}
0
data/mdn-content/files/en-us/web/api/eventsource
data/mdn-content/files/en-us/web/api/eventsource/withcredentials/index.md
--- title: "EventSource: withCredentials property" short-title: withCredentials slug: Web/API/EventSource/withCredentials page-type: web-api-instance-property browser-compat: api.EventSource.withCredentials --- {{APIRef('WebSockets API')}} The **`withCredentials`** read-only property of the {{domxref("EventSource")}} interface returns a boolean value indicating whether the `EventSource` object was instantiated with CORS credentials set. ## Value A boolean value indicating whether the `EventSource` object was instantiated with CORS credentials set (`true`), or not (`false`, the default). ## Examples ```js const evtSource = new EventSource("sse.php"); console.log(evtSource.withCredentials); ``` > **Note:** You can find a full example on GitHub — see [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventSource")}}
0
data/mdn-content/files/en-us/web/api/eventsource
data/mdn-content/files/en-us/web/api/eventsource/url/index.md
--- title: "EventSource: url property" short-title: url slug: Web/API/EventSource/url page-type: web-api-instance-property browser-compat: api.EventSource.url --- {{APIRef('WebSockets API')}} The **`url`** read-only property of the {{domxref("EventSource")}} interface returns a string representing the URL of the source. ## Value A string representing the URL of the source. ## Examples ```js const evtSource = new EventSource("sse.php"); console.log(evtSource.url); ``` > **Note:** You can find a full example on GitHub — see [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventSource")}}
0
data/mdn-content/files/en-us/web/api/eventsource
data/mdn-content/files/en-us/web/api/eventsource/readystate/index.md
--- title: "EventSource: readyState property" short-title: readyState slug: Web/API/EventSource/readyState page-type: web-api-instance-property browser-compat: api.EventSource.readyState --- {{APIRef('WebSockets API')}} The **`readyState`** read-only property of the {{domxref("EventSource")}} interface returns a number representing the state of the connection. ## Value A number representing the state of the connection. Possible values are: - `0` — connecting - `1` — open - `2` — closed ## Examples ```js const evtSource = new EventSource("sse.php"); console.log(evtSource.readyState); ``` > **Note:** You can find a full example on GitHub — see [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventSource")}}
0
data/mdn-content/files/en-us/web/api/eventsource
data/mdn-content/files/en-us/web/api/eventsource/message_event/index.md
--- title: "EventSource: message event" short-title: message slug: Web/API/EventSource/message_event page-type: web-api-event browser-compat: api.EventSource.message_event --- {{APIRef}} The `message` event of the {{domxref("EventSource")}} API is fired when data is received through an event source. 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("message", (event) => {}); onmessage = (event) => {}; ``` ## Event type A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MessageEvent")}} ## Event properties _This interface also inherits properties from its parent, {{domxref("Event")}}._ - {{domxref("MessageEvent.data")}} {{ReadOnlyInline}} - : The data sent by the message emitter. - {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}} - : A string representing the origin of the message emitter. - {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}} - : A string representing a unique ID for the event. - {{domxref("MessageEvent.source")}} {{ReadOnlyInline}} - : A `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter. - {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}} - : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). ## Examples In this basic example, an `EventSource` is created to receive events from the server; a page with the name `sse.php` is responsible for generating the events. ```js const evtSource = new EventSource("sse.php"); const eventList = document.querySelector("ul"); evtSource.addEventListener("message", (e) => { const newElement = document.createElement("li"); newElement.textContent = `message: ${e.data}`; eventList.appendChild(newElement); }); ``` ### onmessage equivalent ```js evtSource.onmessage = (e) => { const newElement = document.createElement("li"); newElement.textContent = `message: ${e.data}`; eventList.appendChild(newElement); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using server-sent events](/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) - [`open`](/en-US/docs/Web/API/EventSource/open_event) - [`error`](/en-US/docs/Web/API/EventSource/error_event)
0
data/mdn-content/files/en-us/web/api/eventsource
data/mdn-content/files/en-us/web/api/eventsource/eventsource/index.md
--- title: "EventSource: EventSource() constructor" short-title: EventSource() slug: Web/API/EventSource/EventSource page-type: web-api-constructor browser-compat: api.EventSource.EventSource --- {{APIRef('WebSockets API')}} The **`EventSource()`** constructor returns a newly-created {{domxref("EventSource")}}, which represents a remote resource. ## Syntax ```js-nolint new EventSource(url) new EventSource(url, options) ``` ### Parameters - `url` - : A string that represents the location of the remote resource serving the events/messages. - `options` {{optional_inline}} - : Provides options to configure the new connection. The possible entries are: - `withCredentials` {{optional_inline}} - : A boolean value, defaulting to `false`, indicating if CORS should be set to `include` credentials. ## Examples ```js const evtSource = new EventSource("sse.php"); const eventList = document.querySelector("ul"); evtSource.onmessage = (e) => { const newElement = document.createElement("li"); newElement.textContent = `message: ${e.data}`; eventList.appendChild(newElement); }; ``` > **Note:** You can find a full example on GitHub — see [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventSource")}}
0
data/mdn-content/files/en-us/web/api/eventsource
data/mdn-content/files/en-us/web/api/eventsource/close/index.md
--- title: "EventSource: close() method" short-title: close() slug: Web/API/EventSource/close page-type: web-api-instance-method browser-compat: api.EventSource.close --- {{APIRef('WebSockets API')}} The **`close()`** method of the {{domxref("EventSource")}} interface closes the connection, if one is made, and sets the {{domxref("EventSource.readyState")}} attribute to `2` (closed). > **Note:** If the connection is already closed, the method does nothing. ## Syntax ```js-nolint close() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const button = document.querySelector("button"); const evtSource = new EventSource("sse.php"); button.onclick = () => { console.log("Connection closed"); evtSource.close(); }; ``` > **Note:** You can find a full example on GitHub — see [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventSource")}}
0
data/mdn-content/files/en-us/web/api/eventsource
data/mdn-content/files/en-us/web/api/eventsource/error_event/index.md
--- title: "EventSource: error event" short-title: error slug: Web/API/EventSource/error_event page-type: web-api-event browser-compat: api.EventSource.error_event --- {{APIRef}} The `error` event of the {{domxref("EventSource")}} API is fired when a connection with an event source fails to be opened. 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 evtSource = new EventSource("sse.php"); // addEventListener version evtSource.addEventListener("error", (e) => { console.log("An error occurred while attempting to connect."); }); // onerror version evtSource.onerror = (e) => { console.log("An error occurred while attempting to connect."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using server-sent events](/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) - [`open`](/en-US/docs/Web/API/EventSource/open_event) - [`message`](/en-US/docs/Web/API/EventSource/message_event)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/webgl_compressed_texture_etc1/index.md
--- title: WEBGL_compressed_texture_etc1 extension short-title: WEBGL_compressed_texture_etc1 slug: Web/API/WEBGL_compressed_texture_etc1 page-type: webgl-extension browser-compat: api.WEBGL_compressed_texture_etc1 --- {{APIRef("WebGL")}} The **`WEBGL_compressed_texture_etc1`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and exposes the [ETC1 compressed texture format](https://en.wikipedia.org/wiki/Ericsson_Texture_Compression). Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial). > **Note:** This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts. ## Constants The compressed texture format is exposed by a constant and can be used with the {{domxref("WebGLRenderingContext.compressedTexImage2D", "compressedTexImage2D()")}} method (note that ETC1 is **not** supported with the {{domxref("WebGLRenderingContext.compressedTexSubImage2D", "compressedTexSubImage2D()")}} method). - `ext.COMPRESSED_RGB_ETC1_WEBGL` - : Compresses 24-bit RGB data with no alpha channel. ## Examples ```js const ext = gl.getExtension("WEBGL_compressed_texture_etc1"); const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D( gl.TEXTURE_2D, 0, ext.COMPRESSED_RGB_ETC1_WEBGL, 512, 512, 0, textureData, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Ericsson Texture Compression – Wikipedia](https://en.wikipedia.org/wiki/Ericsson_Texture_Compression) - {{domxref("WEBGL_compressed_texture_etc")}} (ETC2 and EAC) - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("WebGLRenderingContext.compressedTexImage2D()")}} - {{domxref("WebGLRenderingContext.getParameter()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlmetaelement/index.md
--- title: HTMLMetaElement slug: Web/API/HTMLMetaElement page-type: web-api-interface browser-compat: api.HTMLMetaElement --- {{ APIRef("HTML DOM") }} The **`HTMLMetaElement`** interface contains descriptive metadata about a document provided in HTML as [`<meta>`](/en-US/docs/Web/HTML/Element/meta) elements. This interface inherits all of the properties and methods described in the {{domxref("HTMLElement")}} interface. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLMetaElement.charset")}} - : The character encoding for a HTML document. - {{domxref("HTMLMetaElement.content")}} - : The 'value' part of the name-value pairs of the document metadata. - {{domxref("HTMLMetaElement.httpEquiv")}} - : The name of the pragma directive, the HTTP response header, for a document. - {{domxref("HTMLMetaElement.media")}} - : The media context for a `theme-color` metadata property. - {{domxref("HTMLMetaElement.name")}} - : The 'name' part of the name-value pairs defining the named metadata of a document. - {{domxref("HTMLMetaElement.scheme")}} {{deprecated_inline}} - : Defines the scheme of the value in the {{domxref("HTMLMetaElement.content")}} attribute. This is deprecated and should not be used on new web pages. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Examples The following two examples show a general approach to using the `HTMLMetaElement` interface. For specific examples, see the pages for the individual properties as described in the [Instance properties](#instance_properties) section above. ### Setting the page description metadata The following example creates a new `<meta>` element with a `name` attribute set to [`description`](/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_the_html_specification). The `content` attribute sets a description of the document and is appended to the document `<head>`: ```js let meta = document.createElement("meta"); meta.name = "description"; meta.content = "The <meta> element can be used to provide document metadata in terms of name-value pairs, with the name attribute giving the metadata name, and the content attribute giving the value."; document.head.appendChild(meta); ``` ### Setting the viewport metadata The following example shows how to create a new `<meta>` element with a `name` attribute set to [`viewport`](/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_other_specifications). The `content` attribute sets the viewport size and is appended to the document `<head>`: ```js var meta = document.createElement("meta"); meta.name = "viewport"; meta.content = "width=device-width, initial-scale=1"; document.head.appendChild(meta); ``` For more information on setting the viewport, see [Viewport basics](/en-US/docs/Web/HTML/Viewport_meta_tag#viewport_basics). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{HTMLElement("meta")}}
0
data/mdn-content/files/en-us/web/api/htmlmetaelement
data/mdn-content/files/en-us/web/api/htmlmetaelement/name/index.md
--- title: "HTMLMetaElement: name property" short-title: name slug: Web/API/HTMLMetaElement/name page-type: web-api-instance-property browser-compat: api.HTMLMetaElement.name --- {{APIRef("HTML DOM")}} The **`HTMLMetaElement.name`** property is used in combination with {{domxref("HTMLMetaElement.content")}} to define the name-value pairs for the metadata of a document. The `name` attribute defines the metadata name and the `content` attribute defines the value. ## Value A string. ## Examples ### Reading the metadata name of a meta element The following example queries the first `<meta>` element in a document. The `name` value is logged to the console, showing that [keywords](/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_the_html_specification) have been specified for the document: ```js // given <meta name="keywords" content="documentation, HTML, web technologies"> let meta = document.querySelector("meta"); console.log(meta.name); // "keywords" ``` ### Creating a meta element with `author` metadata The following example creates a new `<meta>` element with a `name` attribute set to [`author`](/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_the_html_specification). The `content` attribute sets the author of the document and the element is appended to the document `<head>`: ```js let meta = document.createElement("meta"); meta.name = "author"; meta.content = "Franz Kafka"; document.head.appendChild(meta); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("meta")}} - [Possible values for the name attribute](/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_the_html_specification)
0
data/mdn-content/files/en-us/web/api/htmlmetaelement
data/mdn-content/files/en-us/web/api/htmlmetaelement/media/index.md
--- title: "HTMLMetaElement: media property" short-title: media slug: Web/API/HTMLMetaElement/media page-type: web-api-instance-property browser-compat: api.HTMLMetaElement.media --- {{APIRef("HTML DOM")}} The **`HTMLMetaElement.media`** property enables specifying the media for `theme-color` metadata. The `theme-color` property enables setting the color of the browser's toolbar or UI in browsers and operating systems that support this property. The `media` property enables setting different theme colors for different `media` values. ## Value A string. ## Examples ### Setting the theme color for dark mode The following example creates a new `<meta>` element with a `name` attribute set to [`theme-color`](/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_the_html_specification). The `content` attribute is set to `#3c790a`, the `media` attribute is set to `prefers-color-scheme: dark`, and the element is appended to the document `<head>`. When a user has specified a dark mode in their operating system, the `media` property can be used to set a different `theme-color`: ```js var meta = document.createElement("meta"); meta.name = "theme-color"; meta.content = "#3c790a"; meta.media = "(prefers-color-scheme: dark)"; document.head.appendChild(meta); ``` ### Setting theme colors by device size Most meta properties can be used only once. However, `theme-color` can be used multiple times if unique `media` values are provided. This example adds two meta elements with a `theme-color`; one for all devices and another for small screens. The order of matching the `media` query matters, so the more specific query should be added later in the document, as shown below: ```js // Add a theme-color for all devices meta = document.createElement("meta"); meta.name = "theme-color"; meta.content = "#ffffff"; document.head.appendChild(meta); // Add a theme-color for small devices var meta = document.createElement("meta"); meta.name = "theme-color"; meta.media = "(max-width: 600px)"; meta.content = "#000000"; document.head.appendChild(meta); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("meta")}} - [Possible values for media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries)
0
data/mdn-content/files/en-us/web/api/htmlmetaelement
data/mdn-content/files/en-us/web/api/htmlmetaelement/content/index.md
--- title: "HTMLMetaElement: content property" short-title: content slug: Web/API/HTMLMetaElement/content page-type: web-api-instance-property browser-compat: api.HTMLMetaElement.content --- {{APIRef("HTML DOM")}} The **`HTMLMetaElement.content`** property gets or sets the `content` attribute of pragma directives and named {{htmlelement("meta")}} data in conjunction with {{domxref("HTMLMetaElement.name")}} or {{domxref("HTMLMetaElement.httpEquiv")}}. For more information, see the [content](/en-US/docs/Web/HTML/Element/meta#content) attribute. ## Value A string. ## Examples ### Reading meta element content The following example queries a `<meta>` element that contains a `name` attribute with the value of `keywords`. The `content` value is logged to the console to display the [keywords](/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_the_html_specification) of the document: ```js // given <meta name="keywords" content="documentation, HTML, web"> let meta = document.querySelector("meta[name='keywords']"); console.log(meta.content); // "documentation, HTML, web" ``` ### Creating a meta element with content The following example creates a new `<meta>` element with a `name` attribute set to [`description`](/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_the_html_specification). The `content` attribute sets a description of the document and is appended to the document `<head>`: ```js let meta = document.createElement("meta"); meta.name = "description"; meta.content = "The <meta> element can be used to provide document metadata in terms of name-value pairs, with the name attribute giving the metadata name, and the content attribute giving the value."; document.head.appendChild(meta); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("meta")}} - {{domxref("HTMLMetaElement.name")}} - {{domxref("HTMLMetaElement.httpEquiv")}} - [Learn: Metadata in HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML#metadata_the_meta_element)
0
data/mdn-content/files/en-us/web/api/htmlmetaelement
data/mdn-content/files/en-us/web/api/htmlmetaelement/scheme/index.md
--- title: "HTMLMetaElement: scheme property" short-title: scheme slug: Web/API/HTMLMetaElement/scheme page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLMetaElement.scheme --- {{APIRef("HTML DOM")}}{{Deprecated_Header}} The **`HTMLMetaElement.scheme`** property defines the scheme of the value in the {{domxref("HTMLMetaElement.content")}} attribute. The `scheme` property was created to enable providing additional information to be used to interpret the value of the `content` property. The `scheme` property takes as its value a scheme format (i.e. `YYYY-MM-DD`) or scheme format name (i.e. `ISBN`), or a URI providing more information regarding the scheme format. The scheme defines the format of the value of the `content` attribute. The `scheme` content is interpreted as an extension of the element's {{domxref("HTMLMetaElement.name")}} if a browser or user agent recognizes the scheme. This property is deprecated and should not be used on new web pages. ## Value A string. ## Examples The following example queries a `<meta>` element that contains a `name` attribute with the value of `identifier`. The `scheme` value is logged to the console to display the scheme of the metadata content: ```js // given <meta name="identifier" content="1580081754" scheme="ISBN"> let meta = document.querySelector("meta[name='identifier']"); console.log(meta.scheme); // "ISBN" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("meta")}}
0
data/mdn-content/files/en-us/web/api/htmlmetaelement
data/mdn-content/files/en-us/web/api/htmlmetaelement/httpequiv/index.md
--- title: "HTMLMetaElement: httpEquiv property" short-title: httpEquiv slug: Web/API/HTMLMetaElement/httpEquiv page-type: web-api-instance-property browser-compat: api.HTMLMetaElement.httpEquiv --- {{APIRef("HTML DOM")}} The **`HTMLMetaElement.httpEquiv`** property gets or sets the pragma directive or an HTTP response header name for the {{domxref("HTMLMetaElement.content")}} attribute. For more details on the possible values, see the [http-equiv](/en-US/docs/Web/HTML/Element/meta#http-equiv) attribute. ## Value A string. ## Examples ### Reading the `http-equiv` value of a meta element The following example queries a `<meta>` element with an `http-equiv` attribute. The `http-equiv` attribute is logged to the console showing a `refresh` [pragma directive](/en-US/docs/Web/HTML/Element/meta#http-equiv) that instructs the browser to refresh the page after a number of seconds defined by the `content` attribute: ```js // given <meta http-equiv="refresh" content="10" /> let meta = document.querySelector("meta[http-equiv]"); console.log(meta.httpEquiv); // refresh console.log(meta.content); // 10 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("meta")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/barcodedetector/index.md
--- title: BarcodeDetector slug: Web/API/BarcodeDetector page-type: web-api-interface status: - experimental browser-compat: api.BarcodeDetector --- {{securecontext_header}}{{APIRef("Barcode Detector API")}}{{AvailableInWorkers}}{{SeeCompatTable}} The **`BarcodeDetector`** interface of the {{domxref('Barcode Detection API', '', '', 'nocode')}} allows detection of linear and two dimensional barcodes in images. ## Constructors - {{domxref('BarcodeDetector.BarcodeDetector', 'BarcodeDetector.BarcodeDetector()')}} {{Experimental_Inline}} - : Creates and returns a `BarcodeDetector` object, with optional `BarcodeDetectorOptions`. ## Static methods - {{domxref('BarcodeDetector/getSupportedFormats_static', 'getSupportedFormats()')}} {{Experimental_Inline}} - : Returns a {{jsxref('Promise')}} which fulfills with an {{jsxref('Array')}} of supported [barcode format types](/en-US/docs/Web/API/Barcode_Detection_API#supported_barcode_formats). ## Instance methods - {{domxref('BarcodeDetector.detect', 'detect()')}} {{Experimental_Inline}} - : Returns a {{jsxref('Promise')}} which fulfills with an array of `DetectedBarcode` objects with the following properties: - `boundingBox`: A {{domxref('DOMRectReadOnly')}}, which returns the dimensions of a rectangle representing the extent of a detected barcode, aligned with the image. - `cornerPoints`: The x and y co-ordinates of the four corner points of the detected barcode relative to the image, starting with the top left and working clockwise. This may not be square due to perspective distortions within the image. - `format`: The detected barcode format. (For a full list of formats, consult the [supported barcode format](/en-US/docs/Web/API/Barcode_Detection_API#supported_barcode_formats)) list. - `rawValue`: A string decoded from the barcode data. ## Examples ### Creating A Detector This example creates a new barcode detector object, with specified supported formats and tests for browser compatibility. ```js // check compatibility if (!("BarcodeDetector" in globalThis)) { console.log("Barcode Detector is not supported by this browser."); } else { console.log("Barcode Detector supported!"); // create new detector const barcodeDetector = new BarcodeDetector({ formats: ["code_39", "codabar", "ean_13"], }); } ``` ### Getting Supported Formats The following example calls the `getSupportFormat()` static method and logs the results to the console. ```js // check supported types BarcodeDetector.getSupportedFormats().then((supportedFormats) => { supportedFormats.forEach((format) => console.log(format)); }); ``` ### Detect Barcodes This example uses the `detect()` method to detect the barcodes within the given image. These are iterated over and the barcode data is logged to the console. ```js barcodeDetector .detect(imageEl) .then((barcodes) => { barcodes.forEach((barcode) => console.log(barcode.rawValue)); }) .catch((err) => { console.log(err); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [barcodefaq.com: A website with information about different barcodes and examples of the different types.](https://www.barcodefaq.com/) - [Accelerated Shape Detection in Images](https://developer.chrome.com/docs/capabilities/shape-detection#barcodedetector)
0
data/mdn-content/files/en-us/web/api/barcodedetector
data/mdn-content/files/en-us/web/api/barcodedetector/detect/index.md
--- title: "BarcodeDetector: detect() method" short-title: detect() slug: Web/API/BarcodeDetector/detect page-type: web-api-instance-method status: - experimental browser-compat: api.BarcodeDetector.detect --- {{securecontext_header}}{{APIRef("Barcode Detector API")}}{{AvailableInWorkers}}{{SeeCompatTable}} The **`detect()`** method of the {{domxref("BarcodeDetector")}} interface returns a {{jsxref('Promise')}} which fulfills with an {{jsxref('Array')}} of detected barcodes within an image. ## Syntax ```js-nolint detect(imageBitmapSource) ``` ### Parameters - `imageBitmapSource` - : Receives an image source as a parameter. This can be a {{domxref("HTMLImageElement")}}, a {{domxref("SVGImageElement")}}, a {{domxref("HTMLVideoElement")}}, a {{domxref("HTMLCanvasElement")}}, an {{domxref("ImageBitmap")}}, an {{domxref("OffscreenCanvas")}}, a {{domxref("VideoFrame")}}, a {{domxref('Blob')}} of type image or an {{domxref('ImageData')}} object. ### Return value Returns a {{jsxref('Promise')}} which fulfills with an array of `DetectedBarcode` objects with the following properties: - `boundingBox` - : A {{domxref('DOMRectReadOnly')}}, which returns the dimensions of a rectangle representing the extent of a detected barcode, aligned with the image. - `cornerPoints` - : The x and y co-ordinates of the four corner points of the detected barcode relative to the image, starting with the top left and working clockwise. This may not be square due to perspective distortions within the image. - `format` - : The detected barcode format. (For a full list of formats see the [supported barcode format](/en-US/docs/Web/API/Barcode_Detection_API#supported_barcode_formats)). - `rawValue` - : A string decoded from the barcode data. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if no parameter is specified or the `type` is not that of an `ImageBitmapSource`. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the `imageBitmapSource` has an origin and is not the same as the document's origin, or if the `imageBitmapSource` is a {{domxref('HTMLCanvasElement')}} and its [origin-clean](https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-origin-clean) flag is set to `false`. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the `imageBitmapSource` is an {{domxref('HTMLImageElement')}} and is not fully decoded or decoding failed, or is an {{domxref('HTMLVideoElement')}} and its {{domxref('HTMLMediaElement.readyState', 'readyState')}} is `HAVE_NOTHING` or `HAVE_METADATA`. ## Examples This example uses the `detect()` method to detect the barcodes within the given image. These are iterated over and the barcode data is logged to the console. ```js barcodeDetector .detect(imageEl) .then((barcodes) => { barcodes.forEach((barcode) => console.log(barcode.rawValue)); }) .catch((err) => { console.error(err); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/barcodedetector
data/mdn-content/files/en-us/web/api/barcodedetector/getsupportedformats_static/index.md
--- title: "BarcodeDetector: getSupportedFormats() static method" short-title: getSupportedFormats() slug: Web/API/BarcodeDetector/getSupportedFormats_static page-type: web-api-static-method status: - experimental browser-compat: api.BarcodeDetector.getSupportedFormats_static --- {{securecontext_header}}{{APIRef("Barcode Detector API")}}{{AvailableInWorkers}}{{SeeCompatTable}} The **`getSupportedFormats()`** static method of the {{domxref("BarcodeDetector")}} interface returns a {{jsxref('Promise')}} which fulfills with an {{jsxref('Array')}} of supported barcode format types. ## Syntax ```js-nolint BarcodeDetector.getSupportedFormats() ``` ### Parameters This method receives no parameters. ### Return value A {{jsxref('Promise')}} which fulfills with an {{jsxref('Array')}} of [supported barcode format types](/en-US/docs/Web/API/Barcode_Detection_API#supported_barcode_formats). ### Exceptions No exceptions are thrown. ## Examples The following example calls the `getSupportFormat()` static method and logs the results to the console. ```js // check supported types BarcodeDetector.getSupportedFormats().then((supportedFormats) => { supportedFormats.forEach((format) => console.log(format)); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/barcodedetector
data/mdn-content/files/en-us/web/api/barcodedetector/barcodedetector/index.md
--- title: "BarcodeDetector: BarcodeDetector() constructor" short-title: BarcodeDetector() slug: Web/API/BarcodeDetector/BarcodeDetector page-type: web-api-constructor status: - experimental browser-compat: api.BarcodeDetector.BarcodeDetector --- {{securecontext_header}}{{APIRef("Barcode Detector API")}}{{AvailableInWorkers}}{{SeeCompatTable}} The **`BarcodeDetector()`** constructor creates a new {{domxref("BarcodeDetector")}} object which detects linear and two-dimensional barcodes in images. ## Syntax ```js-nolint new BarcodeDetector() new BarcodeDetector(options) ``` ### Parameters - `options` {{optional_inline}} - : An options object containing a series of `BarcodeFormats` to search for in the subsequent {{domxref('BarcodeDetector.detect()','detect()')}} calls. The options are: - `formats` {{optional_inline}} - : An {{jsxref('Array')}} of barcode formats as strings. If not provided, `detect()` calls search for all supported formats. Limiting to specific formats is therefore recommended for performance reasons. To see a full list of supported formats see the [supported barcode format](/en-US/docs/Web/API/Barcode_Detection_API#supported_barcode_formats). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the `formats` is specified and the parameter is empty or contains `unknown`. ## Examples This example creates a new barcode detector object, with specified supported formats and tests for browser compatibility. ```js // check compatibility if (!("BarcodeDetector" in globalThis)) { console.log("Barcode Detector is not supported by this browser."); } else { console.log("Barcode Detector supported!"); // create new detector const barcodeDetector = new BarcodeDetector({ formats: ["code_39", "codabar", "ean_13"], }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssmathmax/index.md
--- title: CSSMathMax slug: Web/API/CSSMathMax page-type: web-api-interface browser-compat: api.CSSMathMax --- {{APIRef("CSS Typed Object Model API")}} The **`CSSMathMax`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents the CSS {{CSSXref('max','max()')}} function. It inherits properties and methods from its parent {{domxref('CSSNumericValue')}}. {{InheritanceDiagram}} ## Constructor - {{domxref("CSSMathMax.CSSMathMax", "CSSMathMax()")}} {{Experimental_Inline}} - : Creates a new `CSSMathMax` object. ## Instance properties - {{domxref('CSSMathMax.values')}} {{ReadOnlyInline}} - : Returns a {{domxref('CSSNumericArray')}} object which contains one or more {{domxref('CSSNumericValue')}} objects. ## Static methods _The interface may also inherit methods from its parent interface, {{domxref("CSSMathValue")}}._ ## Instance methods _The interface may also inherit methods from its parent interface, {{domxref("CSSMathValue")}}._ ## Examples To do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssmathmax
data/mdn-content/files/en-us/web/api/cssmathmax/values/index.md
--- title: "CSSMathMax: values property" short-title: values slug: Web/API/CSSMathMax/values page-type: web-api-instance-property browser-compat: api.CSSMathMax.values --- {{APIRef("CSS Typed Object Model API")}} The CSSMathMax.values read-only property of the {{domxref("CSSMathMax")}} interface returns a {{domxref('CSSNumericArray')}} object which contains one or more {{domxref('CSSNumericValue')}} objects. ## Value A {{domxref('CSSNumericArray')}}. ## Examples To do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssmathmax
data/mdn-content/files/en-us/web/api/cssmathmax/cssmathmax/index.md
--- title: "CSSMathMax: CSSMathMax() constructor" short-title: CSSMathMax() slug: Web/API/CSSMathMax/CSSMathMax page-type: web-api-constructor status: - experimental browser-compat: api.CSSMathMax.CSSMathMax --- {{SeeCompatTable}}{{APIRef("CSS Typed Object Model API")}} The **`CSSMathMax()`** constructor creates a new {{domxref("CSSMathMax")}} object which represents the CSS {{CSSXref('max', 'max()')}} function. ## Syntax ```js-nolint new CSSMathMax(args) ``` ### Parameters - `args` - : A list of values for the {{domxref('CSSMathProduct')}} object to be either a double integer or a {{domxref('CSSNumericValue')}}. ### Exceptions - [`TypeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) - : Thrown if there is a _failure_ when adding all of the values in args. ## Examples To do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/css_properties_and_values_api/index.md
--- title: CSS Properties and Values API slug: Web/API/CSS_Properties_and_Values_API page-type: web-api-overview browser-compat: - api.CSSPropertyRule - api.CSS.registerProperty_static --- {{DefaultAPISidebar("CSS Properties and Values API")}} The **CSS Properties and Values API** — part of the [CSS Houdini](/en-US/docs/Web/API/Houdini_APIs) umbrella of APIs — allows developers to explicitly define their {{cssxref('--*', 'CSS custom properties')}}, allowing for property type checking, default values, and properties that do or do not inherit their value. ## Interfaces - {{domxref('CSS/registerProperty_static', 'CSS.registerProperty')}} - : Defines how a browser should parse {{cssxref('--*', 'CSS custom properties')}}. Access this interface through {{domxref('CSS/registerProperty_static', 'CSS.registerProperty')}} in [JavaScript](/en-US/docs/Web/JavaScript). - {{cssxref('@property')}} - : Defines how a browser should parse {{cssxref('--*', 'CSS custom properties')}}. Access this interface through {{cssxref('@property')}} [at-rule](/en-US/docs/Web/CSS/At-rule) in [CSS](/en-US/docs/Web/CSS). ## Examples The following will register a {{cssxref('--*', 'CSS custom property')}} named `--my-prop` using {{domxref('CSS/registerProperty_static', 'CSS.registerProperty')}} in [JavaScript](/en-US/docs/Web/JavaScript). `--my-prop` will use the CSS color syntax, it will have a default value of `#c0ffee`, and it will not inherit its value: ```js window.CSS.registerProperty({ name: "--my-color", syntax: "<color>", inherits: false, initialValue: "#c0ffee", }); ``` The same registration can take place in [CSS](/en-US/docs/Web/CSS) using the {{cssxref('@property')}} [at-rule](/en-US/docs/Web/CSS/At-rule): ```css @property --my-color { syntax: "<color>"; inherits: false; initial-value: #c0ffee; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the CSS properties and values API](/en-US/docs/Web/API/CSS_Properties_and_Values_API/guide) - [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API) - [CSS Typed Object Model](/en-US/docs/Web/API/CSS_Typed_OM_API) - [Houdini APIs](/en-US/docs/Web/API/Houdini_APIs)
0
data/mdn-content/files/en-us/web/api/css_properties_and_values_api
data/mdn-content/files/en-us/web/api/css_properties_and_values_api/guide/index.md
--- title: Using the CSS properties and values API slug: Web/API/CSS_Properties_and_Values_API/guide page-type: guide browser-compat: api.CSS.registerProperty_static --- {{DefaultAPISidebar("CSS Properties and Values API")}} The **CSS Properties and Values API** — part of the [CSS Houdini](/en-US/docs/Web/API/Houdini_APIs) umbrella of APIs — allows the registration of {{cssxref('--*', 'CSS custom properties')}}, allowing for property type checking, default values, and properties that do or do not inherit their value. ## Registering a custom property Registering a custom property allows you to tell the browser how the custom property should behave; what types are allowed, whether the custom property inherits its value, and what the default value of the custom property is. There are two ways to register a property, in [JavaScript](/en-US/docs/Web/JavaScript) or in [CSS](/en-US/docs/Web/CSS). ### CSS.registerProperty The following will register a {{cssxref('--*', 'CSS custom property')}} named `--my-prop` using {{domxref('CSS/registerProperty_static', 'CSS.registerProperty')}}. `--my-prop` will use the CSS color syntax, it will have a default value of `#c0ffee`, and it will not inherit its value: ```js window.CSS.registerProperty({ name: "--my-prop", syntax: "<color>", inherits: false, initialValue: "#c0ffee", }); ``` ### @property The same registration can take place in CSS. The following will register a {{cssxref('--*', 'CSS custom property')}} named `--my-prop` using the {{cssxref('@property')}} [at-rule](/en-US/docs/Web/CSS/At-rule). `--my-prop` will use the CSS color syntax, it will have a default value of `#c0ffee`, and it will not inherit its value: ```css @property --my-prop { syntax: "<color>"; inherits: false; initial-value: #c0ffee; } ``` ## Using registered custom properties One of the advantages of registering a property is that the browser now knows how to handle your custom property through things like transitions! When a property isn't registered, the browser doesn't know how to treat it, so it assumes that any value can be used and therefore can't animate it. When a property has a registered syntax, though, the browser can optimize around that syntax, including being able to animate it! In this example, the custom property `--registered` has been registered using the syntax `<color>` and then used in a linear gradient. That property is then transitioned on hover or focus to a different color. Notice that the transition works with the registered property but not the unregistered one! ### HTML ```html <button class="registered">Background Registered</button> <button class="unregistered">Background Not Registered</button> ``` ### CSS ```css .registered { --registered: #c0ffee; background-image: linear-gradient(to right, #fff, var(--registered)); transition: --registered 1s ease-in-out; } .registered:hover, .registered:focus { --registered: #b4d455; } .unregistered { --unregistered: #c0ffee; background-image: linear-gradient(to right, #fff, var(--unregistered)); transition: --unregistered 1s ease-in-out; } .unregistered:hover, .unregistered:focus { --unregistered: #b4d455; } button { height: 40vh; display: block; width: 100%; font-size: 3vw; } ``` ### JavaScript ```js window.CSS.registerProperty({ name: "--registered", syntax: "<color>", inherits: false, initialValue: "red", }); ``` ### Result {{EmbedLiveSample("Using_registered_custom_properties", 320, 320)}} While not functionally accurate, a good way to think about the difference between the unregistered property in the above example and the registered property is the difference between a {{cssxref('custom-ident')}} and a number when trying to animate {{cssxref('height')}}. You cannot transition or animate from `auto` to a number because the browser doesn't know the value of `auto` until it's calculated. With an unregistered property, the browser likewise doesn't know what the value _may be_ until it's calculated, and because of that, it can't set up a transition from one value to another. When registered, though, you've told the browser what type of value it should expect, and because it knows that, it can then set up the transitions properly. ## Gotchas There are two gotchas when registering a property. The first is that, once a property is registered, there's no way to update it, and trying to re-register it with [JavaScript](/en-US/docs/Web/JavaScript) will throw an error indicating it's already been defined. Second, unlike standard properties, registered properties aren't validated when they're parsed. Rather, they're validated when they're computed. That means both that invalid values won't appear as invalid when inspecting the element's properties, and that including an invalid property after a valid one won't fall back to the valid property. An invalid property will, however, fall back to its registered default. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssscale/index.md
--- title: CSSScale slug: Web/API/CSSScale page-type: web-api-interface browser-compat: api.CSSScale --- {{APIRef("CSS Typed Object Model API")}} The **`CSSScale`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents the [scale()](/en-US/docs/Web/CSS/transform-function/scale) and [scale3d()](/en-US/docs/Web/CSS/transform-function/scale3d) values of the individual {{CSSXRef('transform')}} property in CSS. It inherits properties and methods from its parent {{domxref('CSSTransformValue')}}. {{InheritanceDiagram}} ## Constructor - {{domxref("CSSScale.CSSScale", "CSSScale()")}} - : Creates a new `CSSScale` object. ## Instance properties - {{domxref('CSSScale.x','x')}} - : Returns or sets the x-axis value. - {{domxref('CSSScale.y','y')}} - : Returns or sets the y-axis value. - {{domxref('CSSScale.z','z')}} - : Returns or sets the z-axis value. ## Examples To do. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssscale
data/mdn-content/files/en-us/web/api/cssscale/z/index.md
--- title: "CSSScale: z property" short-title: z slug: Web/API/CSSScale/z page-type: web-api-instance-property browser-compat: api.CSSScale.z --- {{APIRef("CSS Typed OM")}} The **`z`** property of the {{domxref("CSSScale")}} interface representing the z-component of the translating vector. A positive value moves the element towards the viewer, and a negative value farther away. If this value is present then the transform is a 3D transform and the `is2D` property will be set to false. ## Value A double integer or a {{domxref("CSSNumericValue")}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssscale
data/mdn-content/files/en-us/web/api/cssscale/y/index.md
--- title: "CSSScale: y property" short-title: "y" slug: Web/API/CSSScale/y page-type: web-api-instance-property browser-compat: api.CSSScale.y --- {{APIRef("CSS Typed OM")}} The **`y`** property of the {{domxref("CSSScale")}} interface gets and sets the ordinate or y-axis of the translating vector. ## Value A double integer or a {{domxref("CSSNumericValue")}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssscale
data/mdn-content/files/en-us/web/api/cssscale/x/index.md
--- title: "CSSScale: x property" short-title: x slug: Web/API/CSSScale/x page-type: web-api-instance-property browser-compat: api.CSSScale.x --- {{APIRef("CSS Typed OM")}} The **`x`** property of the {{domxref("CSSScale")}} interface gets and sets the abscissa or x-axis of the translating vector. ## Value A double integer or a {{domxref("CSSNumericValue")}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssscale
data/mdn-content/files/en-us/web/api/cssscale/cssscale/index.md
--- title: "CSSScale: CSSScale() constructor" short-title: CSSScale() slug: Web/API/CSSScale/CSSScale page-type: web-api-constructor browser-compat: api.CSSScale.CSSScale --- {{APIRef("CSS Typed OM")}} The **`CSSScale()`** constructor creates a new {{domxref("CSSScale")}} object representing the [scale()](/en-US/docs/Web/CSS/transform-function/scale) and [scale3d()](/en-US/docs/Web/CSS/transform-function/scale3d) values of the individual {{CSSXref('transform')}} property in CSS. ## Syntax ```js-nolint new CSSScale(x, y) new CSSScale(x, y, z) ``` ### Parameters - {{domxref('CSSScale.x','x')}} - : A value for the x-axis of the {{domxref('CSSScale')}} object to be constructed. This must either be a double integer or a {{domxref('CSSNumericValue')}}. - {{domxref('CSSScale.y','y')}} - : A value for the y-axis of the {{domxref('CSSScale')}} object to be constructed. This must either be a double integer or a {{domxref('CSSNumericValue')}}. - {{domxref('CSSScale.z','z')}} {{optional_inline}} - : A value for the z-axis of the {{domxref('CSSScale')}} object to be constructed. This must either be a double integer or a {{domxref('CSSNumericValue')}}. If a value is passed for the `z-axis` this is a 3d transform. The value of `is2D` will be set to false. ## Examples To do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0