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/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/symbols/index.md
--- title: "CSSCounterStyleRule: symbols property" short-title: symbols slug: Web/API/CSSCounterStyleRule/symbols page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.symbols --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`symbols`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/symbols","symbols")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `symbols` gives us the value "◰ ◳ ◲ ◱". ```css @counter-style box-corner { system: fixed; symbols: ◰ ◳ ◲ ◱; suffix: ": "; negative: "-"; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].symbols); // "◰ ◳ ◲ ◱" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/prefix/index.md
--- title: "CSSCounterStyleRule: prefix property" short-title: prefix slug: Web/API/CSSCounterStyleRule/prefix page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.prefix --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`prefix`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/prefix","prefix")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `prefix` gives us the value "Chapter ". ```css @counter-style chapters { system: numeric; symbols: "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"; prefix: "Chapter "; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].prefix); // "Chapter " ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/pad/index.md
--- title: "CSSCounterStyleRule: pad property" short-title: pad slug: Web/API/CSSCounterStyleRule/pad page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.pad --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`pad`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/pad", "pad")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `pad` gives us the value "0". ```css @counter-style box-corner { system: numeric; symbols: "0" "1" "2" "3" "4" "5"; pad: 2 "0"; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].pad); // "0" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/fallback/index.md
--- title: "CSSCounterStyleRule: fallback property" short-title: fallback slug: Web/API/CSSCounterStyleRule/fallback page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.fallback --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`fallback`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/fallback","fallback")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string. ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `fallback` gives us the value "disc". ```css @counter-style box-corner { system: fixed; symbols: ◰ ◳ ◲ ◱; suffix: ": "; fallback: disc; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].fallback); // "disc" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/range/index.md
--- title: "CSSCounterStyleRule: range property" short-title: range slug: Web/API/CSSCounterStyleRule/range page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.range --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`range`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/range","range")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `range` gives us the value "2 4, 7 9". ```css @counter-style range-multi-example { system: cyclic; symbols: "\25A0" "\25A1"; range: 2 4, 7 9; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].range); // "2 4, 7 9" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/system/index.md
--- title: "CSSCounterStyleRule: system property" short-title: system slug: Web/API/CSSCounterStyleRule/system page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.system --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`system`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/system", "system")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `system` gives us the value "fixed". ```css @counter-style box-corner { system: fixed; symbols: ◰ ◳ ◲ ◱; suffix: ": "; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].system); // "fixed" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/suffix/index.md
--- title: "CSSCounterStyleRule: suffix property" short-title: suffix slug: Web/API/CSSCounterStyleRule/suffix page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.suffix --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`suffix`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/suffix","suffix")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `suffix` gives us the value ": ". ```css @counter-style box-corner { system: fixed; symbols: ◰ ◳ ◲ ◱; suffix: ": "; negative: "-"; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].suffix); // ": " ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfecolormatrixelement/index.md
--- title: SVGFEColorMatrixElement slug: Web/API/SVGFEColorMatrixElement page-type: web-api-interface browser-compat: api.SVGFEColorMatrixElement --- {{APIRef("SVG")}} The **`SVGFEColorMatrixElement`** interface corresponds to the {{SVGElement("feColorMatrix")}} element. {{InheritanceDiagram}} ## Constants <table class="no-markdown"> <tbody> <tr> <th>Name</th> <th>Value</th> <th>Description</th> </tr> <tr> <td><code>SVG_FECOLORMATRIX_TYPE_UNKNOWN</code></td> <td>0</td> <td> The type is not one of predefined types. It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. </td> </tr> <tr> <td><code>SVG_FECOLORMATRIX_TYPE_MATRIX</code></td> <td>1</td> <td>Corresponds to the <code>matrix</code> value.</td> </tr> <tr> <td><code>SVG_FECOLORMATRIX_TYPE_SATURATE</code></td> <td>2</td> <td>Corresponds to the <code>saturate</code> value.</td> </tr> <tr> <td><code>SVG_FECOLORMATRIX_TYPE_HUEROTATE</code></td> <td>3</td> <td>Corresponds to <code>hueRotate</code> value.</td> </tr> <tr> <td><code>SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA</code></td> <td>4</td> <td>Corresponds to <code>luminanceToAlpha</code> value.</td> </tr> </tbody> </table> ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGFEColorMatrixElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element. - {{domxref("SVGFEColorMatrixElement.in1")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element. - {{domxref("SVGFEColorMatrixElement.result")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element. - {{domxref("SVGFEColorMatrixElement.type")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("type")}} attribute of the given element. It takes one of the `SVG_FECOLORMATRIX_TYPE_*` constants defined on this interface. - {{domxref("SVGFEColorMatrixElement.values")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumberList")}} corresponding to the {{SVGAttr("values")}} attribute of the given element. - {{domxref("SVGFEColorMatrixElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element. - {{domxref("SVGFEColorMatrixElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGFEColorMatrixElement.y")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element. ## Instance methods _This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}_. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("feColorMatrix")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/beforeunloadevent/index.md
--- title: BeforeUnloadEvent slug: Web/API/BeforeUnloadEvent page-type: web-api-interface browser-compat: api.BeforeUnloadEvent --- {{APIRef}} The **`BeforeUnloadEvent`** interface represents the event object for the {{domxref("Window/beforeunload_event", "beforeunload")}} event, which is fired when the current window, contained document, and associated resources are about to be unloaded. See the {{domxref("Window/beforeunload_event", "beforeunload")}} event reference for detailed guidance on using this event. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{DOMxRef("Event")}}._ - {{domxref("BeforeUnloadEvent.returnValue", "returnValue")}} {{Deprecated_Inline}} - : When set to a [truthy](/en-US/docs/Glossary/Truthy) value, triggers a browser-controlled confirmation dialog asking users to confirm if they want to leave the page when they try to close or reload it. This is a legacy feature, and best practice is to trigger the dialog by invoking `event.preventDefault()`, while also setting `returnValue` to support legacy cases. ## Instance methods _Inherits methods from its parent, {{DOMxRef("Event")}}._ ## Examples In the following example we have an HTML text {{htmlelement("input")}} to represent some data that could be changed and require saving: ```html <form> <input type="text" name="name" id="name" /> </form> ``` Our JavaScript attaches an {{domxref("Element/input_event", "input")}} event listener to the `<input>` element that listens for changes in the inputted value. When the value is updated to a non-empty value, a {{domxref("Window.beforeunload_event", "beforeunload")}} event listener is attached to the {{domxref("Window")}} object. If the value becomes an empty string again (i.e. the value is deleted), the `beforeunload` event listener is removed again — as mentioned above in the [Usage notes](#usage_notes), the listener should be removed when there is no unsaved data to warn about. The `beforeunload` event handler function invokes `event.preventDefault()` to trigger the warning dialog when the user closes or navigates the tab. We have also included `event.returnValue = true` in the handler function so that any browsers that don't support the `event.preventDefault()` mechanism will still run the demo correctly. ```js const beforeUnloadHandler = (event) => { // Recommended event.preventDefault(); // Included for legacy support, e.g. Chrome/Edge < 119 event.returnValue = true; }; const nameInput = document.querySelector("#name"); nameInput.addEventListener("input", (event) => { if (event.target.value !== "") { window.addEventListener("beforeunload", beforeUnloadHandler); } else { window.removeEventListener("beforeunload", beforeUnloadHandler); } }); ``` When the `<input>` value is non-empty, if you try to close, navigate, or reload the page the browser displays the warning dialog. Try it out: {{EmbedLiveSample("Examples", "100%", 50)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window/beforeunload_event", "beforeunload")}} event
0
data/mdn-content/files/en-us/web/api/beforeunloadevent
data/mdn-content/files/en-us/web/api/beforeunloadevent/returnvalue/index.md
--- title: "BeforeUnloadEvent: returnValue property" short-title: returnValue slug: Web/API/BeforeUnloadEvent/returnValue page-type: web-api-instance-property status: - deprecated browser-compat: api.BeforeUnloadEvent.returnValue --- {{APIRef("HTML DOM")}}{{deprecated_header}} The **`returnValue`** property of the {{domxref("BeforeUnloadEvent")}} interface, when set to a truthy value, triggers a browser-generated confirmation dialog asking users to confirm if they _really_ want to leave the page when they try to close or reload it, or navigate somewhere else. This is intended to help prevent loss of unsaved data. > **Note:** `returnValue` is a legacy feature, and best practice is to trigger the dialog by invoking {{domxref("Event.preventDefault()")}} on the `BeforeUnloadEvent` object, while also setting `returnValue` to support legacy cases. See the {{domxref("Window/beforeunload_event", "beforeunload")}} event reference for detailed up-to-date guidance. ## Value `returnValue` is initialized to an empty string (`""`) value. Setting it to just about any [truthy](/en-US/docs/Glossary/Truthy) value will cause the dialog to be triggered on page close/reload, however note that it also requires [sticky activation](/en-US/docs/Glossary/Sticky_activation). In other words, the browser will only show the dialog if the frame or any embedded frame receives a user gesture or user interaction. If the user has never interacted with the page, then there is no user data to save, so no legitimate use case for the dialog. > **Note:** A generic browser-specified string is displayed in the dialog. This cannot be controlled by the webpage code. ## Examples See the {{domxref("Window/beforeunload_event", "beforeunload")}} event reference page for a best practice example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtciceparameters/index.md
--- title: RTCIceParameters slug: Web/API/RTCIceParameters page-type: web-api-interface browser-compat: api.RTCIceParameters --- {{APIRef("WebRTC")}} The **`RTCIceParameters`** dictionary specifies the username fragment and password assigned to an {{Glossary("ICE")}} session. During ICE negotiation, each peer's username fragment and password are recorded in an `RTCIceParameters` object, which can be obtained from the {{domxref("RTCIceTransport")}} by calling its {{domxref("RTCIceTransport.getLocalParameters", "getLocalParameters()")}} or {{domxref("RTCIceTransport.getRemoteParameters", "getRemoteParameters()")}} method, depending on which end interests you. ## Instance properties - {{domxref("RTCIceParameters.usernameFragment", "usernameFragment")}} - : A string specifying the value of the ICE session's username fragment field, `ufrag`. - {{domxref("RTCIceParameters.password", "password")}} - : A string specifying the session's password string. ## Usage notes The username fragment and password uniquely identify the remote peer for the duration of the ICE session, and are used to both ensure security and to avoid crosstalk across multiple ongoing ICE sessions. See {{domxref("RTCIceCandidate.usernameFragment")}} for further information. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtciceparameters
data/mdn-content/files/en-us/web/api/rtciceparameters/usernamefragment/index.md
--- title: "RTCIceParameters: usernameFragment property" short-title: usernameFragment slug: Web/API/RTCIceParameters/usernameFragment page-type: web-api-instance-property browser-compat: api.RTCIceParameters.usernameFragment --- {{APIRef("WebRTC")}} The **{{domxref("RTCIceParameters")}}** dictionary's **`usernameFragment`** property specifies the username fragment ("ufrag") that uniquely identifies the corresponding ICE session for the duration of the current ICE session. ## Value A string containing the username fragment that, in tandem with the {{domxref("RTCIceParameters.password", "password")}}, uniquely identify the ICE session being used by the transport. The string may be up to 256 characters long. See {{domxref("RTCIceCandidate.usernameFragment")}} to learn more about username fragments and their role in a connection. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtciceparameters
data/mdn-content/files/en-us/web/api/rtciceparameters/password/index.md
--- title: "RTCIceParameters: password property" short-title: password slug: Web/API/RTCIceParameters/password page-type: web-api-instance-property browser-compat: api.RTCIceParameters.password --- {{APIRef("WebRTC")}} The **{{domxref("RTCIceParameters")}}** dictionary's **`password`** property specifies the ICE password that, in tandem with the {{domxref("RTCIceParameters.usernameFragment", "usernameFragment")}}, uniquely identifies an ICE session for its entire duration. ## Value A string containing the password that corresponds to the transport's `usernameFragment` string ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgsvgelement/index.md
--- title: SVGSVGElement slug: Web/API/SVGSVGElement page-type: web-api-interface browser-compat: api.SVGSVGElement --- {{APIRef("SVG")}} The **`SVGSVGElement`** interface provides access to the properties of {{SVGElement("svg")}} elements, as well as methods to manipulate them. This interface contains also various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent, {{domxref("SVGGraphicsElement")}}._ - {{domxref("SVGSVGElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given {{SVGElement("svg")}} element. - {{domxref("SVGSVGElement.y")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given {{SVGElement("svg")}} element. - {{domxref("SVGSVGElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given {{SVGElement("svg")}} element. - {{domxref("SVGSVGElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given {{SVGElement("svg")}} element. - {{domxref("SVGSVGElement.pixelUnitToMillimeterX")}} {{Deprecated_Inline}} - : A float representing the size of the pixel unit (as defined by CSS2) along the x-axis of the viewport, which represents a unit somewhere in the range of 70dpi to 120dpi, and, on systems that support this, might actually match the characteristics of the target medium. On systems where it is impossible to know the size of a pixel, a suitable default pixel size is provided. - {{domxref("SVGSVGElement.pixelUnitToMillimeterY")}} {{Deprecated_Inline}} - : A float representing the size of a pixel unit along the y-axis of the viewport. - {{domxref("SVGSVGElement.screenPixelToMillimeterX")}} {{Deprecated_Inline}} - : User interface (UI) events in DOM Level 2 indicate the screen positions at which the given UI event occurred. When the browser actually knows the physical size of a "screen unit", this float attribute will express that information; otherwise, user agents will provide a suitable default value (such as `.28mm`). - {{domxref("SVGSVGElement.screenPixelToMillimeterY")}} {{Deprecated_Inline}} - : Corresponding size of a screen pixel along the y-axis of the viewport. - {{domxref("SVGSVGElement.useCurrentView")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : The initial view (i.e., before magnification and panning) of the current innermost SVG document fragment can be either the "standard" view, i.e., based on attributes on the {{SVGElement("svg")}} element such as {{SVGAttr("viewBox")}}) or on a "custom" view (i.e., a hyperlink into a particular {{SVGElement("view")}} or other element). If the initial view is the "standard" view, then this attribute is `false`. If the initial view is a "custom" view, then this attribute is `true`. - {{domxref("SVGSVGElement.currentView")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : An {{domxref("SVGViewSpec")}} defining the initial view (i.e., before magnification and panning) of the current innermost SVG document fragment. The meaning depends on the situation: If the initial view was a "standard" view, then: - the values for {{SVGAttr("viewBox")}}, {{SVGAttr("preserveAspectRatio")}} and {{SVGAttr("zoomAndPan")}} within {{SVGAttr("currentView")}} will match the values for the corresponding DOM attributes that are on `SVGSVGElement` directly - the value for {{SVGAttr("transform")}} within {{SVGAttr("currentView")}} will be `null` If the initial view was a link into a {{SVGElement("view")}} element, then: - the values for {{SVGAttr("viewBox")}}, {{SVGAttr("preserveAspectRatio")}} and {{SVGAttr("zoomAndPan")}} within {{SVGAttr("currentView")}} will correspond to the corresponding attributes for the given {{SVGElement("view")}} element - the value for {{SVGAttr("transform")}} within {{SVGAttr("currentView")}} will be `null` If the initial view was a link into another element (i.e., other than a {{SVGElement("view")}}), then: - the values for {{SVGAttr("viewBox")}}, {{SVGAttr("preserveAspectRatio")}} and {{SVGAttr("zoomAndPan")}} within {{SVGAttr("currentView")}} will match the values for the corresponding DOM attributes that are on `SVGSVGElement` directly for the closest ancestor {{SVGElement("svg")}} element - the values for {{SVGAttr("transform")}} within {{SVGAttr("currentView")}} will be `null` If the initial view was a link into the SVG document fragment using an SVG view specification fragment identifier (i.e., `#svgView(…)`), then: - the values for {{SVGAttr("viewBox")}}, {{SVGAttr("preserveAspectRatio")}}, {{SVGAttr("zoomAndPan")}}, {{SVGAttr("transform")}} within {{SVGAttr("currentView")}} will correspond to the values from the SVG view specification fragment identifier - {{domxref("SVGSVGElement.currentScale")}} - : On an outermost {{SVGElement("svg")}} element, this float attribute indicates the current scale factor relative to the initial view to take into account user magnification and panning operations. DOM attributes `currentScale` and `currentTranslate` are equivalent to the 2×3 matrix `[a b c d e f] = [currentScale 0 0 currentScale currentTranslate.x currentTranslate.y]`. If "magnification" is enabled (i.e., `zoomAndPan="magnify"`), then the effect is as if an extra transformation were placed at the outermost level on the SVG document fragment (i.e., outside the outermost {{SVGElement("svg")}} element). - {{domxref("SVGSVGElement.currentTranslate")}} {{ReadOnlyInline}} - : An {{domxref("SVGPoint")}} representing the translation factor that takes into account user "magnification" corresponding to an outermost {{SVGElement("svg")}} element. The behavior is undefined for `<svg>` elements that are not at the outermost level. ## Instance methods _This interface also inherits methods from its parent, {{domxref("SVGGraphicsElement")}}._ - {{domxref("SVGSVGElement.suspendRedraw()")}} {{Deprecated_Inline}} - : Takes a time-out value which indicates that redraw shall not occur until: the corresponding `unsuspendRedraw()` call has been made, an `unsuspendRedrawAll()` call has been made, or its timer has timed out. In environments that do not support interactivity (e.g., print media), then redraw shall not be suspended. Calls to `suspendRedraw()` and `unsuspendRedraw()` should, but need not be, made in balanced pairs. To suspend redraw actions as a collection of SVG DOM changes occur, precede the changes to the SVG DOM with a method call similar to: ```js const suspendHandleID = suspendRedraw(maxWaitMilliseconds); ``` and follow the changes with a method call similar to: ```js unsuspendRedraw(suspendHandleID); ``` Note that multiple `suspendRedraw()` calls can be used at once, and that each such method call is treated independently of the other `suspendRedraw()` method calls. - {{domxref("SVGSVGElement.unsuspendRedraw()")}} {{Deprecated_Inline}} - : Cancels a specified `suspendRedraw()` by providing a unique suspend handle ID that was returned by a previous `suspendRedraw()` call. - {{domxref("SVGSVGElement.unsuspendRedrawAll()")}} {{Deprecated_Inline}} - : Cancels all currently active `suspendRedraw()` method calls. This method is most useful at the very end of a set of SVG DOM calls to ensure that all pending `suspendRedraw()` method calls have been cancelled. - {{domxref("SVGSVGElement.forceRedraw()")}} {{Deprecated_Inline}} - : In rendering environments supporting interactivity, forces the user agent to immediately redraw all regions of the viewport that require updating. - {{domxref("SVGSVGElement.pauseAnimations()")}} - : Suspends (i.e., pauses) all currently running animations that are defined within the SVG document fragment corresponding to this {{SVGElement("svg")}} element, causing the animation clock corresponding to this document fragment to stand still until it is unpaused. - {{domxref("SVGSVGElement.unpauseAnimations()")}} - : Resumes (i.e., unpauses) currently running animations that are defined within the SVG document fragment, causing the animation clock to continue from the time at which it was suspended. - {{domxref("SVGSVGElement.animationsPaused()")}} - : Returns `true` if this SVG document fragment is in a paused state. - {{domxref("SVGSVGElement.getCurrentTime()")}} - : Returns the current time in seconds relative to the start time for the current SVG document fragment. If `getCurrentTime()` is called before the document timeline has begun (for example, by script running in a {{SVGElement("script")}} element before the document's `SVGLoad` event is dispatched), then `0` is returned. - {{domxref("SVGSVGElement.setCurrentTime()")}} - : Adjusts the clock for this SVG document fragment, establishing a new current time. If `setCurrentTime()` is called before the document timeline has begun (for example, by script running in a {{SVGElement("script")}} element before the document's `SVGLoad` event is dispatched), then the value of seconds in the last invocation of the method gives the time that the document will seek to once the document timeline has begun. - {{domxref("SVGSVGElement.getIntersectionList()")}} - : Returns a {{domxref("NodeList")}} of graphics elements whose rendered content intersects the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in {{SVGAttr("pointer-events")}} processing. - {{domxref("SVGSVGElement.getEnclosureList()")}} - : Returns a {{domxref("NodeList")}} of graphics elements whose rendered content is entirely contained within the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in {{SVGAttr("pointer-events")}} processing. - {{domxref("SVGSVGElement.checkIntersection()")}} - : Returns `true` if the rendered content of the given element intersects the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in {{SVGAttr("pointer-events")}} processing. - {{domxref("SVGSVGElement.checkEnclosure()")}} - : Returns `true` if the rendered content of the given element is entirely contained within the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in {{SVGAttr("pointer-events")}} processing. - {{domxref("SVGSVGElement.deselectAll()")}} - : Unselects any selected objects, including any selections of text strings and type-in bars. - {{domxref("SVGSVGElement.createSVGNumber()")}} - : Creates an {{domxref("SVGNumber")}} object outside of any document trees. The object is initialized to `0`. - {{domxref("SVGSVGElement.createSVGLength()")}} - : Creates an {{domxref("SVGLength")}} object outside of any document trees. The object is initialized to `0` user units. - {{domxref("SVGSVGElement.createSVGAngle()")}} - : Creates an {{domxref("SVGAngle")}} object outside of any document trees. The object is initialized to a value of `0` degrees (unitless). - {{domxref("SVGSVGElement.createSVGPoint()")}} - : Creates an {{domxref("SVGPoint")}} object outside of any document trees. The object is initialized to the point `(0,0)` in the user coordinate system. - {{domxref("SVGSVGElement.createSVGMatrix()")}} - : Creates an {{domxref("DOMMatrix", "SVGMatrix")}} object outside of any document trees. The object is initialized to the identity matrix. - {{domxref("SVGSVGElement.createSVGRect()")}} - : Creates an {{domxref("SVGRect")}} object outside of any document trees. The object is initialized such that all values are set to `0` user units. - {{domxref("SVGSVGElement.createSVGTransform()")}} - : Creates an {{domxref("SVGTransform")}} object outside of any document trees. The object is initialized to an identity matrix transform (`SVG_TRANSFORM_MATRIX`). - {{domxref("SVGSVGElement.createSVGTransformFromMatrix()")}} - : Creates an {{domxref("SVGTransform")}} object outside of any document trees. The object is initialized to the given matrix transform (i.e., `SVG_TRANSFORM_MATRIX`). The values from the parameter matrix are copied, the matrix parameter is not adopted as `SVGTransform::matrix`. - {{domxref("SVGSVGElement.getElementById()")}} - : Searches this SVG document fragment (i.e., the search is restricted to a subset of the document tree) for an Element whose `id` is given by `elementId`. If an Element is found, that Element is returned. If no such element exists, returns `null`. Behavior is not defined if more than one element has this id. ## Event handlers The following {{domxref("Window")}} `onXYZ` event handler properties are also available as aliases targeting the `window` object. However, it is advised to listen to them on the `window` object directly rather than on `SVGSVGElement`. > **Note:** Using `addEventListener()` on `SVGSVGElement` will not work for the `onXYZ` event handlers listed below. Listen to the events on the {{domxref("window")}} object instead. - {{domxref("window.afterprint_event", "SVGSVGElement.onafterprint")}} - : Fired after the associated document has started printing or the print preview has been closed. - {{domxref("window.beforeprint_event", "SVGSVGElement.onbeforeprint")}} - : Fired when the associated document is about to be printed or previewed for printing. - {{domxref("window.beforeunload_event", "SVGSVGElement.onbeforeunload")}} - : Fired when the window, the document and its resources are about to be unloaded. - {{domxref("window.gamepadconnected_event", "SVGSVGElement.ongamepadconnected")}} - : Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used. - {{domxref("window.gamepaddisconnected_event", "SVGSVGElement.ongamepaddisconnected")}} - : Fired when the browser detects that a gamepad has been disconnected. - {{domxref("window.hashchange_event", "SVGSVGElement.onhashchange")}} - : Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol). - {{domxref("window.languagechange_event", "SVGSVGElement.onlanguagechange")}} - : Fired when the user's preferred language changes. - {{domxref("window.message_event", "SVGSVGElement.onmessage")}} - : Fired when the window receives a message, for example from a call to [`Window.postMessage()`](/en-US/docs/Web/API/Window/postMessage) from another browsing context. - {{domxref("window.messageerror_event", "SVGSVGElement.onmessageerror")}} - : Fired when the window receives a message that can't be deserialized. - {{domxref("window.offline_event", "SVGSVGElement.onoffline")}} - : Fired when the browser has lost access to the network and the value of {{domxref("Navigator.onLine")}} switches to `false`. - {{domxref("window.online_event", "SVGSVGElement.ononline")}} - : Fired when the browser has gained access to the network and the value of {{domxref("Navigator.onLine")}} switches to `true`. - {{domxref("window.pagehide_event", "SVGSVGElement.onpagehide")}} - : Fired when the browser hides the current page in the process of presenting a different page from the session's history. - {{domxref("window.pageshow_event", "SVGSVGElement.onpageshow")}} - : Fired when the browser displays the window's document due to navigation. - {{domxref("window.popstate_event", "SVGSVGElement.onpopstate")}} - : Fired when the active history entry changes while the user navigates the session history. - {{domxref("window.rejectionhandled_event", "SVGSVGElement.onrejectionhandled")}} - : Fired whenever a JavaScript {{jsxref("Promise")}} is rejected and the rejection has been handled. - {{domxref("window.storage_event", "SVGSVGElement.onstorage")}} - : Fired when a storage area (`localStorage`) has been modified in the context of another document. - {{domxref("window.unhandledrejection_event", "SVGSVGElement.onunhandledrejection")}} - : Fired whenever a {{jsxref("Promise")}} is rejected but the rejection was not handled. - {{domxref("window.unload_event", "SVGSVGElement.onunload")}} - : Fired when the document is being unloaded. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("circle")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/range/index.md
--- title: Range slug: Web/API/Range page-type: web-api-interface browser-compat: api.Range --- {{APIRef("DOM")}} The **`Range`** interface represents a fragment of a document that can contain nodes and parts of text nodes. A range can be created by using the {{ domxref("Document.createRange()") }} method. Range objects can also be retrieved by using the {{ domxref("Selection/getRangeAt", "getRangeAt()") }} method of the {{ domxref("Selection") }} object or the {{domxref("Document/caretRangeFromPoint", "caretRangeFromPoint()")}} method of the {{domxref("Document")}} object. There also is the {{domxref("Range.Range()", "Range()")}} constructor available. {{InheritanceDiagram}} ## Instance properties _There are no inherited properties._ - {{domxref("Range.collapsed")}} {{ReadOnlyInline}} - : Returns a boolean value indicating whether the range's start and end points are at the same position. - {{domxref("Range.commonAncestorContainer")}} {{ReadOnlyInline}} - : Returns the deepest {{ domxref("Node") }} that contains the `startContainer` and `endContainer` nodes. - {{domxref("Range.endContainer")}} {{ReadOnlyInline}} - : Returns the {{ domxref("Node") }} within which the `Range` ends. - {{domxref("Range.endOffset")}} {{ReadOnlyInline}} - : Returns a number representing where in the `endContainer` the `Range` ends. - {{domxref("Range.startContainer")}} {{ReadOnlyInline}} - : Returns the {{ domxref("Node") }} within which the `Range` starts. - {{domxref("Range.startOffset")}} {{ReadOnlyInline}} - : Returns a number representing where in the `startContainer` the `Range` starts. ## Constructor - {{ domxref("Range.Range()", "Range()") }} - : Returns a `Range` object with the global {{domxref("Document")}} as its start and end. ## Instance methods _There are no inherited methods._ - {{ domxref("Range.collapse()")}} - : Collapses the `Range` to one of its boundary points. - {{ domxref("Range.compareBoundaryPoints()")}} - : Compares the boundary points of the `Range` with another `Range`. - {{ domxref("Range.compareNode()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a constant representing whether the {{domxref("Node")}} is before, after, inside, or surrounding the range. - {{ domxref("Range.comparePoint()")}} - : Returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the `Range`. - {{ domxref("Range.cloneContents()")}} - : Returns a {{ domxref("DocumentFragment") }} copying the nodes of a `Range`. - {{ domxref("Range.cloneRange()")}} - : Returns a `Range` object with boundary points identical to the cloned `Range`. - {{ domxref("Range.createContextualFragment()")}} - : Returns a {{ domxref("DocumentFragment") }} created from a given string of code. - {{ domxref("Range.deleteContents()")}} - : Removes the contents of a `Range` from the {{ domxref("Document") }}. - {{ domxref("Range.detach()")}} - : Does nothing. Kept for compatibility. - {{ domxref("Range.extractContents()")}} - : Moves contents of a `Range` from the document tree into a {{ domxref("DocumentFragment") }}. - {{ domxref("Range.getBoundingClientRect()") }} - : Returns a {{ domxref("DOMRect") }} object which bounds the entire contents of the `Range`; this would be the union of all the rectangles returned by {{ domxref("range.getClientRects()") }}. - {{ domxref("Range.getClientRects()") }} - : Returns a list of {{ domxref("DOMRect") }} objects that aggregates the results of {{ domxref("Element.getClientRects()") }} for all the elements in the `Range`. - {{ domxref("Range.isPointInRange()")}} - : Returns a `boolean` indicating whether the given point is in the `Range`. - {{ domxref("Range.insertNode()")}} - : Insert a {{ domxref("Node") }} at the start of a `Range`. - {{ domxref("Range.intersectsNode()")}} - : Returns a `boolean` indicating whether the given node intersects the `Range`. - {{ domxref("Range.selectNode()")}} - : Sets the `Range` to contain the {{ domxref("Node") }} and its contents. - {{ domxref("Range.selectNodeContents()")}} - : Sets the `Range` to contain the contents of a {{ domxref("Node") }}. - {{ domxref("Range.setEnd()")}} - : Sets the end position of a `Range`. - {{ domxref("Range.setStart()")}} - : Sets the start position of a `Range`. - {{ domxref("Range.setEndAfter()")}} - : Sets the end position of a `Range` relative to another {{ domxref("Node") }}. - {{ domxref("Range.setEndBefore()")}} - : Sets the end position of a `Range` relative to another {{ domxref("Node") }}. - {{ domxref("Range.setStartAfter()")}} - : Sets the start position of a `Range` relative to another {{ domxref("Node") }}. - {{ domxref("Range.setStartBefore()")}} - : Sets the start position of a `Range` relative to another {{ domxref("Node") }}. - {{ domxref("Range.surroundContents()")}} - : Moves content of a `Range` into a new {{ domxref("Node") }}. - {{ domxref("Range.toString()")}} - : Returns the text of the `Range`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/detach/index.md
--- title: "Range: detach() method" short-title: detach() slug: Web/API/Range/detach page-type: web-api-instance-method browser-compat: api.Range.detach --- {{ApiRef("DOM")}} The **`Range.detach()`** method does nothing. It used to disable the {{domxref("Range")}} object and enable the browser to release associated resources. The method has been kept for compatibility. ## Syntax ```js-nolint detach() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); range.detach(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/comparepoint/index.md
--- title: "Range: comparePoint() method" short-title: comparePoint() slug: Web/API/Range/comparePoint page-type: web-api-instance-method browser-compat: api.Range.comparePoint --- {{ApiRef("DOM")}} The **`Range.comparePoint()`** method returns `-1`, `0`, or `1` depending on whether the `referenceNode` is before, the same as, or after the {{domxref("Range")}}. If the _reference node_ is a {{domxref("Node")}} of type {{domxref("Text")}}, {{domxref("Comment")}}, or {{domxref("CDATASection")}}, then offset is the number of characters from the start of _reference node_. For other {{domxref("Node")}} types, offset is the number of child nodes between the start of the _reference node_. ## Syntax ```js-nolint comparePoint(referenceNode, offset) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} to compare with the {{domxref("Range")}}. - `offset` - : An integer greater than or equal to zero representing the offset inside the _referenceNode_. ### Return value Returns `-1`, `0`, or `1`. ## Examples ```js range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); returnValue = range.comparePoint(document.getElementsByTagName("p").item(0), 1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/collapse/index.md
--- title: "Range: collapse() method" short-title: collapse() slug: Web/API/Range/collapse page-type: web-api-instance-method browser-compat: api.Range.collapse --- {{APIRef("DOM")}} The **`Range.collapse()`** method collapses the {{domxref("Range")}} to one of its boundary points. A collapsed {{domxref("Range")}} is empty, containing no content, specifying a single-point in a DOM tree. To determine if a {{domxref("Range")}} is already collapsed, see the {{domxref("Range.collapsed")}} property. ## Syntax ```js-nolint collapse() collapse(toStart) ``` ### Parameters - `toStart` {{optional_inline}} - : A boolean value: `true` collapses the {{domxref("Range")}} to its start, `false` to its end. If omitted, it defaults to `false` {{experimental_inline}}. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const range = document.createRange(); const referenceNode = document.getElementsByTagName("div").item(0); range.selectNode(referenceNode); range.collapse(true); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/surroundcontents/index.md
--- title: "Range: surroundContents() method" short-title: surroundContents() slug: Web/API/Range/surroundContents page-type: web-api-instance-method browser-compat: api.Range.surroundContents --- {{ApiRef("DOM")}} The **`Range.surroundContents()`** method moves content of the {{ domxref("Range") }} into a new node, placing the new node at the start of the specified range. This method is nearly equivalent to `newNode.appendChild(range.extractContents()); range.insertNode(newNode)`. After surrounding, the boundary points of the `range` include `newNode`. An exception will be thrown, however, if the {{ domxref("Range") }} splits a non-{{ domxref("Text") }} node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail. ## Syntax ```js-nolint surroundContents(newParent) ``` ### Parameters - `newParent` - : A {{ domxref("Node") }} with which to surround the contents. ### Return value None ({{jsxref("undefined")}}). ## Examples ### HTML ```html <span class="header-text">Put this in a headline</span> ``` ### JavaScript ```js const range = document.createRange(); const newParent = document.createElement("h1"); range.selectNode(document.querySelector(".header-text")); range.surroundContents(newParent); ``` ### Result {{EmbedLiveSample("Examples")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/intersectsnode/index.md
--- title: "Range: intersectsNode() method" short-title: intersectsNode() slug: Web/API/Range/intersectsNode page-type: web-api-instance-method browser-compat: api.Range.intersectsNode --- {{ApiRef("DOM")}} The **`Range.intersectsNode()`** method returns a boolean indicating whether the given {{domxref("Node")}} intersects the {{domxref("Range")}}. ## Syntax ```js-nolint intersectsNode(referenceNode) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} to compare with the {{domxref("Range")}}. ### Return value A boolean. ## Examples ```js const range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); const intersectingNode = range.intersectsNode( document.getElementsByTagName("p").item(0), ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/tostring/index.md
--- title: "Range: toString() method" short-title: toString() slug: Web/API/Range/toString page-type: web-api-instance-method browser-compat: api.Range.toString --- {{ApiRef("DOM")}} The **`Range.toString()`** method is a {{Glossary("stringifier")}} returning the text of the {{domxref("Range")}}. Alerting the contents of a {{domxref("Range")}} makes an implicit `toString()` call, so comparing range and text through an alert dialog is ineffective. ## Syntax ```js-nolint toString() ``` ### Parameters None. ### Return value A string. ## Examples ### HTML ```html <p> This example logs <em>everything</em> between the emphasized <em>words</em>. Look at the output below. </p> <p id="log"></p> ``` ### JavaScript ```js const range = document.createRange(); range.setStartBefore(document.getElementsByTagName("em").item(0), 0); range.setEndAfter(document.getElementsByTagName("em").item(1), 0); document.getElementById("log").textContent = range.toString(); ``` ### Result {{EmbedLiveSample("Examples")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/comparenode/index.md
--- title: "Range: compareNode() method" short-title: compareNode() slug: Web/API/Range/compareNode page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Range.compareNode --- {{APIRef("DOM")}}{{deprecated_header}}{{Non-standard_Header}} The **`Range.compareNode()`** returns a constant indicating the position of the {{DOMxRef("Node")}}. The possible values are: - `NODE_BEFORE` (`0`) - : Node starts before the Range - `NODE_AFTER` (`1`) - : Node ends after the Range - `NODE_BEFORE_AND_AFTER` (`2`) - : Node starts before and ends after the Range - `NODE_INSIDE` (`3`) - : Node starts after and ends before the Range, i.e. the Node is completely selected by the Range. > **Warning:** This method [has been removed](/en-US/docs/Mozilla/Firefox/Releases/3/Site_compatibility) from [Gecko 1.9](/en-US/docs/Mozilla/Firefox/Releases/3) and > will not exist in future versions of Firefox, which was the only browser implementing > it; you should switch to {{DOMxRef("Range.compareBoundaryPoints()")}} as soon as > possible. The following function can be used as replacement: ```js function rangeCompareNode(range, node) { const nodeRange = node.ownerDocument.createRange(); try { nodeRange.selectNode(node); } catch (e) { nodeRange.selectNodeContents(node); } const nodeIsBefore = range.compareBoundaryPoints(Range.START_TO_START, nodeRange) === 1; const nodeIsAfter = range.compareBoundaryPoints(Range.END_TO_END, nodeRange) === -1; if (nodeIsBefore && !nodeIsAfter) return 0; if (!nodeIsBefore && nodeIsAfter) return 1; if (nodeIsBefore && nodeIsAfter) return 2; return 3; } ``` ## Syntax ```js-nolint compareNode(referenceNode) ``` ### Parameters - `referenceNode` - : The {{DOMxRef("Node")}} to compare with the `Range`. ### Return value A constant indicating the position of the {{DOMxRef("Node")}}. ## Examples ```js range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); returnValue = range.compareNode(document.getElementsByTagName("p").item(0)); ``` ## Notes This method is obsolete; you should use the W3C DOM {{DOMxRef("Range.compareBoundaryPoints()")}} method. ## Specifications This method is not standard and therefore not part of any specification. ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/startcontainer/index.md
--- title: "Range: startContainer property" short-title: startContainer slug: Web/API/Range/startContainer page-type: web-api-instance-property browser-compat: api.Range.startContainer --- {{ApiRef("DOM")}} The **`Range.startContainer`** read-only property returns the {{domxref("Node")}} within which the `Range` starts. To change the start position of a node, use one of the {{domxref("Range.setStart()")}} methods. ## Value A {{domxref("Node")}} object. ## Examples ```js range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); startRangeNode = range.startContainer; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/createcontextualfragment/index.md
--- title: "Range: createContextualFragment() method" short-title: createContextualFragment() slug: Web/API/Range/createContextualFragment page-type: web-api-instance-method browser-compat: api.Range.createContextualFragment --- {{ApiRef("DOM")}} The **`Range.createContextualFragment()`** method returns a {{domxref("DocumentFragment")}} by invoking the HTML fragment parsing algorithm or the XML fragment parsing algorithm with the start of the range (the _parent_ of the selected node) as the context node. The HTML fragment parsing algorithm is used if the range belongs to a `Document` whose HTMLness bit is set. In the HTML case, if the context node would be `html`, for historical reasons the fragment parsing algorithm is invoked with `body` as the context instead. ## Syntax ```js-nolint createContextualFragment(tagString) ``` ### Parameters - `tagString` - : Text that contains text and tags to be converted to a document fragment. ### Return value A {{domxref("DocumentFragment")}} object. ## Examples ```js const tagString = "<div>I am a div node</div>"; const range = document.createRange(); // Make the parent of the first div in the document become the context node range.selectNode(document.getElementsByTagName("div").item(0)); const documentFragment = range.createContextualFragment(tagString); document.body.appendChild(documentFragment); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/extractcontents/index.md
--- title: "Range: extractContents() method" short-title: extractContents() slug: Web/API/Range/extractContents page-type: web-api-instance-method browser-compat: api.Range.extractContents --- {{ApiRef("DOM")}} The **`Range.extractContents()`** method moves contents of the {{ domxref("Range") }} from the document tree into a {{ domxref("DocumentFragment") }}. Event listeners added using DOM Events are not retained during extraction. HTML attribute events are retained or duplicated as they are for the {{domxref("Node.cloneNode()")}} method. HTML `id` attributes are also cloned, which can lead to an invalid document if a partially-selected node is extracted and appended to the document. Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid. ## Syntax ```js-nolint extractContents() ``` ### Parameters None. ### Return value A {{ domxref("DocumentFragment") }} object. ## Examples ### Basic example ```js const range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); const documentFragment = range.extractContents(); document.body.appendChild(documentFragment); ``` ### Moving items between containers This example lets you move items between two containers. Select one or more item, and then click "swap" to move them to the opposite container. #### HTML ```html <p id="list1">123456</p> <button id="swap">Swap selected item(s)</button> <p id="list2">abcdef</p> ``` #### CSS ```css body { pointer-events: none; } p { border: 1px solid; font-size: 2em; padding: 0.3em; } button { font-size: 1.2em; padding: 0.5em; pointer-events: auto; } ``` #### JavaScript ```js const list1 = document.getElementById("list1"); const list2 = document.getElementById("list2"); const button = document.getElementById("swap"); button.addEventListener("click", (e) => { selection = window.getSelection(); for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i); if ( range.commonAncestorContainer === list1 || range.commonAncestorContainer.parentNode === list1 ) { const documentFragment = range.extractContents(); list2.appendChild(documentFragment); } else if ( range.commonAncestorContainer === list2 || range.commonAncestorContainer.parentNode === list2 ) { const documentFragment = range.extractContents(); list1.appendChild(documentFragment); } } }); ``` #### Result {{EmbedLiveSample("Moving_items_between_containers", 700, 300)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/clonerange/index.md
--- title: "Range: cloneRange() method" short-title: cloneRange() slug: Web/API/Range/cloneRange page-type: web-api-instance-method browser-compat: api.Range.cloneRange --- {{ APIRef("DOM") }} The **`Range.cloneRange()`** method returns a {{domxref("Range")}} object with boundary points identical to the cloned {{domxref("Range")}}. The returned clone is copied by value, not reference, so a change in either {{domxref("Range")}} does not affect the other. ## Syntax ```js-nolint cloneRange() ``` ### Parameters None. ### Return value A {{domxref("Range")}} object. ## Examples ```js range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); clone = range.cloneRange(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/selectnode/index.md
--- title: "Range: selectNode() method" short-title: selectNode() slug: Web/API/Range/selectNode page-type: web-api-instance-method browser-compat: api.Range.selectNode --- {{ApiRef("DOM")}} The **`Range.selectNode()`** method sets the {{domxref("Range")}} to contain the {{domxref("Node")}} and its contents. The parent {{domxref("Node")}} of the start and end of the {{domxref("Range")}} will be the same as the parent of the _referenceNode_. ## Syntax ```js-nolint selectNode(referenceNode) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} to select within a {{domxref("Range")}}. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js let range = document.createRange(); let referenceNode = document.getElementsByTagName("div").item(0); range.selectNode(referenceNode); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/getboundingclientrect/index.md
--- title: "Range: getBoundingClientRect() method" short-title: getBoundingClientRect() slug: Web/API/Range/getBoundingClientRect page-type: web-api-instance-method browser-compat: api.Range.getBoundingClientRect --- {{ApiRef("DOM")}} The **`Range.getBoundingClientRect()`** method returns a {{ domxref("DOMRect") }} object that bounds the contents of the range; this is a rectangle enclosing the union of the bounding rectangles for all the elements in the range. This method is useful for determining the viewport coordinates of the cursor or selection inside a text box. See {{domxref("Element.getBoundingClientRect()")}} for details on the returned value. ## Syntax ```js-nolint getBoundingClientRect() ``` ### Parameters None. ### Return value A {{domxref("DOMRect")}} object that encloses the union of the bounding rectangles for all elements in the range. ## Examples ### HTML ```html <div id="highlight"></div> <p> This example positions a "highlight" rectangle behind the contents of a range. The range's content <em>starts here</em> and continues on until it <em>ends here</em>. The bounding client rectangle contains everything selected in the range. </p> ``` ### CSS ```css #highlight { background: yellow; position: absolute; z-index: -1; } p { width: 200px; } ``` ### JavaScript ```js const range = document.createRange(); range.setStartBefore(document.getElementsByTagName("em").item(0)); range.setEndAfter(document.getElementsByTagName("em").item(1)); const clientRect = range.getBoundingClientRect(); const highlight = document.getElementById("highlight"); highlight.style.left = `${clientRect.x}px`; highlight.style.top = `${clientRect.y}px`; highlight.style.width = `${clientRect.width}px`; highlight.style.height = `${clientRect.height}px`; ``` ### Result {{EmbedLiveSample("Examples")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Range.getClientRects()")}} - finer-grained result for non-rectangular ranges (e.g., when the selection wraps onto the next line); - {{domxref("Element.getBoundingClientRect()")}} - {{domxref("Document.caretPositionFromPoint()")}} - to get the (node, offset) from viewport coordinates.
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/insertnode/index.md
--- title: "Range: insertNode() method" short-title: insertNode() slug: Web/API/Range/insertNode page-type: web-api-instance-method browser-compat: api.Range.insertNode --- {{ApiRef("DOM")}} The **`Range.insertNode()`** method inserts a node at the start of the {{domxref("Range")}}. The new node is inserted at the start boundary point of the `Range`. If the new node is to be added to a text {{domxref("Node")}}, that `Node` is split at the insertion point, and the insertion occurs between the two text nodes. If the new node is a document fragment, the children of the document fragment are inserted instead. ## Syntax ```js-nolint insertNode(newNode) ``` ### Parameters - `newNode` - : The {{domxref("Node")}} to insert at the start of the `range`. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js range = document.createRange(); newNode = document.createElement("p"); newNode.appendChild(document.createTextNode("New Node Inserted Here")); range.selectNode(document.getElementsByTagName("div").item(0)); range.insertNode(newNode); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/setendafter/index.md
--- title: "Range: setEndAfter() method" short-title: setEndAfter() slug: Web/API/Range/setEndAfter page-type: web-api-instance-method browser-compat: api.Range.setEndAfter --- {{ApiRef("DOM")}} The **`Range.setEndAfter()`** method sets the end position of a {{domxref("Range")}} relative to another {{domxref("Node")}}. The parent `Node` of end of the `Range` will be the same as that for the `referenceNode`. ## Syntax ```js-nolint setEndAfter(referenceNode) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} to end the {{domxref("Range")}} after. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const range = document.createRange(); const referenceNode = document.getElementsByTagName("div").item(0); range.setEndAfter(referenceNode); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/commonancestorcontainer/index.md
--- title: "Range: commonAncestorContainer property" short-title: commonAncestorContainer slug: Web/API/Range/commonAncestorContainer page-type: web-api-instance-property browser-compat: api.Range.commonAncestorContainer --- {{ApiRef("DOM")}} The **`Range.commonAncestorContainer`** read-only property returns the deepest — or furthest down the document tree — {{domxref("Node")}} that contains both [boundary points](https://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Position-h3) of the {{domxref("Range")}}. This means that if {{domxref("Range.startContainer")}} and {{domxref("Range.endContainer")}} both refer to the same node, this node is the **common ancestor container**. Since a `Range` need not be continuous, and may also partially select nodes, this is a convenient way to find a `Node` which encloses a `Range`. This property is read-only. To change the ancestor container of a `Node`, consider using the various methods available to set the start and end positions of the `Range`, such as {{domxref("Range.setStart()")}} and {{domxref("Range.setEnd()")}}. ## Value A {{domxref("Node")}} object. ## Examples In this example, we create an event listener to handle {{domxref("Element/pointerup_event", "pointerup")}} events on a list. The listener gets the common ancestors of each piece of selected text and triggers an animation to highlight them. ### HTML ```html <ul> <li> Strings <ul> <li>Cello</li> <li> Violin <ul> <li>First Chair</li> <li>Second Chair</li> </ul> </li> </ul> </li> <li> Woodwinds <ul> <li>Clarinet</li> <li>Oboe</li> </ul> </li> </ul> ``` ### CSS The `.highlight` class created below uses a set of CSS {{cssxref("@keyframes")}} to animate a fading outline. ```css .highlight { animation: highlight linear 1s; } @keyframes highlight { from { outline: 1px solid #f00f; } to { outline: 1px solid #f000; } } ``` ```css hidden body { padding: 1px; } ``` ### JavaScript ```js document.addEventListener("pointerup", (e) => { const selection = window.getSelection(); if (selection.type === "Range") { for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i); playAnimation(range.commonAncestorContainer); } } }); function playAnimation(el) { if (el.nodeType === Node.TEXT_NODE) { el = el.parentNode; } el.classList.remove("highlight"); setTimeout(() => { el.classList.add("highlight"); }, 0); } ``` ### Result {{EmbedLiveSample("Examples", 700, 190)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/startoffset/index.md
--- title: "Range: startOffset property" short-title: startOffset slug: Web/API/Range/startOffset page-type: web-api-instance-property browser-compat: api.Range.startOffset --- {{ApiRef("DOM")}} The **`Range.startOffset`** read-only property returns a number representing where in the `startContainer` the `Range` starts. If the `startContainer` is a {{domxref("Node")}} of type {{domxref("Text")}}, {{domxref("Comment")}}, or {{domxref("CDATASection")}}, then the offset is the number of characters from the start of the `startContainer` to the boundary point of the {{domxref("Range")}}. For other {{domxref("Node")}} types, the `startOffset` is the number of child nodes between the start of the `startContainer` and the boundary point of the {{domxref("Range")}}. To change the `startOffset` of a {{domxref("Range")}}, use the {{domxref("Range.setStart")}} method. ## Value A number. ## Examples ```js const range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); const startRangeOffset = range.startOffset; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/setstartafter/index.md
--- title: "Range: setStartAfter() method" short-title: setStartAfter() slug: Web/API/Range/setStartAfter page-type: web-api-instance-method browser-compat: api.Range.setStartAfter --- {{ApiRef("DOM")}} The **`Range.setStartAfter()`** method sets the start position of a {{domxref("Range")}} relative to a {{domxref("Node")}}. The parent {{domxref("Node")}} of the start of the {{domxref("Range")}} will be the same as that for the `referenceNode`. ## Syntax ```js-nolint setStartAfter(referenceNode) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} to start the {{domxref("Range")}} after. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const range = document.createRange(); const referenceNode = document.getElementsByTagName("div").item(0); range.setStartAfter(referenceNode); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/setstart/index.md
--- title: "Range: setStart() method" short-title: setStart() slug: Web/API/Range/setStart page-type: web-api-instance-method browser-compat: api.Range.setStart --- {{ApiRef("DOM")}} The **`Range.setStart()`** method sets the start position of a {{ domxref("Range") }}. If the `startNode` is a {{domxref("Node")}} of type {{domxref("Text")}}, {{domxref("Comment")}}, or {{domxref("CDataSection")}}, then `startOffset` is the number of characters from the start of `startNode`. For other `Node` types, `startOffset` is the number of child nodes between the start of the `startNode`. Setting the start point below (lower in the document) the end point will result in a collapsed range with the start and end points both set to the specified start position. ## Syntax ```js-nolint setStart(startNode, startOffset) ``` ### Parameters - `startNode` - : The {{ domxref("Node") }} where the {{ domxref("Range") }} should start. - `startOffset` - : An integer greater than or equal to zero representing the offset for the start of the {{ domxref("Range") }} from the start of `startNode`. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Highlight part of an element This example uses the `Range.setStart()` and {{domxref("Range.setEnd()")}} methods to add part of an address to a range. The selected range is then highlighted using {{domxref("Range.surroundContents()")}}. The address contains nine nodes: five text nodes, and four {{htmlElement("br")}} elements. #### HTML ```html <p id="address"> Wyatt Earp<br /> 101 E. Main St.<br /> Dodge City, KS<br /> 67801<br /> USA </p> <hr /> <p>Nodes in the original address:</p> <ol id="log"></ol> ``` #### JavaScript ```js const address = document.getElementById("address"); const log = document.getElementById("log"); // Log info address.childNodes.forEach((node) => { const li = document.createElement("li"); li.textContent = `${node.nodeName}, ${node.nodeValue}`; log.appendChild(li); }); // Highlight the street and city const startOffset = 2; // Start at third node: 101 E. Main St. const endOffset = 5; // End at fifth node: Dodge City, KS const range = document.createRange(); range.setStart(address, startOffset); range.setEnd(address, endOffset); const mark = document.createElement("mark"); range.surroundContents(mark); ``` #### Result {{EmbedLiveSample("Highlight_part_of_an_element", 700, 400)}} ### Get characters from a text node This example uses the `Range.setStart()` and {{domxref("Range.setEnd()")}} methods to define the contents of a range. The resulting range contains the first through fifth characters within a text node. #### HTML ```html <p id="content">0123456789</p> <p id="log"></p> ``` #### JavaScript ```js const element = document.getElementById("content"); const textNode = element.childNodes[0]; const range = document.createRange(); range.setStart(textNode, 0); // Start at first character range.setEnd(textNode, 5); // End at fifth character document.getElementById("log").textContent = range; ``` #### Result {{EmbedLiveSample("Get_characters_from_a_text_node", 700, 100)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/ispointinrange/index.md
--- title: "Range: isPointInRange() method" short-title: isPointInRange() slug: Web/API/Range/isPointInRange page-type: web-api-instance-method browser-compat: api.Range.isPointInRange --- {{ApiRef("DOM")}} The **`Range.isPointInRange()`** method returns a boolean indicating whether the given point is in the {{domxref("Range")}}. It returns `true` if the point (cursor position) at `offset` within `ReferenceNode` is within this range. ## Syntax ```js-nolint isPointInRange(referenceNode, offset) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} to compare with the {{domxref("Range")}}. - `offset` - : The offset into {{domxref("Node")}} of the point to compare with the {{domxref("Range")}}. ### Return value A boolean. ## Examples ```js range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); bool = range.isPointInRange(document.getElementsByTagName("p").item(0), 1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/getclientrects/index.md
--- title: "Range: getClientRects() method" short-title: getClientRects() slug: Web/API/Range/getClientRects page-type: web-api-instance-method browser-compat: api.Range.getClientRects --- {{ApiRef("DOM")}} The **`Range.getClientRects()`** method returns a list of {{ domxref("DOMRect") }} objects representing the area of the screen occupied by the [range](/en-US/docs/Web/API/Range). This is created by aggregating the results of calls to {{ domxref("Element.getClientRects()") }} for all the elements in the range. ## Syntax ```js-nolint getClientRects() ``` ### Parameters None. ### Return value An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) sequence of {{domxref("DOMRect")}} objects. ## Examples ### Logging selected client rect sizes #### HTML ```html <div></div> <pre id="output"></pre> ``` #### CSS ```css div { height: 80px; width: 200px; background-color: blue; } ``` #### JavaScript ```js const range = document.createRange(); range.selectNode(document.querySelector("div")); rectList = range.getClientRects(); const output = document.querySelector("#output"); for (const rect of rectList) { output.textContent = `${output.textContent}\n${rect.width}:${rect.height}`; } ``` #### Result {{EmbedLiveSample("Logging selected client rect sizes")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Range")}}
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/deletecontents/index.md
--- title: "Range: deleteContents() method" short-title: deleteContents() slug: Web/API/Range/deleteContents page-type: web-api-instance-method browser-compat: api.Range.deleteContents --- {{ApiRef("DOM")}} The **`Range.deleteContents()`** method removes the contents of the {{ domxref("Range") }} from the {{ domxref("Document") }}. Unlike {{ domxref("Range.extractContents()") }}, this method does not return a {{domxref("DocumentFragment")}} containing the deleted content. ## Syntax ```js-nolint deleteContents() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); range.deleteContents(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/compareboundarypoints/index.md
--- title: "Range: compareBoundaryPoints() method" short-title: compareBoundaryPoints() slug: Web/API/Range/compareBoundaryPoints page-type: web-api-instance-method browser-compat: api.Range.compareBoundaryPoints --- {{ApiRef("DOM")}} The **`Range.compareBoundaryPoints()`** method compares the boundary points of the {{domxref("Range")}} with those of another range. ## Syntax ```js-nolint compareBoundaryPoints(how, sourceRange) ``` ### Parameters - `how` - : A constant describing the comparison method: - `Range.END_TO_END` compares the end boundary-point of _sourceRange_ to the end boundary-point of `Range`. - `Range.END_TO_START` compares the end boundary-point of _sourceRange_ to the start boundary-point of `Range`. - `Range.START_TO_END` compares the start boundary-point of _sourceRange_ to the end boundary-point of `Range`. - `Range.START_TO_START` compares the start boundary-point of _sourceRange_ to the start boundary-point of `Range`. - `sourceRange` - : A {{domxref("Range")}} to compare boundary points with the range. ### Return value A number, `-1`, `0`, or `1`, indicating whether the corresponding boundary-point of the {{domxref("Range")}} is respectively before, equal to, or after the corresponding boundary-point of _sourceRange_. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the value of the `how` parameter is invalid. ## Examples ```js const range = document.createRange(); range.selectNode(document.querySelector("div")); const sourceRange = document.createRange(); sourceRange.selectNode(document.getElementsByTagName("div")[1]); const compare = range.compareBoundaryPoints(Range.START_TO_END, sourceRange); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/selectnodecontents/index.md
--- title: "Range: selectNodeContents() method" short-title: selectNodeContents() slug: Web/API/Range/selectNodeContents page-type: web-api-instance-method browser-compat: api.Range.selectNodeContents --- {{ApiRef("DOM")}} The **`Range.selectNodeContents()`** method sets the {{domxref("Range")}} to contain the contents of a {{domxref("Node")}}. The parent `Node` of the start and end of the `Range` will be the reference node. The `startOffset` is 0, and the `endOffset` is the number of child `Node`s or number of characters contained in the reference node. ## Syntax ```js-nolint selectNodeContents(referenceNode) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} whose contents will be selected within a {{domxref("Range")}}. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const range = document.createRange(); const referenceNode = document.querySelector("div"); range.selectNodeContents(referenceNode); ``` ### Live sample This example lets the user select and deselect a paragraph with buttons. {{domxref("Document.createRange()")}}, `Range.selectNodeContents()`, and {{domxref("Selection.addRange()")}} are used to select the content. {{domxref("Window.getSelection()")}} and {{domxref("Selection.removeAllRanges()")}} are used to deselect it. #### HTML ```html <p id="p"> <strong>Use the buttons below</strong> to select or deselect the contents of this paragraph. </p> <button id="select-button">Select paragraph</button> <button id="deselect-button">Deselect paragraph</button> ``` #### JavaScript ```js const p = document.getElementById("p"); const selectButton = document.getElementById("select-button"); const deselectButton = document.getElementById("deselect-button"); selectButton.addEventListener("click", (e) => { // Clear any current selection const selection = window.getSelection(); selection.removeAllRanges(); // Select paragraph const range = document.createRange(); range.selectNodeContents(p); selection.addRange(range); }); deselectButton.addEventListener("click", (e) => { const selection = window.getSelection(); selection.removeAllRanges(); }); ``` #### Result {{EmbedLiveSample("Live_sample")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/endoffset/index.md
--- title: "Range: endOffset property" short-title: endOffset slug: Web/API/Range/endOffset page-type: web-api-instance-property browser-compat: api.Range.endOffset --- {{ApiRef("DOM")}} The **`Range.endOffset`** read-only property returns a number representing where in the {{domxref("Range.endContainer")}} the {{domxref("Range")}} ends. If the `endContainer` is a {{domxref("Node")}} of type {{domxref("Text")}}, {{domxref("Comment")}}, or {{domxref("CDATASection")}}, then the offset is the number of characters from the start of the `endContainer` to the boundary point of the {{domxref("Range")}}. For other {{domxref("Node")}} types, the `endOffset` is the number of child nodes between the start of the `endContainer` and the boundary point of the {{domxref("Range")}}. This property is read-only. To change the `endOffset` of a {{domxref("Range")}}, use one of the {{domxref("Range.setEnd")}} methods. ## Value A number. ## Examples ```js const range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); endRangeOffset = range.endOffset; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/clonecontents/index.md
--- title: "Range: cloneContents() method" short-title: cloneContents() slug: Web/API/Range/cloneContents page-type: web-api-instance-method browser-compat: api.Range.cloneContents --- {{ APIRef("DOM") }} The **`Range.cloneContents()`** returns a {{ domxref("DocumentFragment") }} copying the objects of type {{ domxref("Node") }} included in the {{ domxref("Range") }}. Event listeners added using {{domxref("EventTarget.addEventListener()", "addEventListener()")}} are not copied during cloning. HTML attribute events are duplicated as they are for the {{ domxref("Node.cloneNode()") }} method. HTML `id` attributes are also cloned, which can lead to an invalid document through cloning. Partially selected nodes include the parent tags necessary to make the document fragment valid. ## Syntax ```js-nolint cloneContents() ``` ### Parameters None. ### Return value A {{domxref("DocumentFragment") }} object. ## Examples ```js range = document.createRange(); range.selectNode(document.getElementsByTagName("div").item(0)); documentFragment = range.cloneContents(); document.body.appendChild(documentFragment); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/setstartbefore/index.md
--- title: "Range: setStartBefore() method" short-title: setStartBefore() slug: Web/API/Range/setStartBefore page-type: web-api-instance-method browser-compat: api.Range.setStartBefore --- {{ApiRef("DOM")}} The **`Range.setStartBefore()`** method sets the start position of a {{domxref("Range")}} relative to another {{domxref("Node")}}. The parent {{domxref("Node")}} of the start of the {{domxref("Range")}} will be the same as that for the `referenceNode`. ## Syntax ```js-nolint setStartBefore(referenceNode) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} before which the {{domxref("Range")}} should start. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const range = document.createRange(); const referenceNode = document.getElementsByTagName("div").item(0); range.setStartBefore(referenceNode); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/setendbefore/index.md
--- title: "Range: setEndBefore() method" short-title: setEndBefore() slug: Web/API/Range/setEndBefore page-type: web-api-instance-method browser-compat: api.Range.setEndBefore --- {{ApiRef("DOM")}} The **`Range.setEndBefore()`** method sets the end position of a `Range` relative to another {{domxref("Node")}}. The parent `Node` of end of the `Range` will be the same as that for the `referenceNode`. ## Syntax ```js-nolint setEndBefore(referenceNode) ``` ### Parameters - `referenceNode` - : The {{domxref("Node")}} to end the `Range` before. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const range = document.createRange(); const referenceNode = document.getElementsByTagName("div").item(0); range.setEndBefore(referenceNode); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/endcontainer/index.md
--- title: "Range: endContainer property" short-title: endContainer slug: Web/API/Range/endContainer page-type: web-api-instance-property browser-compat: api.Range.endContainer --- {{ApiRef("DOM")}} The **`Range.endContainer`** read-only property returns the {{domxref("Node")}} within which the {{domxref("Range")}} ends. To change the end position of a node, use the {{domxref("Range.setEnd()")}} method or a similar one. ## Value A {{domxref("Node")}} object. ## Examples ```js const range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); endRangeNode = range.endContainer; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/range/index.md
--- title: "Range: Range() constructor" short-title: Range() slug: Web/API/Range/Range page-type: web-api-constructor browser-compat: api.Range.Range --- {{ APIRef("DOM") }} The **`Range()`** constructor returns a newly created {{domxref("Range")}} object whose start and end is the global {{domxref("Document")}} object. ## Syntax ```js-nolint new Range() ``` ### Parameters None. ## Examples In this example we create a new range with the `Range()` constructor, and set its beginning and end positions using the {{domxref("Range.setStartBefore()")}} and {{domxref("Range.setEndAfter()")}} methods. We then select the range using {{domxref("window.getSelection()")}} and {{domxref("Selection.addRange()")}}. ### HTML ```html <p>First paragraph.</p> <p>Second paragraph.</p> <p>Third paragraph.</p> <p>Fourth paragraph.</p> ``` ### JavaScript ```js const paragraphs = document.querySelectorAll("p"); // Create new range const range = new Range(); // Start range at second paragraph range.setStartBefore(paragraphs[1]); // End range at third paragraph range.setEndAfter(paragraphs[2]); // Get window selection const selection = window.getSelection(); // Add range to window selection selection.addRange(range); ``` ### Result {{EmbedLiveSample("Examples", 400, 210)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model) - {{domxref("Document.createRange()")}}
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/setend/index.md
--- title: "Range: setEnd() method" short-title: setEnd() slug: Web/API/Range/setEnd page-type: web-api-instance-method browser-compat: api.Range.setEnd --- {{ApiRef("DOM")}} The **`Range.setEnd()`** method sets the end position of a {{ domxref("Range") }} to be located at the given offset into the specified node x.Setting the end point above (higher in the document) than the start point will result in a collapsed range with the start and end points both set to the specified end position. ## Syntax ```js-nolint setEnd(endNode, endOffset) ``` ### Parameters - `endNode` - : The {{ domxref("Node") }} inside which the {{ domxref("Range") }} should end. - `endOffset` - : An integer greater than or equal to zero representing the offset for the end of the `Range` from the start of `endNode`. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidNodeTypeError` {{domxref("DOMException")}} - : The node specified by `endNode` is a doctype node; range endpoints cannot be located inside a doctype node. - `IndexSizeError` {{domxref("DOMException")}} - : The value specified by `endOffset` is either greater than or equal to the length of the node or is less than zero. ## Usage notes If the `endNode` is a {{domxref("Node")}} of type {{domxref("Text")}}, {{domxref("Comment")}}, or {{domxref("CDataSection")}}, then `endOffset` is the number of characters from the start of `endNode`. For other {{domxref("Node")}} types, `endOffset` is the number of child nodes between the start of the `endNode`. ## Examples ```js const range = document.createRange(); const endNode = document.getElementsByTagName("p").item(3); const endOffset = endNode.childNodes.length; range.setEnd(endNode, endOffset); ``` > **Note:** `setEnd()` is commonly used in conjunction with > {{domxref("Range.setStart", "setStart()")}} to fully configure a range. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api/range
data/mdn-content/files/en-us/web/api/range/collapsed/index.md
--- title: "Range: collapsed property" short-title: collapsed slug: Web/API/Range/collapsed page-type: web-api-instance-property browser-compat: api.Range.collapsed --- {{ APIRef("DOM") }} The **`Range.collapsed`** read-only property returns a boolean flag indicating whether the start and end points of the {{domxref("Range")}} are at the same position. It returns `true` if the start and end boundary points of the {{domxref("Range")}} are the same point in the DOM, `false` if not. A collapsed {{domxref("Range")}} is empty (containing no content), and specifies a single point in a DOM tree. To collapse a range, see the {{domxref("Range.collapse()")}} method. ## Value A boolean. ## Examples ```js let range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); isCollapsed = range.collapsed; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The DOM interfaces index](/en-US/docs/Web/API/Document_Object_Model)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/backgroundfetchmanager/index.md
--- title: BackgroundFetchManager slug: Web/API/BackgroundFetchManager page-type: web-api-interface status: - experimental browser-compat: api.BackgroundFetchManager --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`BackgroundFetchManager`** interface of the {{domxref('Background Fetch API','','',' ')}} is a map where the keys are background fetch IDs and the values are {{domxref("BackgroundFetchRegistration")}} objects. ## Instance properties None. ## Instance methods - {{domxref('BackgroundFetchManager.fetch','fetch()' )}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} that resolves with a {{domxref("BackgroundFetchRegistration")}} object for a supplied array of URLs and {{domxref("Request")}} objects. - {{domxref('BackgroundFetchManager.get','get()')}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} that resolves with the {{domxref("BackgroundFetchRegistration")}} associated with the provided `id` or {{jsxref("undefined")}} if the `id` is not found. - {{domxref('BackgroundFetchManager.getIds','getIds()')}} {{Experimental_Inline}} - : Returns the IDs of all registered background fetches. ## Examples The example below shows how to get an instance of {{domxref("BackgroundFetchManager")}} from a {{domxref("ServiceWorkerRegistration")}} object and calls `fetch()` to download an audio file in the background. ```js navigator.serviceWorker.ready.then(async (swReg) => { const bgFetch = await swReg.backgroundFetch.fetch( "my-fetch", ["/ep-5.mp3", "ep-5-artwork.jpg"], { title: "Episode 5: Interesting things.", icons: [ { sizes: "300x300", src: "/ep-5-icon.png", type: "image/png", }, ], downloadTotal: 60 * 1024 * 1024, }, ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/backgroundfetchmanager
data/mdn-content/files/en-us/web/api/backgroundfetchmanager/get/index.md
--- title: "BackgroundFetchManager: get() method" short-title: get() slug: Web/API/BackgroundFetchManager/get page-type: web-api-instance-method status: - experimental browser-compat: api.BackgroundFetchManager.get --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`get()`** method of the {{domxref("BackgroundFetchManager")}} interface returns a {{jsxref("Promise")}} that resolves with the {{domxref("BackgroundFetchRegistration")}} associated with the provided `id` or {{jsxref("undefined")}} if the `id` is not found. ## Syntax ```js-nolint get(id) ``` ### Parameters - `id` - : The ID of a {{domxref("backgroundFetchRegistration")}} defined by calling {{domxref("BackgroundFetchManager.fetch","fetch()")}}. ### Return value A {{jsxref("Promise")}} that resolves with a {{domxref("BackgroundFetchRegistration")}} or {{jsxref("undefined")}}. ## Examples The following examples shows how to use `get()` to retrieve a {{domxref("BackgroundFetchRegistration")}}. With an active {{domxref('ServiceWorker', 'service worker')}}, use the {{domxref('ServiceWorkerRegistration.backgroundFetch')}} to access the `BackgroundFetchManager` object and call its `get()` method. ```js navigator.serviceWorker.ready.then(async (swReg) => { const bgFetch = await swReg.backgroundFetch.get("my-fetch"); }); // my code block ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/backgroundfetchmanager
data/mdn-content/files/en-us/web/api/backgroundfetchmanager/fetch/index.md
--- title: "BackgroundFetchManager: fetch() method" short-title: fetch() slug: Web/API/BackgroundFetchManager/fetch page-type: web-api-instance-method status: - experimental browser-compat: api.BackgroundFetchManager.fetch --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`fetch()`** method of the {{domxref("BackgroundFetchManager")}} interface initiates a background fetch operation, given one or more URLs or {{domxref("Request")}} objects. ## Syntax ```js-nolint fetch(id, requests) fetch(id, requests, options) ``` ### Parameters - `id` - : A developer-defined identifier that can be passed to the other methods to retrieve the {{domxref("BackgroundFetchRegistration")}} for this operation. - `requests` - : A `RequestInfo` object or an array of `RequestInfo` objects. Each `RequestInfo` object is a {{domxref("Request")}} object or a string that will be given as the `input` argument to the {{domxref("Request.Request()", "Request()")}} constructor. - `options` {{optional_inline}} - : An object which will be used to customize the fetch progress dialog that the browser shows to the user. It has the following properties: - `title` - : A string that will be used as the title for the progress dialog. - `icons` - : An array of objects, each representing an icon that the browser may use for the progress dialog. Each object has the following properties: - `src` - : A string representing a URL to the icon file. - `sizes` - : A string representing the sizes of the image, expressed using the same syntax as the [`sizes`](/en-US/docs/Web/HTML/Element/link#sizes) attribute of the [`<link>`](/en-US/docs/Web/HTML/Element/link) element. {{optional_inline}} - `type` - : A string representing the {{Glossary("MIME")}} type of the icon. {{optional_inline}} - `label` - : A string representing the accessible name of the icon. {{optional_inline}} - `downloadTotal` - : A number representing the estimated total download size, in bytes, for the fetch operation. This is used to show the user how big the download is and to show the user download progress. As soon as the total download size exceeds `downloadTotal`, then the fetch is aborted. ### Return value A {{jsxref("Promise")}} that resolves with a {{domxref("BackgroundFetchRegistration")}} object. ### Exceptions - {{jsxref("TypeError")}} - : Raised if no request is provided, if the mode of a request is 'no-cors', if no service worker is present, a request already exists with the requested `id`, or the request fails. - `AbortError` {{domxref("DOMException")}} - : Indicates that the fetch was aborted. - `NotAllowedError` {{domxref("DOMException")}} - : Indicates that user permission has not been granted to make background fetches. ## Examples The following example shows how to use `fetch()` to initiate a background fetch operation. With an active {{domxref('ServiceWorker', 'service worker', "", "nocode")}}, use the {{domxref('ServiceWorkerRegistration.backgroundFetch')}} property to access the `BackgroundFetchManager` object and call its `fetch()` method. ```js navigator.serviceWorker.ready.then(async (swReg) => { const bgFetch = await swReg.backgroundFetch.fetch( "my-fetch", ["/ep-5.mp3", "ep-5-artwork.jpg"], { title: "Episode 5: Interesting things.", icons: [ { sizes: "300x300", src: "/ep-5-icon.png", type: "image/png", label: "Downloading a show", }, ], downloadTotal: 60 * 1024 * 1024, }, ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/backgroundfetchmanager
data/mdn-content/files/en-us/web/api/backgroundfetchmanager/getids/index.md
--- title: "BackgroundFetchManager: getIds() method" short-title: getIds() slug: Web/API/BackgroundFetchManager/getIds page-type: web-api-instance-method status: - experimental browser-compat: api.BackgroundFetchManager.getIds --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`getIds()`** method of the {{domxref("BackgroundFetchManager")}} interface returns the IDs of all registered background fetches. ## Syntax ```js-nolint getIds() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with an {{jsxref('Array')}} of {{jsxref('String', 'strings')}}. ### Exceptions None. ## Examples The following examples shows how to retrieve the IDs of all registered background fetches. With an active [service worker](/en-US/docs/Web/API/ServiceWorker), use the {{domxref('ServiceWorkerRegistration.backgroundFetch')}} property to access the `BackgroundFetchManager` object and call its `getIds()` method. ```js navigator.serviceWorker.ready.then(async (swReg) => { const ids = await swReg.backgroundFetch.getIds(); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/reportingobserver/index.md
--- title: ReportingObserver slug: Web/API/ReportingObserver page-type: web-api-interface browser-compat: api.ReportingObserver --- {{APIRef("Reporting API")}} The `ReportingObserver` interface of the [Reporting API](/en-US/docs/Web/API/Reporting_API) allows you to collect and access reports. ## Constructor - {{domxref("ReportingObserver.ReportingObserver", "ReportingObserver()")}} - : Creates a new `ReportingObserver` object instance, which can be used to collect and access reports. ## Instance properties _This interface has no properties defined on it._ ## Instance methods - {{domxref("ReportingObserver.disconnect()")}} - : Stops a reporting observer that had previously started observing from collecting reports. - {{domxref("ReportingObserver.observe()")}} - : Instructs a reporting observer to start collecting reports in its report queue. - {{domxref("ReportingObserver.takeRecords()")}} - : Returns the current list of reports contained in the observer's report queue, and empties the queue. ## Events _This interface has no events that fire on it._ ## Examples In our [deprecation_report.html](https://mdn.github.io/dom-examples/reporting-api/deprecation_report.html) example, we create a simple reporting observer to observe usage of deprecated features on our web page: ```js const options = { types: ["deprecation"], buffered: true, }; const observer = new ReportingObserver((reports, observer) => { reportBtn.onclick = () => displayReports(reports); }, options); ``` We then tell it to start observing reports using {{domxref("ReportingObserver.observe()")}}; this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: ```js observer.observe(); ``` Later on in the example we deliberately use the deprecated version of {{domxref("MediaDevices.getUserMedia()")}}: ```js if (navigator.mozGetUserMedia) { navigator.mozGetUserMedia(constraints, success, failure); } else { navigator.getUserMedia(constraints, success, failure); } ``` This causes a deprecation report to be generated; because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details. ![image of a jolly bearded man with various stats displayed below it about a deprecated feature](reporting_api_example.png) > **Note:** If you look at the [complete source code](https://github.com/mdn/dom-examples/blob/main/reporting-api/deprecation_report.html), you'll notice that we actually call the deprecated `getUserMedia()` method twice. After the first time we call {{domxref("ReportingObserver.takeRecords()")}}, which returns the first generated report and empties the queue. Because of this, when the button is pressed only the second report is listed. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Reporting API](/en-US/docs/Web/API/Reporting_API)
0
data/mdn-content/files/en-us/web/api/reportingobserver
data/mdn-content/files/en-us/web/api/reportingobserver/takerecords/index.md
--- title: "ReportingObserver: takeRecords() method" short-title: takeRecords() slug: Web/API/ReportingObserver/takeRecords page-type: web-api-instance-method browser-compat: api.ReportingObserver.takeRecords --- {{APIRef("Reporting API")}} The **`takeRecords()`** method of the {{domxref("ReportingObserver")}} interface returns the current list of reports contained in the observer's report queue, and empties the queue. ## Syntax ```js-nolint takeRecords() ``` ### Parameters None. ### Return value An array of {{domxref("Report")}} objects. ## Examples ```js const options = { types: ["deprecation"], buffered: true, }; const observer = new ReportingObserver((reports, observer) => { reportBtn.onclick = () => displayReports(reports); }, options); observer.observe(); // … const records = observer.takeRecords(); console.log(records); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Reporting API](/en-US/docs/Web/API/Reporting_API)
0
data/mdn-content/files/en-us/web/api/reportingobserver
data/mdn-content/files/en-us/web/api/reportingobserver/observe/index.md
--- title: "ReportingObserver: observe() method" short-title: observe() slug: Web/API/ReportingObserver/observe page-type: web-api-instance-method browser-compat: api.ReportingObserver.observe --- {{APIRef("Reporting API")}} The **`observe()`** method of the {{domxref("ReportingObserver")}} interface instructs a reporting observer to start collecting reports in its report queue. ## Syntax ```js-nolint observe() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const options = { types: ["deprecation"], buffered: true, }; const observer = new ReportingObserver((reports, observer) => { reportBtn.onclick = () => displayReports(reports); }, options); observer.observe(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Reporting API](/en-US/docs/Web/API/Reporting_API)
0
data/mdn-content/files/en-us/web/api/reportingobserver
data/mdn-content/files/en-us/web/api/reportingobserver/reportingobserver/index.md
--- title: "ReportingObserver: ReportingObserver() constructor" short-title: ReportingObserver() slug: Web/API/ReportingObserver/ReportingObserver page-type: web-api-constructor browser-compat: api.ReportingObserver.ReportingObserver --- {{APIRef("Reporting API")}} The **`ReportingObserver()`** constructor of the [Reporting API](/en-US/docs/Web/API/Reporting_API) creates a new {{domxref("ReportingObserver")}} object instance, which can be used to collect and access reports. ## Syntax ```js-nolint new ReportingObserver(callback) new ReportingObserver(callback, options) ``` ### Parameters - `callback` - : A callback function that runs when the observer starts to collect reports (i.e. via {{domxref("ReportingObserver.observe()")}}). The callback function is given two parameters: - `reports` - : A sequence of {{domxref("Report")}} objects representing the reports collected in the observer's report queue. This is probably the most common way to retrieve the reports. - `observer` - : A reference to the same `ReportingObserver` object, allowing for recursive report collection, etc. - `options` {{optional_inline}} - : An object allowing you to set the options for creating the object. The available options are: - `types` - : An array of strings representing the types of report to be collected by this observer. Available types include `deprecation`, `intervention`, and `crash` (although this last type usually isn't retrievable via a `ReportingObserver`). If this option is omitted, all supported types are collected. - `buffered` - : a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (`true`) or not (`false`). ## Examples ```js const options = { types: ["deprecation"], buffered: true, }; const observer = new ReportingObserver((reports, observer) => { reportBtn.onclick = () => displayReports(reports); }, options); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Reporting API](/en-US/docs/Web/API/Reporting_API)
0
data/mdn-content/files/en-us/web/api/reportingobserver
data/mdn-content/files/en-us/web/api/reportingobserver/disconnect/index.md
--- title: "ReportingObserver: disconnect() method" short-title: disconnect() slug: Web/API/ReportingObserver/disconnect page-type: web-api-instance-method browser-compat: api.ReportingObserver.disconnect --- {{APIRef("Reporting API")}} The **`disconnect()`** method of the {{domxref("ReportingObserver")}} interface stops a reporting observer that had previously started observing from collecting reports. After calling `disconnect()`, neither {{domxref("ReportingObserver.takeRecords()")}} nor the `records` parameter of the [`ReportingObserver()`](/en-US/docs/Web/API/ReportingObserver/ReportingObserver) callback will return any reports. The associated observer will no longer be active. ## Syntax ```js-nolint disconnect() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const options = { types: ["deprecation"], buffered: true, }; const observer = new ReportingObserver((reports, observer) => { reportBtn.onclick = () => displayReports(reports); }, options); observer.observe(); // ... observer.disconnect(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Reporting API](/en-US/docs/Web/API/Reporting_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrlightprobe/index.md
--- title: XRLightProbe slug: Web/API/XRLightProbe page-type: web-api-interface status: - experimental browser-compat: api.XRLightProbe --- {{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}} The **`XRLightProbe`** interface of the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) contains lighting information at a given point in the user's environment. You can get an `XRLighting` object using the {{domxref("XRSession.requestLightProbe()")}} method. This object doesn't itself contain lighting values, but it is used to collect lighting states for each {{domxref("XRFrame")}}. See {{domxref("XRLightEstimate")}} for the estimated lighting values for an `XRLightProbe`. {{InheritanceDiagram}} ## Instance properties - `XRLightProbe.onreflectionchange` - : Event handler property for the {{domxref("XRLightProbe.reflectionchange_event", "reflectionchange")}} event. - {{domxref("XRLightProbe.probeSpace")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : An {{domxref("XRSpace")}} tracking the position and orientation the lighting estimations are relative to. ## Instance methods None. ## Events - {{domxref("XRLightProbe.reflectionchange_event", "reflectionchange")}} {{Experimental_Inline}} - : Fired each time the estimated reflection cube map changes. (This happens when the user moves around and the environment's lighting changes.) ## Examples ### Getting an `XRLightProbe` object for a session Use the {{domxref("XRSession.requestLightProbe()")}} method to get a light probe. ```js const lightProbe = await xrSession.requestLightProbe(); ``` ### Getting a probe pose within an `XRFrame` Pass the light probe's `probeSpace` to {{domxref("XRFrame.getPose()")}} to get a light probe for a pose. ```js const probePose = xrFrame.getPose(lightProbe.probeSpace, xrReferenceSpace); ``` ### Using the `reflectionchange` event Pass `XRLightProbe` to get a reflection cube map whenever the {{domxref("XRLightProbe.reflectionchange_event", "reflectionchange")}} event fires. See also {{domxref("XRWebGLBinding.getReflectionCubeMap()")}}. ```js const glBinding = new XRWebGLBinding(xrSession, gl); const lightProbe = await xrSession.requestLightProbe(); let glCubeMap = glBinding.getReflectionCubeMap(lightProbe); lightProbe.addEventListener("reflectionchange", () => { glCubeMap = glBinding.getReflectionCubeMap(lightProbe); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRSession.requestLightProbe()")}}
0
data/mdn-content/files/en-us/web/api/xrlightprobe
data/mdn-content/files/en-us/web/api/xrlightprobe/probespace/index.md
--- title: "XRLightProbe: probeSpace property" short-title: probeSpace slug: Web/API/XRLightProbe/probeSpace page-type: web-api-instance-property status: - experimental browser-compat: api.XRLightProbe.probeSpace --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The _read-only_ **`probeSpace`** property of the {{DOMxRef("XRLightProbe")}} interface returns an {{domxref("XRSpace")}} tracking the position and orientation that the lighting estimations are relative to. ## Value An {{domxref("XRSpace")}} object. ## Examples The `probeSpace` property returns the position and orientation in space that the lighting estimate is relative to. It may update over time as the user moves around. Use the {{domxref("XRFrame.getPose()")}} method to get the current lighting state with each frame. ```js const lightProbe = await xrSession.requestLightProbe(); const probePose = xrFrame.getPose(lightProbe.probeSpace, xrReferenceSpace); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRSpace()")}} - {{domxref("XRFrame.getPose()")}}
0
data/mdn-content/files/en-us/web/api/xrlightprobe
data/mdn-content/files/en-us/web/api/xrlightprobe/reflectionchange_event/index.md
--- title: "XRLightProbe: reflectionchange event" short-title: reflectionchange slug: Web/API/XRLightProbe/reflectionchange_event page-type: web-api-event status: - experimental browser-compat: api.XRLightProbe.reflectionchange_event --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The WebXR **`reflectionchange`** event fires each time the estimated reflection cube map changes. This happens in response to use movements through different lighting conditions or to direct changes to lighting itself. This event is not cancelable. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("reflectionchange", (event) => {}); onreflectionchange = (event) => {}; ``` ## Event type {{domxref("Event")}}. ## Examples ### Using the `reflectionchange` event Whenever the `reflectionchange` event fires on a light probe, you can retrieve an updated cube map by calling {{domxref("XRWebGLBinding.getReflectionCubeMap()")}}. This is less expensive than retrieving lighting information with every {{domxref("XRFrame")}}. ```js const glBinding = new XRWebGLBinding(xrSession, gl); const lightProbe = await xrSession.requestLightProbe(); let glCubeMap = glBinding.getReflectionCubeMap(lightProbe); lightProbe.addEventListener("reflectionchange", () => { glCubeMap = glBinding.getReflectionCubeMap(lightProbe); }); ``` ### The `onreflectionchange` event handler property The `reflectionchange` event is also available using the `onreflectionchange` event handler property. ```js lightProbe.onreflectionchange = (event) => { glCubeMap = glBinding.getReflectionCubeMap(lightProbe); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventTarget.addEventListener", "addEventListener()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/extendablecookiechangeevent/index.md
--- title: ExtendableCookieChangeEvent slug: Web/API/ExtendableCookieChangeEvent page-type: web-api-interface browser-compat: api.ExtendableCookieChangeEvent --- {{securecontext_header}}{{APIRef("Cookie Store API")}} The **`ExtendableCookieChangeEvent`** interface of the {{domxref("Cookie Store API", "", "", "nocode")}} is the event type passed to {{domxref("ServiceWorkerGlobalScope/cookiechange_event", "cookiechange")}} event fired at the {{domxref("ServiceWorkerGlobalScope")}} when any cookie changes occur which match the service worker's cookie change subscription list. A cookie change event consists of a cookie and a type. (either "changed" or "deleted") Cookie changes that cause the `ExtendableCookieChangeEvent` to be dispatched are: - A cookie is newly created and not immediately removed. In this case `type` is "changed". - A cookie is newly created and immediately removed. In this case `type` is "deleted" - A cookie is removed. In this case `type` is "deleted". > **Note:** A cookie that is replaced due to the insertion of another cookie with the same name, domain, and path, is ignored and does not trigger a change event. {{AvailableInWorkers}} {{InheritanceDiagram}} ## Constructor - {{domxref("ExtendableCookieChangeEvent.ExtendableCookieChangeEvent", "ExtendableCookieChangeEvent()")}} - : Creates a new `ExtendableCookieChangeEvent`. ## Instance properties _This interface also inherits properties from {{domxref("ExtendableEvent")}}._ - {{domxref("ExtendableCookieChangeEvent.changed")}} {{ReadOnlyInline}} - : Returns an array containing the changed cookies. - {{domxref("ExtendableCookieChangeEvent.deleted")}} {{ReadOnlyInline}} - : Returns an array containing the deleted cookies. ## Instance methods _This interface also inherits methods from {{domxref("ExtendableEvent")}}._ ## Examples In the below example, we use {{domxref("CookieStoreManager.getSubscriptions()")}} to get a list of existing subscriptions. (In service workers, a subscription is required in order to listen for events.) We unsubscribe from existing subscriptions using {{domxref("CookieStoreManager.unsubscribe()")}}, then subscribe to the cookie with a name of 'COOKIE_NAME' using {{domxref("CookieStoreManager.subscribe()")}}. If that cookie is changed, the event listener logs the event to the console. This will be an `ExtendableCookieChangeEvent` object, with the {{domxref("ExtendableCookieChangeEvent.changed","changed")}} or {{domxref("ExtendableCookieChangeEvent.deleted","deleted")}} property containing the modified cookie. ```js self.addEventListener("activate", (event) => { event.waitUntil(async () => { const subscriptions = await self.registration.cookies.getSubscriptions(); await self.registration.cookies.unsubscribe(subscriptions); await self.registration.cookies.subscribe([ { name: "COOKIE_NAME", }, ]); }); }); self.addEventListener("cookiechange", (event) => { console.log(event); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/extendablecookiechangeevent
data/mdn-content/files/en-us/web/api/extendablecookiechangeevent/extendablecookiechangeevent/index.md
--- title: "ExtendableCookieChangeEvent: ExtendableCookieChangeEvent() constructor" short-title: ExtendableCookieChangeEvent() slug: Web/API/ExtendableCookieChangeEvent/ExtendableCookieChangeEvent page-type: web-api-constructor browser-compat: api.ExtendableCookieChangeEvent.ExtendableCookieChangeEvent --- {{securecontext_header}}{{APIRef("Cookie Store API")}} The **`ExtendableCookieChangeEvent()`** constructor creates a new {{domxref("ExtendableCookieChangeEvent")}} object which is the event type passed to {{domxref("ServiceWorkerGlobalScope/cookiechange_event", "cookiechange")}} event fired at the {{domxref("ServiceWorkerGlobalScope")}} when any cookie changes occur which match the service worker's cookie change subscription list. This constructor is called by the browser when a change event occurs. > **Note:** This event constructor is generally not needed for production websites. It's primary use is for tests that require an instance of this event. {{AvailableInWorkers}} ## Syntax ```js-nolint new ExtendableCookieChangeEvent(type) new ExtendableCookieChangeEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers always set it to `cookiechange`. - `options` {{optional_inline}} - : An object that, _in addition of the properties defined in {{domxref("ExtendableEvent/ExtendableEvent", "ExtendableEvent()")}}_, can have the following properties: - `changed` {{optional_inline}} - : An array containing a changed cookie. - `deleted` {{optional_inline}} - : An array containing a deleted cookie. ### Return value A new {{domxref("ExtendableCookieChangeEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/extendablecookiechangeevent
data/mdn-content/files/en-us/web/api/extendablecookiechangeevent/changed/index.md
--- title: "ExtendableCookieChangeEvent: changed property" short-title: changed slug: Web/API/ExtendableCookieChangeEvent/changed page-type: web-api-instance-property browser-compat: api.ExtendableCookieChangeEvent.changed --- {{securecontext_header}}{{APIRef("Cookie Store API")}} The **`changed`** read-only property of the {{domxref("ExtendableCookieChangeEvent")}} interface returns any cookies that have been changed by the given `ExtendableCookieChangeEvent` instance. {{AvailableInWorkers}} ## Value An array of objects containing the changed cookie(s). Each object contains the following properties: - `name` - : A string containing the name of the cookie. - `value` - : A string containing the value of the cookie. - `domain` - : A string containing the domain of the cookie. - `path` - : A string containing the path of the cookie. - `expires` - : A timestamp, given as [Unix time](/en-US/docs/Glossary/Unix_time) in milliseconds, containing the expiration date of the cookie. - `secure` - : A {{jsxref("boolean")}} indicating whether the cookie is from a site with a secure context (HTTPS rather than HTTP). - `sameSite` - : One of the following [`SameSite`](/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value) values: - `"strict"` - : Cookies will only be sent in a first-party context and not be sent with requests initiated by third party websites. - `"lax"` - : Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating within the origin site (i.e. when following a link). - `"none"` - : Cookies will be sent in all contexts. - `partitioned` - : A boolean indicating whether the cookie is a partitioned cookie (`true`) or not (`false`). See [Cookies Having Independent Partitioned State (CHIPS)](/en-US/docs/Web/Privacy/Partitioned_cookies) for more information. ## Examples In this example when the cookie is set, the event listener logs the `changed` property to the console. The first item in that array contains an object representing the cookie that has just been set. ```js self.addEventListener("cookiechange", (event) => { console.log(event.changed[0]); }); const one_day = 24 * 60 * 60 * 1000; cookieStore.set({ name: "cookie1", value: "cookie1-value", expires: Date.now() + one_day, domain: "example.com", }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/extendablecookiechangeevent
data/mdn-content/files/en-us/web/api/extendablecookiechangeevent/deleted/index.md
--- title: "ExtendableCookieChangeEvent: deleted property" short-title: deleted slug: Web/API/ExtendableCookieChangeEvent/deleted page-type: web-api-instance-property browser-compat: api.ExtendableCookieChangeEvent.deleted --- {{securecontext_header}}{{APIRef("Cookie Store API")}} The **`deleted`** read-only property of the {{domxref("ExtendableCookieChangeEvent")}} interface returns any cookies that have been deleted by the given `ExtendableCookieChangeEvent` instance. {{AvailableInWorkers}} ## Value An array of objects containing the deleted cookie(s). Each object contains the following properties: - `name` - : A string containing the name of the cookie. - `value` - : A string containing the value of the cookie. - `domain` - : A string containing the domain of the cookie. - `path` - : A string containing the path of the cookie. - `expires` - : A timestamp, given as [Unix time](/en-US/docs/Glossary/Unix_time) in milliseconds, containing the expiration date of the cookie. - `secure` - : A {{jsxref("boolean")}} indicating whether the cookie is from a site with a secure context (HTTPS rather than HTTP). - `sameSite` - : One of the following [`SameSite`](/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value) values: - `"strict"` - : Cookies will only be sent in a first-party context and not be sent with requests initiated by third party websites. - `"lax"` - : Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating within the origin site (i.e. when following a link). - `"none"` - : Cookies will be sent in all contexts. - `partitioned` - : A boolean indicating whether the cookie is a partitioned cookie (`true`) or not (`false`). See [Cookies Having Independent Partitioned State (CHIPS)](/en-US/docs/Web/Privacy/Partitioned_cookies) for more information. ## Examples In this example when the cookie is deleted the event listener logs the first item in the `deleted` property to the console. It contains an object representing the cookie that has just been deleted. ```js self.addEventListener("cookiechange", (event) => { console.log(event.deleted[0]); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/speechrecognition/index.md
--- title: SpeechRecognition slug: Web/API/SpeechRecognition page-type: web-api-interface browser-compat: api.SpeechRecognition --- {{APIRef("Web Speech API")}} The **`SpeechRecognition`** interface of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is the controller interface for the recognition service; this also handles the {{domxref("SpeechRecognitionEvent")}} sent from the recognition service. > **Note:** On some browsers, like Chrome, using Speech Recognition on a web page involves a server-based recognition engine. Your audio is sent to a web service for recognition processing, so it won't work offline. {{InheritanceDiagram}} ## Constructor - {{domxref("SpeechRecognition.SpeechRecognition", "SpeechRecognition()")}} - : Creates a new `SpeechRecognition` object. ## Instance properties _`SpeechRecognition` also inherits properties from its parent interface, {{domxref("EventTarget")}}._ - {{domxref("SpeechRecognition.grammars")}} - : Returns and sets a collection of {{domxref("SpeechGrammar")}} objects that represent the grammars that will be understood by the current `SpeechRecognition`. - {{domxref("SpeechRecognition.lang")}} - : Returns and sets the language of the current `SpeechRecognition`. If not specified, this defaults to the HTML [`lang`](/en-US/docs/Web/HTML/Element/html#lang) attribute value, or the user agent's language setting if that isn't set either. - {{domxref("SpeechRecognition.continuous")}} - : Controls whether continuous results are returned for each recognition, or only a single result. Defaults to single (`false`.) - {{domxref("SpeechRecognition.interimResults")}} - : Controls whether interim results should be returned (`true`) or not (`false`.) Interim results are results that are not yet final (e.g. the {{domxref("SpeechRecognitionResult.isFinal")}} property is `false`.) - {{domxref("SpeechRecognition.maxAlternatives")}} - : Sets the maximum number of {{domxref("SpeechRecognitionAlternative")}}s provided per result. The default value is 1. ## Instance methods _`SpeechRecognition` also inherits methods from its parent interface, {{domxref("EventTarget")}}._ - {{domxref("SpeechRecognition.abort()")}} - : Stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a {{domxref("SpeechRecognitionResult")}}. - {{domxref("SpeechRecognition.start()")}} - : Starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current `SpeechRecognition`. - {{domxref("SpeechRecognition.stop()")}} - : Stops the speech recognition service from listening to incoming audio, and attempts to return a {{domxref("SpeechRecognitionResult")}} using the audio captured so far. ## Events Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the `oneventname` property of this interface. - [`audiostart`](/en-US/docs/Web/API/SpeechRecognition/audiostart_event) - : Fired when the user agent has started to capture audio. Also available via the `onaudiostart` property. - [`audioend`](/en-US/docs/Web/API/SpeechRecognition/audioend_event) - : Fired when the user agent has finished capturing audio. Also available via the `onaudioend` property. - [`end`](/en-US/docs/Web/API/SpeechRecognition/end_event) - : Fired when the speech recognition service has disconnected. Also available via the `onend` property. - [`error`](/en-US/docs/Web/API/SpeechRecognition/error_event) - : Fired when a speech recognition error occurs. Also available via the `onerror` property. - [`nomatch`](/en-US/docs/Web/API/SpeechRecognition/nomatch_event) - : Fired when the speech recognition service returns a final result with no significant recognition. This may involve some degree of recognition, which doesn't meet or exceed the {{domxref("SpeechRecognitionAlternative.confidence","confidence")}} threshold. Also available via the `onnomatch` property. - [`result`](/en-US/docs/Web/API/SpeechRecognition/result_event) - : Fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app. Also available via the `onresult` property. - [`soundstart`](/en-US/docs/Web/API/SpeechRecognition/soundstart_event) - : Fired when any sound — recognizable speech or not — has been detected. Also available via the `onsoundstart` property. - [`soundend`](/en-US/docs/Web/API/SpeechRecognition/soundend_event) - : Fired when any sound — recognizable speech or not — has stopped being detected. Also available via the `onsoundend` property. - [`speechstart`](/en-US/docs/Web/API/SpeechRecognition/speechstart_event) - : Fired when sound that is recognized by the speech recognition service as speech has been detected. Also available via the `onspeechstart` property. - [`speechend`](/en-US/docs/Web/API/SpeechRecognition/speechend_event) - : Fired when speech recognized by the speech recognition service has stopped being detected. Also available via the `onspeechend` property. - [`start`](/en-US/docs/Web/API/SpeechRecognition/start_event) - : Fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current `SpeechRecognition`. Also available via the `onstart` property. ## Examples In our simple [Speech color changer](https://github.com/mdn/dom-examples/tree/main/web-speech-api/speech-color-changer) example, we create a new `SpeechRecognition` object instance using the {{domxref("SpeechRecognition.SpeechRecognition", "SpeechRecognition()")}} constructor, create a new {{domxref("SpeechGrammarList")}}, and set it to be the grammar that will be recognized by the `SpeechRecognition` instance using the {{domxref("SpeechRecognition.grammars")}} property. After some other values have been defined, we then set it so that the recognition service starts when a click event occurs (see {{domxref("SpeechRecognition.start()")}}.) When a result has been successfully recognized, the {{domxref("SpeechRecognition.result_event", "result")}} event fires, we extract the color that was spoken from the event object, and then set the background color of the {{htmlelement("html")}} element to that color. ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; recognition.continuous = false; recognition.lang = "en-US"; recognition.interimResults = false; recognition.maxAlternatives = 1; const diagnostic = document.querySelector(".output"); const bg = document.querySelector("html"); document.body.onclick = () => { recognition.start(); console.log("Ready to receive a color command."); }; recognition.onresult = (event) => { const color = event.results[0][0].transcript; diagnostic.textContent = `Result received: ${color}`; bg.style.backgroundColor = color; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/speechstart_event/index.md
--- title: "SpeechRecognition: speechstart event" short-title: speechstart slug: Web/API/SpeechRecognition/speechstart_event page-type: web-api-event browser-compat: api.SpeechRecognition.speechstart_event --- {{APIRef("Web Speech API")}} The **`speechstart`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when sound recognized by the speech recognition service as speech has been detected. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("speechstart", (event) => {}); onspeechstart = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples You can use the `speechstart` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("speechstart", () => { console.log("Speech has been detected"); }); ``` Or use the `onspeechstart` event handler property: ```js recognition.onspeechstart = () => { console.log("Speech has been detected"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/soundstart_event/index.md
--- title: "SpeechRecognition: soundstart event" short-title: soundstart slug: Web/API/SpeechRecognition/soundstart_event page-type: web-api-event browser-compat: api.SpeechRecognition.soundstart_event --- {{APIRef("Web Speech API")}} The **`soundstart`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when any sound — recognizable speech or not — has been detected. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("soundstart", (event) => {}); onsoundstart = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples You can use the `soundstart` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("soundstart", () => { console.log("Some sound is being received"); }); ``` Or use the `onsoundstart` event handler property: ```js recognition.onsoundstart = () => { console.log("Some sound is being received"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/stop/index.md
--- title: "SpeechRecognition: stop() method" short-title: stop() slug: Web/API/SpeechRecognition/stop page-type: web-api-instance-method browser-compat: api.SpeechRecognition.stop --- {{APIRef("Web Speech API")}} The **`stop()`** method of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) stops the speech recognition service from listening to incoming audio, and attempts to return a {{domxref("SpeechRecognitionResult")}} using the audio captured so far. ## Syntax ```js-nolint stop() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; const diagnostic = document.querySelector(".output"); const bg = document.querySelector("html"); document.body.onclick = () => { recognition.start(); console.log("Ready to receive a color command."); }; abortBtn.onclick = () => { recognition.abort(); console.log("Speech recognition aborted."); }; recognition.onspeechend = () => { recognition.stop(); console.log("Speech recognition has stopped."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/start/index.md
--- title: "SpeechRecognition: start() method" short-title: start() slug: Web/API/SpeechRecognition/start page-type: web-api-instance-method browser-compat: api.SpeechRecognition.start --- {{APIRef("Web Speech API")}} The **`start()`** method of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current {{domxref("SpeechRecognition")}}. ## Syntax ```js-nolint start() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; const diagnostic = document.querySelector(".output"); const bg = document.querySelector("html"); document.body.onclick = () => { recognition.start(); console.log("Ready to receive a color command."); }; abortBtn.onclick = () => { recognition.abort(); console.log("Speech recognition aborted."); }; recognition.onspeechend = () => { recognition.stop(); console.log("Speech recognition has stopped."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/grammars/index.md
--- title: "SpeechRecognition: grammars property" short-title: grammars slug: Web/API/SpeechRecognition/grammars page-type: web-api-instance-property browser-compat: api.SpeechRecognition.grammars --- {{APIRef("Web Speech API")}} The **`grammars`** property of the {{domxref("SpeechRecognition")}} interface returns and sets a collection of {{domxref("SpeechGrammar")}} objects that represent the grammars that will be understood by the current `SpeechRecognition`. ## Value A {{domxref("SpeechGrammarList")}} containing the {{domxref("SpeechGrammar")}} objects that represent your grammar for your app. ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; //recognition.continuous = false; recognition.lang = "en-US"; recognition.interimResults = false; recognition.maxAlternatives = 1; // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/soundend_event/index.md
--- title: "SpeechRecognition: soundend event" short-title: soundend slug: Web/API/SpeechRecognition/soundend_event page-type: web-api-event browser-compat: api.SpeechRecognition.soundend_event --- {{APIRef("Web Speech API")}} The **`soundend`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when any sound — recognizable speech or not — has stopped being detected. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("soundend", (event) => {}); onsoundend = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples You can use the `soundend` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("soundend", (event) => { console.log("Sound has stopped being received"); }); ``` Or use the `onsoundend` event handler property: ```js recognition.onsoundend = (event) => { console.log("Sound has stopped being received"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/audioend_event/index.md
--- title: "SpeechRecognition: audioend event" short-title: audioend slug: Web/API/SpeechRecognition/audioend_event page-type: web-api-event browser-compat: api.SpeechRecognition.audioend_event --- {{APIRef("Web Speech API")}} The **`audioend`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when the user agent has finished capturing audio for speech recognition. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("audioend", (event) => {}); onaudioend = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples You can use the `audioend` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("audioend", () => { console.log("Audio capturing ended"); }); ``` Or use the `onaudioend` event handler property: ```js recognition.onaudioend = () => { console.log("Audio capturing ended"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/lang/index.md
--- title: "SpeechRecognition: lang property" short-title: lang slug: Web/API/SpeechRecognition/lang page-type: web-api-instance-property browser-compat: api.SpeechRecognition.lang --- {{APIRef("Web Speech API")}} The **`lang`** property of the {{domxref("SpeechRecognition")}} interface returns and sets the language of the current `SpeechRecognition`. If not specified, this defaults to the HTML [`lang`](/en-US/docs/Web/HTML/Element/html#lang) attribute value, or the user agent's language setting if that isn't set either. ## Value A string representing the BCP 47 language tag for the current `SpeechRecognition`. ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; //recognition.continuous = false; recognition.lang = "en-US"; recognition.interimResults = false; recognition.maxAlternatives = 1; // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/start_event/index.md
--- title: "SpeechRecognition: start event" short-title: start slug: Web/API/SpeechRecognition/start_event page-type: web-api-event browser-compat: api.SpeechRecognition.start_event --- {{APIRef("Web Speech API")}} The **`start`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechRecognition")}} object is fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current `SpeechRecognition`. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("start", (event) => {}); onstart = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples You can use the `start` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("start", () => { console.log("Speech recognition service has started"); }); ``` Or use the `onstart` event handler property: ```js recognition.onstart = () => { console.log("Speech recognition service has started"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/abort/index.md
--- title: "SpeechRecognition: abort() method" short-title: abort() slug: Web/API/SpeechRecognition/abort page-type: web-api-instance-method browser-compat: api.SpeechRecognition.abort --- {{APIRef("Web Speech API")}} The **`abort()`** method of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a {{domxref("SpeechRecognitionResult")}}. ## Syntax ```js-nolint abort() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; const diagnostic = document.querySelector(".output"); const bg = document.querySelector("html"); document.body.onclick = () => { recognition.start(); console.log("Ready to receive a color command."); }; abortBtn.onclick = () => { recognition.abort(); console.log("Speech recognition aborted."); }; recognition.onspeechend = () => { recognition.stop(); console.log("Speech recognition has stopped."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/audiostart_event/index.md
--- title: "SpeechRecognition: audiostart event" short-title: audiostart slug: Web/API/SpeechRecognition/audiostart_event page-type: web-api-event browser-compat: api.SpeechRecognition.audiostart_event --- {{APIRef("Web Speech API")}} The **`audiostart`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when the user agent has started to capture audio for speech recognition. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("audiostart", (event) => {}); onaudiostart = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples You can use the `audiostart` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("audiostart", () => { console.log("Audio capturing started"); }); ``` Or use the `onaudiostart` event handler property: ```js recognition.onaudiostart = () => { console.log("Audio capturing started"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/result_event/index.md
--- title: "SpeechRecognition: result event" short-title: result slug: Web/API/SpeechRecognition/result_event page-type: web-api-event browser-compat: api.SpeechRecognition.result_event --- {{APIRef("Web Speech API")}} The **`result`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("result", (event) => {}); onresult = (event) => {}; ``` ## Event type A {{domxref("SpeechRecognitionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechRecognitionEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechRecognitionEvent.emma")}} {{ReadOnlyInline}} - : Returns an Extensible MultiModal Annotation markup language (EMMA) — XML — representation of the result. - {{domxref("SpeechRecognitionEvent.interpretation")}} {{ReadOnlyInline}} - : Returns the semantic meaning of what the user said. - {{domxref("SpeechRecognitionEvent.resultIndex")}} {{ReadOnlyInline}} - : Returns the lowest index value result in the {{domxref("SpeechRecognitionResultList")}} "array" that has actually changed. - {{domxref("SpeechRecognitionEvent.results")}} {{ReadOnlyInline}} - : Returns a {{domxref("SpeechRecognitionResultList")}} object representing all the speech recognition results for the current session. ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. You can use the `result` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new SpeechRecognition(); recognition.addEventListener("result", (event) => { const color = event.results[0][0].transcript; diagnostic.textContent = `Result received: ${color}.`; bg.style.backgroundColor = color; }); ``` Or use the `onresult` event handler property: ```js recognition.onresult = (event) => { const color = event.results[0][0].transcript; diagnostic.textContent = `Result received: ${color}.`; bg.style.backgroundColor = color; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/maxalternatives/index.md
--- title: "SpeechRecognition: maxAlternatives property" short-title: maxAlternatives slug: Web/API/SpeechRecognition/maxAlternatives page-type: web-api-instance-property browser-compat: api.SpeechRecognition.maxAlternatives --- {{APIRef("Web Speech API")}} The **`maxAlternatives`** property of the {{domxref("SpeechRecognition")}} interface sets the maximum number of {{domxref("SpeechRecognitionAlternative")}}s provided per {{domxref("SpeechRecognitionResult")}}. The default value is 1. ## Value A number representing the maximum returned alternatives for each result. ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; //recognition.continuous = false; recognition.lang = "en-US"; recognition.interimResults = false; recognition.maxAlternatives = 1; // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/nomatch_event/index.md
--- title: "SpeechRecognition: nomatch event" short-title: nomatch slug: Web/API/SpeechRecognition/nomatch_event page-type: web-api-event browser-compat: api.SpeechRecognition.nomatch_event --- {{APIRef("Web Speech API")}} The **`nomatch`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when the speech recognition service returns a final result with no significant recognition. This may involve some degree of recognition, which doesn't meet or exceed the {{domxref("SpeechRecognitionAlternative.confidence","confidence")}} threshold. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("nomatch", (event) => {}); onnomatch = (event) => {}; ``` ## Event type A {{domxref("SpeechRecognitionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechRecognitionEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechRecognitionEvent.emma")}} {{ReadOnlyInline}} - : Returns an Extensible MultiModal Annotation markup language (EMMA) — XML — representation of the result. - {{domxref("SpeechRecognitionEvent.interpretation")}} {{ReadOnlyInline}} - : Returns the semantic meaning of what the user said. - {{domxref("SpeechRecognitionEvent.resultIndex")}} {{ReadOnlyInline}} - : Returns the lowest index value result in the {{domxref("SpeechRecognitionResultList")}} "array" that has actually changed. - {{domxref("SpeechRecognitionEvent.results")}} {{ReadOnlyInline}} - : Returns a {{domxref("SpeechRecognitionResultList")}} object representing all the speech recognition results for the current session. ## Examples You can use the `nomatch` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("nomatch", () => { console.error("Speech not recognized"); }); ``` Or use the `onnomatch` event handler property: ```js recognition.onnomatch = () => { console.error("Speech not recognized"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/interimresults/index.md
--- title: "SpeechRecognition: interimResults property" short-title: interimResults slug: Web/API/SpeechRecognition/interimResults page-type: web-api-instance-property browser-compat: api.SpeechRecognition.interimResults --- {{APIRef("Web Speech API")}} The **`interimResults`** property of the {{domxref("SpeechRecognition")}} interface controls whether interim results should be returned (`true`) or not (`false`.) Interim results are results that are not yet final (e.g. the {{domxref("SpeechRecognitionResult.isFinal")}} property is `false`.) The default value for **`interimResults`** is `false`. ## Value A boolean value representing the state of the current `SpeechRecognition`'s interim results. `true` means interim results are returned, and `false` means they aren't. ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; //recognition.continuous = false; recognition.lang = "en-US"; recognition.interimResults = false; recognition.maxAlternatives = 1; // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/end_event/index.md
--- title: "SpeechRecognition: end event" short-title: end slug: Web/API/SpeechRecognition/end_event page-type: web-api-event browser-compat: api.SpeechRecognition.end_event --- {{APIRef("Web Speech API")}} The **`end`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechRecognition")}} object is fired when the speech recognition service has disconnected. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("end", (event) => {}); onend = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples You can use the `end` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("end", () => { console.log("Speech recognition service disconnected"); }); ``` Or use the `onend` event handler property: ```js recognition.onend = () => { console.log("Speech recognition service disconnected"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/speechrecognition/index.md
--- title: "SpeechRecognition: SpeechRecognition() constructor" short-title: SpeechRecognition() slug: Web/API/SpeechRecognition/SpeechRecognition page-type: web-api-constructor browser-compat: api.SpeechRecognition.SpeechRecognition --- {{APIRef("Web Speech API")}} The **`SpeechRecognition()`** constructor creates a new {{domxref("SpeechRecognition")}} object instance. ## Syntax ```js-nolint new SpeechRecognition() ``` ### Parameters None. ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; //recognition.continuous = false; recognition.lang = "en-US"; recognition.interimResults = false; recognition.maxAlternatives = 1; // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/speechend_event/index.md
--- title: "SpeechRecognition: speechend event" short-title: speechend slug: Web/API/SpeechRecognition/speechend_event page-type: web-api-event browser-compat: api.SpeechRecognition.speechend_event --- {{APIRef("Web Speech API")}} The **`speechend`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when speech recognized by the speech recognition service has stopped being detected. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("speechend", (event) => {}); onspeechend = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples You can use the `speechend` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("speechend", () => { console.log("Speech has stopped being detected"); }); ``` Or use the `onspeechend` event handler property: ```js recognition.onspeechend = () => { console.log("Speech has stopped being detected"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/error_event/index.md
--- title: "SpeechRecognition: error event" short-title: error slug: Web/API/SpeechRecognition/error_event page-type: web-api-event browser-compat: api.SpeechRecognition.error_event --- {{APIRef("Web Speech API")}} The **`error`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechRecognition")}} object is fired when a speech recognition error occurs. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("error", (event) => {}); onerror = (event) => {}; ``` ## Event type A {{domxref("SpeechRecognitionErrorEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechRecognitionErrorEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechRecognitionErrorEvent.error")}} {{ReadOnlyInline}} - : Returns the type of error raised. - {{domxref("SpeechRecognitionErrorEvent.message")}} {{ReadOnlyInline}} - : Returns a message describing the error in more detail. ## Examples You can use the `error` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js const recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener("error", (event) => { console.error(`Speech recognition error detected: ${event.error}`); }); ``` Or use the `onerror` event handler property: ```js recognition.onerror = (event) => { console.error(`Speech recognition error detected: ${event.error}`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognition
data/mdn-content/files/en-us/web/api/speechrecognition/continuous/index.md
--- title: "SpeechRecognition: continuous property" short-title: continuous slug: Web/API/SpeechRecognition/continuous page-type: web-api-instance-property browser-compat: api.SpeechRecognition.continuous --- {{APIRef("Web Speech API")}} The **`continuous`** property of the {{domxref("SpeechRecognition")}} interface controls whether continuous results are returned for each recognition, or only a single result. It defaults to single results (`false`.) ## Value A boolean value representing the current `SpeechRecognition`'s continuous status. `true` means continuous, and `false` means not continuous (single result each time.) ## Examples This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example. ```js const grammar = "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;"; const recognition = new SpeechRecognition(); const speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; recognition.continuous = false; recognition.lang = "en-US"; recognition.interimResults = false; recognition.maxAlternatives = 1; // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/caches/index.md
--- title: caches global property short-title: caches slug: Web/API/caches page-type: web-api-global-property browser-compat: api.caches --- {{APIRef("Service Workers API")}}{{AvailableInWorkers}} The global **`caches`** read-only property returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests. {{securecontext_header}} ## Value A {{domxref("CacheStorage")}} object. ## Examples The following example shows how you'd use a cache in a [service worker](/en-US/docs/Web/API/Service_Worker_API) context to store assets offline. ```js this.addEventListener("install", (event) => { event.waitUntil( caches .open("v1") .then((cache) => cache.addAll([ "/", "/index.html", "/style.css", "/app.js", "/image-list.js", "/star-wars-logo.jpg", "/gallery/", "/gallery/bountyHunters.jpg", "/gallery/myLittleVader.jpg", "/gallery/snowTroopers.jpg", ]), ), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Service Workers](/en-US/docs/Web/API/Service_Worker_API) - [Web Workers](/en-US/docs/Web/API/Web_Workers_API) - {{domxref("CacheStorage")}} - {{domxref("Cache")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/midiport/index.md
--- title: MIDIPort slug: Web/API/MIDIPort page-type: web-api-interface browser-compat: api.MIDIPort --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`MIDIPort`** interface of the {{domxref('Web MIDI API','','',' ')}} represents a MIDI input or output port. A `MIDIPort` instance is created when a new MIDI device is connected. Therefore it has no constructor. {{InheritanceDiagram}} ## Instance properties - {{domxref("MIDIPort.id")}} {{ReadOnlyInline}} - : Returns a string containing the unique ID of the port. - {{domxref("MIDIPort.manufacturer")}} {{ReadOnlyInline}} - : Returns a string containing the manufacturer of the port. - {{domxref("MIDIPort.name")}} {{ReadOnlyInline}} - : Returns a string containing the system name of the port. - {{domxref("MIDIPort.type")}} {{ReadOnlyInline}} - : Returns a string containing the type of the port, one of: - `"input"` - : The `MIDIPort` is an input port. - `"output"` - : The `MIDIPort` is an output port. - {{domxref("MIDIPort.version")}} {{ReadOnlyInline}} - : Returns a string containing the version of the port. - {{domxref("MIDIPort.state")}} {{ReadOnlyInline}} - : Returns a string containing the state of the port, one of: - `"disconnected"` - : The device that this `MIDIPort` represents is disconnected from the system. - `"connected"` - : The device that this `MIDIPort` represents is currently connected. - {{domxref("MIDIPort.connection")}} {{ReadOnlyInline}} - : Returns a string containing the connection state of the port, one of: - `"open"` - : The device that this `MIDIPort` represents has been opened and is available. - `"closed"` - : The device that this `MIDIPort` represents has not been opened, or has been closed. - `"pending"` - : The device that this `MIDIPort` represents has been opened but has subsequently disconnected . ## Instance methods _This interface also inherits methods from {{domxref("EventTarget")}}._ - {{domxref("MIDIPort.open()")}} - : Makes the MIDI device connected to this `MIDIPort` explicitly available, and returns a {{jsxref("Promise")}} which resolves once access to the port has been successful. - {{domxref("MIDIPort.close()")}} - : Makes the MIDI device connected to this `MIDIPort` unavailable, changing the {{domxref("MIDIPort.state","state")}} from `"open"` to `"closed"`. This returns a {{jsxref("Promise")}} which resolves once the port has been closed. ## Events - {{domxref("MIDIPort.statechange_event")}} - : Called when an existing port changes its state or connection. ## Examples ### List ports and their information The following example lists input and output ports, and displays information about them using properties of `MIDIPort`. ```js function listInputsAndOutputs(midiAccess) { for (const entry of midiAccess.inputs) { const input = entry[1]; console.log( `Input port [type:'${input.type}'] id:'${input.id}' manufacturer: '${input.manufacturer}' name: '${input.name}' version: '${input.version}'`, ); } for (const entry of midiAccess.outputs) { const output = entry[1]; console.log( `Output port [type:'${output.type}'] id: '${output.id}' manufacturer: '${output.manufacturer}' name: '${output.name}' version: '${output.version}'`, ); } } ``` ### Add available ports to a select list The following example takes the list of input ports and adds them to a select list, in order that a user can choose the device they want to use. ```js inputs.forEach((port, key) => { const opt = document.createElement("option"); opt.text = port.name; document.getElementById("inputportselector").add(opt); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/name/index.md
--- title: "MIDIPort: name property" short-title: name slug: Web/API/MIDIPort/name page-type: web-api-instance-property browser-compat: api.MIDIPort.name --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`name`** read-only property of the {{domxref("MIDIPort")}} interface returns the system name of the port. ## Value A string containing the system name of the port. ## Examples The following example loops through all input ports and prints the name of each to the console. ```js for (const entry of midiAccess.inputs) { const input = entry[1]; console.log(input.name); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/manufacturer/index.md
--- title: "MIDIPort: manufacturer property" short-title: manufacturer slug: Web/API/MIDIPort/manufacturer page-type: web-api-instance-property browser-compat: api.MIDIPort.manufacturer --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`manufacturer`** read-only property of the {{domxref("MIDIPort")}} interface returns the manufacturer of the port. ## Value A string containing the manufacturer of the port. ## Examples The following example loops through all input ports and prints the manufacturer of each to the console. ```js for (const entry of midiAccess.inputs) { const input = entry[1]; console.log(input.manufacturer); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/statechange_event/index.md
--- title: "MIDIPort: statechange event" short-title: statechange slug: Web/API/MIDIPort/statechange_event page-type: web-api-event browser-compat: api.MIDIPort.statechange_event --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`statechange`** event of the {{domxref("MIDIPort")}} interface is fired when a port changes from open to closed, or closed to open. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("statechange", (event) => {}); onstatechange = (event) => {}; ``` ## Event type A {{domxref("MIDIConnectionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MIDIConnectionEvent")}} ## Event properties - {{domxref("MIDIConnectionEvent.port")}} {{ReadOnlyInline}} - : Returns a reference to a {{domxref("MIDIPort")}} instance for a port that has been connected or disconnected. ## Example In the following example the current {{domxref("MIDIPort.state")}} is logged each time it changes. ```js port.onstatechange = (event) => { console.log(port.state); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/id/index.md
--- title: "MIDIPort: id property" short-title: id slug: Web/API/MIDIPort/id page-type: web-api-instance-property browser-compat: api.MIDIPort.id --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`id`** read-only property of the {{domxref("MIDIPort")}} interface returns the unique ID of the port. ## Value A string containing an ID for the port. ## Examples The following example loops through all input ports and prints the id of each to the console. ```js for (const entry of midiAccess.inputs) { const input = entry[1]; console.log(input.id); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/connection/index.md
--- title: "MIDIPort: connection property" short-title: connection slug: Web/API/MIDIPort/connection page-type: web-api-instance-property browser-compat: api.MIDIPort.connection --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`connection`** read-only property of the {{domxref("MIDIPort")}} interface returns the connection state of the port. ## Value Returns a string containing the connection state of the port, one of: - `"open"` - : The device that this `MIDIPort` represents has been opened and is available. - `"closed"` - : The device that this `MIDIPort` represents has not been opened, or has been closed. - `"pending"` - : The device that this `MIDIPort` represents has been opened but has subsequently disconnected. ## Examples The following example loops through all input ports and prints the connection status of each to the console. ```js for (const entry of midiAccess.inputs) { const input = entry[1]; console.log(input.connection); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/state/index.md
--- title: "MIDIPort: state property" short-title: state slug: Web/API/MIDIPort/state page-type: web-api-instance-property browser-compat: api.MIDIPort.state --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`state`** read-only property of the {{domxref("MIDIPort")}} interface returns the state of the port. ## Value A string containing the state of the port, one of: - `"disconnected"` - : The device that this `MIDIPort` represents is disconnected from the system. - `"connected"` - : The device that this `MIDIPort` represents is currently connected. ## Examples The following example loops through all input ports and prints the state of each to the console. ```js for (const entry of midiAccess.inputs) { const input = entry[1]; console.log(input.state); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/type/index.md
--- title: "MIDIPort: type property" short-title: type slug: Web/API/MIDIPort/type page-type: web-api-instance-property browser-compat: api.MIDIPort.type --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`type`** read-only property of the {{domxref("MIDIPort")}} interface returns the type of the port, indicating whether this is an input or output MIDI port. ## Value A string containing the type of the port, one of: - `"input"` - : The `MIDIPort` is an input port. - `"output"` - : The `MIDIPort` is an output port. ## Examples The following example loops through all input ports and prints the `type` of each to the console. ```js for (const entry of midiAccess.inputs) { const input = entry[1]; console.log(input.type); // should always be input } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/close/index.md
--- title: "MIDIPort: close() method" short-title: close() slug: Web/API/MIDIPort/close page-type: web-api-instance-method browser-compat: api.MIDIPort.close --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`close()`** method of the {{domxref("MIDIPort")}} interface makes the access to the MIDI device connected to this `MIDIPort` unavailable. If the port is successfully closed a new {{domxref("MIDIConnectionEvent")}} is queued to the {{domxref("MIDIPort.statechange_event", "MIDIPort statechange")}} and {{domxref("MIDIAccess.statechange_event", "MIDIAccess statechange")}} events, and the {{domxref("MIDIPort.connection")}} property is changed to `"closed"`. ## Syntax ```js-nolint close() ``` ### Parameters None. ### Return value Returns a {{jsxref("Promise")}} which resolves once the port has been closed. ## Examples The following example shows an output port being closed. ```js let output = midiAccess.outputs.get(portID); output.close(); // closes the port ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/version/index.md
--- title: "MIDIPort: version property" short-title: version slug: Web/API/MIDIPort/version page-type: web-api-instance-property browser-compat: api.MIDIPort.version --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`version`** read-only property of the {{domxref("MIDIPort")}} interface returns the version of the port. ## Value A string containing the version of the port. ## Examples The following example loops through all input ports and prints the version of each to the console. ```js for (const entry of midiAccess.inputs) { const input = entry[1]; console.log(input.version); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midiport
data/mdn-content/files/en-us/web/api/midiport/open/index.md
--- title: "MIDIPort: open() method" short-title: open() slug: Web/API/MIDIPort/open page-type: web-api-instance-method browser-compat: api.MIDIPort.open --- {{securecontext_header}}{{DefaultAPISidebar("Web MIDI API")}} The **`open()`** method of the {{domxref("MIDIPort")}} interface makes the MIDI device connected to this `MIDIPort` explicitly available. If the port is successfully opened a new {{domxref("MIDIConnectionEvent")}} is queued to the {{domxref("MIDIPort.statechange_event", "MIDIPort statechange")}} and {{domxref("MIDIAccess.statechange_event", "MIDIAccess statechange")}} events, and the {{domxref("MIDIPort.connection")}} property is changed to `"open"`. If the port is already open when this method is called, then the promise will resolve successfully. ## Syntax ```js-nolint open() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} which resolves once access to the port has been successfully obtained. ### Exceptions - `InvalidAccessError` {{domxref("DOMException")}} - : The promise is rejected with this error if the port is unavailable and cannot be opened. ## Examples The following example shows an output port being opened. ```js const output = midiAccess.outputs.get(portID); output.open(); // opens the port ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtcpeerconnectioniceerrorevent/index.md
--- title: RTCPeerConnectionIceErrorEvent slug: Web/API/RTCPeerConnectionIceErrorEvent page-type: web-api-interface browser-compat: api.RTCPeerConnectionIceErrorEvent --- {{DefaultAPISidebar("WebRTC API")}} The **`RTCPeerConnectionIceErrorEvent`** interface—based upon the {{domxref("Event")}} interface—provides details pertaining to an {{Glossary("ICE")}} error announced by sending an {{domxref("RTCPeerConnection.icecandidateerror_event", "icecandidateerror")}} event to the {{domxref("RTCPeerConnection")}} object. {{InheritanceDiagram}} ## Constructor - {{domxref("RTCPeerConnectionIceErrorEvent.RTCPeerConnectionIceErrorEvent", "RTCPeerConnectionIceErrorEvent()")}} - : Creates and returns a new `RTCPeerConnectionIceErrorEvent` object, with its `type` and other properties initialized as specified in the parameters. You will not normally create an object of this type yourself. ## Instance properties _The `RTCPeerConnectionIceErrorEvent` interface includes the properties found on the {{domxref("Event")}} interface, as well as the following properties:_ - {{domxref("RTCPeerConnectionIceErrorEvent.address", "address")}} {{ReadOnlyInline}} - : A string providing the local IP address used to communicate with the {{Glossary("STUN")}} or {{Glossary("TURN")}} server being used to negotiate the connection, or `null` if the local IP address has not yet been exposed as part of a local ICE candidate. - {{domxref("RTCPeerConnectionIceErrorEvent.errorCode", "errorCode")}} {{ReadOnlyInline}} - : An unsigned integer value stating the numeric [STUN error code](https://www.iana.org/assignments/stun-parameters/stun-parameters.xhtml#stun-parameters-6) returned by the STUN or TURN server. If no host candidate can reach the server, this property is set to the number 701, which is outside the range of valid STUN error codes. The 701 error is fired only once per server URL, and only while the {{domxref("RTCPeerConnection.icegatheringstate", "icegatheringstate")}} is `gathering`. - {{domxref("RTCPeerConnectionIceErrorEvent.errorText", "errorText")}} {{ReadOnlyInline}} - : A string containing the STUN reason text returned by the STUN or TURN server. If communication with the STUN or TURN server couldn't be established at all, this string will be a browser-specific string explaining the error. - {{domxref("RTCPeerConnectionIceErrorEvent.port", "port")}} {{ReadOnlyInline}} - : An unsigned integer value giving the port number over which communication with the STUN or TURN server is taking place, using the IP address given in `address`. `null` if the connection hasn't been established (that is, if `address` is `null`). - {{domxref("RTCPeerConnectionIceErrorEvent.url", "url")}} {{ReadOnlyInline}} - : A string indicating the URL of the STUN or TURN server with which the error occurred. ## Instance methods _`RTCPeerConnectionIceErrorEvent` has no methods other than any provided by the parent interface, {{domxref("Event")}}._ ## Examples TBD ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnectioniceerrorevent
data/mdn-content/files/en-us/web/api/rtcpeerconnectioniceerrorevent/address/index.md
--- title: "RTCPeerConnectionIceErrorEvent: address property" short-title: address slug: Web/API/RTCPeerConnectionIceErrorEvent/address page-type: web-api-instance-property browser-compat: api.RTCPeerConnectionIceErrorEvent.address --- {{DefaultAPISidebar("WebRTC")}} The {{domxref("RTCPeerConnectionIceErrorEvent")}} property **`address`** is a string which indicates the local IP address being used to communicate with the {{Glossary("STUN")}} or {{Glossary("TURN")}} server during negotiations. The error which occurred involved this address. ## Value A string which specifies the local IP address of the network connection to the ICE server with which negotiations were occurring when the error occurred. This address identifies the network interface on the local device which is being used to attempt to establish the connection to the remote peer. This can be useful on multi-homed systems—devices with more than one network connection—to determine which network interface is being used. For example, on a mobile phone, there are typically at least two network interfaces available: the cellular connection and a Wi-Fi connection. If the local IP address isn't exposed as part of a local candidate, the value of `address` is `null`. ## Examples This example creates a handler for {{domxref("RTCPeerConnection.icecandidateerror_event", "icecandidateerror")}} events which creates human-readable messages describing the local network interface for the connection as well as the ICE server that was being used to try to open the connection, then calls a function to display those as well as the event's {{domxref("RTCPeerConnectionIceErrorEvent.errorText", "errorText")}} property's contents. ```js pc.addEventListener("icecandidateerror", (event) => { let networkInfo = `[Local interface: ${event.address}:${event.port}`; let iceServerInfo = `[ICE server: ${event.url}`; showMessage(errorText, iceServerInfo, networkInfo); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/usbisochronousintransferresult/index.md
--- title: USBIsochronousInTransferResult slug: Web/API/USBIsochronousInTransferResult page-type: web-api-interface status: - experimental browser-compat: api.USBIsochronousInTransferResult --- {{securecontext_header}}{{APIRef("WebUSB API")}}{{SeeCompatTable}} The `USBIsochronousInTransferResult` interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides the result from a call to the `isochronousTransferIn()` method of the `USBDevice` interface. It represents the result from requesting a transfer of data from the USB device to the USB host. ## Constructor - {{domxref("USBIsochronousInTransferResult.USBIsochronousInTransferResult", "USBIsochronousInTransferResult()")}} {{Experimental_Inline}} - : Creates a new `USBIsochronousInTransferResult` object with the provided `packets` and `data` fields. ## Instance properties - {{domxref("USBIsochronousInTransferResult.data")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a `DataView` object containing the data received from the device. This is the combined data from all packets. See the individual `DataView` objects in the `packets` array for the portion of this buffer containing data from each packet. - {{domxref("USBIsochronousInTransferResult.packets")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns an array of `USBIsochronousInTransferPacket` objects containing the result of each request to receive a packet from the device. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/webgl_lose_context/index.md
--- title: WEBGL_lose_context extension short-title: WEBGL_lose_context slug: Web/API/WEBGL_lose_context page-type: webgl-extension browser-compat: api.WEBGL_lose_context --- {{APIRef("WebGL")}} The **WEBGL_lose_context** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and exposes functions to simulate losing and restoring a {{domxref("WebGLRenderingContext")}}. 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. ## Instance methods - {{domxref("WEBGL_lose_context.loseContext()")}} - : Simulates losing the context. - {{domxref("WEBGL_lose_context.restoreContext()")}} - : Simulates restoring the context. ## Examples With this extension, you can simulate the [`webglcontextlost`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event) and [`webglcontextrestored`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextrestored_event) events: ```js const canvas = document.getElementById("canvas"); const gl = canvas.getContext("webgl"); canvas.addEventListener("webglcontextlost", (event) => { console.log(event); }); gl.getExtension("WEBGL_lose_context").loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WebGLRenderingContext.isContextLost()")}} - Events: [`webglcontextlost`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event), [`webglcontextrestored`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextrestored_event), [`webglcontextcreationerror`](/en-US/docs/Web/API/HTMLCanvasElement/webglcontextcreationerror_event)
0