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/rtcicecandidate | data/mdn-content/files/en-us/web/api/rtcicecandidate/relatedaddress/index.md | ---
title: "RTCIceCandidate: relatedAddress property"
short-title: relatedAddress
slug: Web/API/RTCIceCandidate/relatedAddress
page-type: web-api-instance-property
browser-compat: api.RTCIceCandidate.relatedAddress
---
{{APIRef("WebRTC")}}
The **{{domxref("RTCIceCandidate")}}** interface's read-only **`relatedAddress`** property is a
string indicating the **related address** of a relay or reflexive candidate.
If the candidate is a host candidate (that is, its {{domxref("RTCIceCandidate/address", "address")}} is in fact the real IP address of the remote peer), `relatedAddress` is `null`.
The `relatedAddress` field's value is set from the `candidateInfo` options object passed to the {{domxref("RTCIceCandidate.RTCIceCandidate", "RTCIceCandidate()")}} constructor.
You can't specify the value of `relatedAddress` directly in the options object, but its value is automatically extracted from the object's `candidate` a-line if it's formatted properly(the `rel-address` field).
The related address and port ({{domxref("RTCIceCandidate.relatedPort", "relatedPort")}}) are not used at all by {{Glossary("ICE")}} itself; they are provided
for analysis and diagnostic purposes only, and their inclusion may be blocked by security systems, so do not rely on them having non-`null` values.
## Value
A string which contains the candidate's related address. For both
peer and server reflexive candidates, the related address (and related port) are the
base for that server or peer reflexive candidate. For relay candidates, the related
address and port are set to the mapped address selected by the TURN server.
For host candidates, `relatedAddress` is `null`, meaning the field is not included in the candidate's a-line.
## Usage notes
The related address is included in ICE candidates despite not being used by ICE itself.
`relatedAddress` can be used for diagnostic purposes; by observing the
relationships between the various types of candidates and their addresses and related
addresses. `relatedAddress` can also be used by Quality-of-Service (QoS) mechanisms.
Here's an [SDP](/en-US/docs/Web/API/WebRTC_API/Protocols#sdp) attribute line (a-line) describing an ICE candidate discovered by the STUN server:
```plain
a=candidate:4234997325 1 udp 2043278322 192.0.2.172 6502 typ srflx raddr 198.51.100.45 rport 32768 generation 0
```
The remote address, `relatedAddress`, is the dotted quad (for IPv4) or
colon-delineated 64-bit address (for IPv6) immediately following the text `"raddr"`, or `"198.51.100.45"`.
## Examples
In this example, the candidate's {{domxref("RTCIceCandidate.type", "type")}} is
checked, and then debugging output is presented, based on the candidate type, including
the candidate's {{domxref("RTCIceCandidate/address", "ip")}} and `relatedAddress`.
```js
switch (candidate.type) {
case "host":
console.log(`Host candidate's IP address is ${candidate.ip}`);
break;
case "srflx":
console.log(
`Server reflexive candidate's base address is ${candidate.relatedAddress}; reachable at ${candidate.ip}`,
);
break;
case "prflx":
console.log(
`Peer reflexive candidate's base address is ${candidate.relatedAddress}; reachable at ${candidate.ip}`,
);
break;
case "relay":
console.log(
`Relay candidate's address assigned by the TURN server is ${candidate.relatedAddress}; reachable at ${candidate.ip}`,
);
break;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- [Introduction to WebRTC protocols](/en-US/docs/Web/API/WebRTC_API/Protocols)
- [WebRTC connectivity](/en-US/docs/Web/API/WebRTC_API/Connectivity)
- [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime)
- {{domxref("RTCIceCandidate.relatedPort")}}
- {{domxref("RTCIceCandidate.address")}} and {{domxref("RTCIceCandidate.port")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/sharedstorageoperation/index.md | ---
title: SharedStorageOperation
slug: Web/API/SharedStorageOperation
page-type: web-api-interface
status:
- experimental
browser-compat: api.SharedStorageOperation
---
{{APIRef("Shared Storage API")}}{{SeeCompatTable}}
The **`SharedStorageOperation`** interface of the {{domxref("Shared Storage API", "Shared Storage API", "", "nocode")}} represents the base class for all output gate operation types.
The output gate types are detailed below:
<table class="no-markdown">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Defined by</th>
<th>Invoked by</th>
</tr>
</thead>
<tbody>
<tr>
<td>URL Selection</td>
<td>Used to select a URL to display to the user based on shared storage data.</td>
<td>{{domxref("SharedStorageSelectURLOperation")}}</td>
<td>{{domxref("WindowSharedStorage.selectURL()", "selectURL()")}}</td>
</tr>
<tr>
<td>Run</td>
<td>A generic way to process some shared storage data. Used, for example, by the <a href="https://developer.chrome.com/docs/privacy-sandbox/private-aggregation/">Private Aggregation API</a> to process shared storage data and generate aggregated reports. </td>
<td>{{domxref("SharedStorageRunOperation")}}</td>
<td>{{domxref("WindowSharedStorage.run()", "run()")}}</td>
</tr>
</tbody>
</table>
## Examples
### Defining individual operations
Many shared storage worklet module scripts only define and register a single operation; you can see examples on the {{domxref("SharedStorageSelectURLOperation")}} and {{domxref("SharedStorageRunOperation")}} pages.
### Defining multiple operations
In more advanced cases, it is possible to define and register multiple operations in the same shared storage worklet module script with different names. In the following worklet module script, we define a URL Selection operation called `SelectURLOperation` that selects a URL for A/B testing, and a Run operation called `ExperimentGroupReportingOperation`, which runs a histogram report based on the user's A/B testing group:
```js
// ab-testing-worklet.js
class SelectURLOperation {
async run(urls, data) {
// Read the user's group from shared storage
const experimentGroup = await sharedStorage.get("ab-testing-group");
// Log to console for the demo
console.log(`urls = ${JSON.stringify(urls)}`);
console.log(`data = ${JSON.stringify(data)}`);
console.log(`ab-testing-group in shared storage is ${experimentGroup}`);
// Return the index of the group
return data.indexOf(experimentGroup);
}
}
function getBucketForTestingGroup(testingGroup) {
switch (testingGroup) {
case "control":
return 0;
case "experiment-a":
return 1;
case "experiment-b":
return 2;
}
}
class ExperimentGroupReportingOperation {
async run() {
const experimentGroup = await sharedStorage.get("ab-testing-group");
const bucket = BigInt(getBucketForTestingGroup(experimentGroup));
privateAggregation.contributeToHistogram({ bucket, value: 1 });
}
}
// Register the operations
register("ab-testing", SelectURLOperation);
register("experiment-group-reporting", ExperimentGroupReportingOperation);
```
In the main browsing context, these operations are invoked by {{domxref("WindowSharedStorage.selectURL()", "selectURL()")}} and {{domxref("WindowSharedStorage.run()", "run()")}}, respectively. The operations to invoke via these methods are selected using the names they were registered with, and they are also required to conform to the structures defined by the {{domxref("SharedStorageSelectURLOperation")}} and {{domxref("SharedStorageRunOperation")}} classes and their `run()` methods.
```js
// For demo purposes. The hostname is used to determine the usage of
// development localhost URL vs production URL
const contentProducerUrl = window.location.host;
// Map the experiment groups to the URLs
const EXPERIMENT_MAP = [
{
group: "control",
url: `https://${contentProducerUrl}/ads/default-ad.html`,
},
{
group: "experiment-a",
url: `https://${contentProducerUrl}/ads/experiment-ad-a.html`,
},
{
group: "experiment-b",
url: `https://${contentProducerUrl}/ads/experiment-ad-b.html`,
},
];
// Choose a random group for the initial experiment
function getRandomExperiment() {
const randomIndex = Math.floor(Math.random() * EXPERIMENT_MAP.length);
return EXPERIMENT_MAP[randomIndex].group;
}
async function injectAd() {
// Load the worklet module
await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");
// Set the initial value in the storage to a random experiment group
window.sharedStorage.set("ab-testing-group", getRandomExperiment(), {
ignoreIfPresent: true,
});
const urls = EXPERIMENT_MAP.map(({ url }) => ({ url }));
const groups = EXPERIMENT_MAP.map(({ group }) => group);
// Resolve the selectURL call to a fenced frame config only when it exists on the page
const resolveToConfig = typeof window.FencedFrameConfig !== "undefined";
// Run the URL selection operation to select an ad based on the experiment group in shared storage
const selectedUrl = await window.sharedStorage.selectURL("ab-testing", urls, {
data: groups,
resolveToConfig,
keepAlive: true,
});
const adSlot = document.getElementById("ad-slot");
if (resolveToConfig && selectedUrl instanceof FencedFrameConfig) {
adSlot.config = selectedUrl;
} else {
adSlot.src = selectedUrl;
}
// Run the reporting operation
await window.sharedStorage.run("experiment-group-reporting");
}
injectAd();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediakeymessageevent/index.md | ---
title: MediaKeyMessageEvent
slug: Web/API/MediaKeyMessageEvent
page-type: web-api-interface
browser-compat: api.MediaKeyMessageEvent
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeyMessageEvent`** interface of the [Encrypted Media Extensions API](/en-US/docs/Web/API/Encrypted_Media_Extensions_API) contains the content and related data when the content decryption module generates a message for the session.
{{InheritanceDiagram}}
## Constructor
- {{domxref("MediaKeyMessageEvent.MediaKeyMessageEvent","MediaKeyMessageEvent()")}}
- : Creates a new instance of `MediaKeyMessageEvent`.
## Instance properties
Inherits properties from its parent, {{domxref("Event")}}.
- {{domxref("MediaKeyMessageEvent.message")}} {{ReadOnlyInline}}
- : Returns an {{jsxref("ArrayBuffer")}} with a message from the content decryption module. Messages vary by key system.
- {{domxref("MediaKeyMessageEvent.messageType")}} {{ReadOnlyInline}}
- : Indicates the type of message. May be one of `license-request`, `license-renewal`, `license-release`, or `individualization-request`.
## Instance methods
Inherits methods from its parent, {{domxref("Event")}}.
## Examples
```js
// TBD
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeymessageevent | data/mdn-content/files/en-us/web/api/mediakeymessageevent/mediakeymessageevent/index.md | ---
title: "MediaKeyMessageEvent: MediaKeyMessageEvent() constructor"
short-title: MediaKeyMessageEvent()
slug: Web/API/MediaKeyMessageEvent/MediaKeyMessageEvent
page-type: web-api-constructor
browser-compat: api.MediaKeyMessageEvent.MediaKeyMessageEvent
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeyMessageEvent`** constructor creates a new {{domxref("MediaKeyMessageEvent")}} object.
## Syntax
```js-nolint
new MediaKeyMessageEvent(type)
new MediaKeyMessageEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `message`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `messageType`
- : A message type that allows applications to differentiate messages without parsing them.
Allowed values are: `license-request`, `license-renewal`, `license-renewal`, or `individualization-request`.
- `message`
- : An array containing the message generated by the content decryption module.
### Return value
A new {{domxref("MediaKeyMessageEvent")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeymessageevent | data/mdn-content/files/en-us/web/api/mediakeymessageevent/messagetype/index.md | ---
title: "MediaKeyMessageEvent: messageType property"
short-title: messageType
slug: Web/API/MediaKeyMessageEvent/messageType
page-type: web-api-instance-property
browser-compat: api.MediaKeyMessageEvent.messageType
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeyMessageEvent.messageType`** read-only property indicates the
type of message. It may be one of `license-request`,
`license-renewal`, `license-release`, or
`individualization-request`.
## Value
One of the following:
- `license-request`
- `license-renewal`
- `license-release`
- `individualization-request`
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediakeymessageevent | data/mdn-content/files/en-us/web/api/mediakeymessageevent/message/index.md | ---
title: "MediaKeyMessageEvent: message property"
short-title: message
slug: Web/API/MediaKeyMessageEvent/message
page-type: web-api-instance-property
browser-compat: api.MediaKeyMessageEvent.message
---
{{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}}
The **`MediaKeyMessageEvent.message`** read-only property
returns an {{jsxref("ArrayBuffer")}} with a message from the content decryption module.
Messages vary by key system.
## Value
An {{jsxref("ArrayBuffer")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/visualviewport/index.md | ---
title: VisualViewport
slug: Web/API/VisualViewport
page-type: web-api-interface
browser-compat: api.VisualViewport
---
{{APIRef("Visual Viewport")}}
The **`VisualViewport`** interface of the {{domxref("Visual Viewport API", "", "", "nocode")}} represents the visual viewport for a given window. For a page containing iframes, each iframe, as well as the containing page, will have a unique window object. Each window on a page will have a unique `VisualViewport` representing the properties associated with that window.
You can get a window's visual viewport using {{domxref("Window.visualViewport")}}.
> **Note:** Only the top-level window has a visual viewport that's distinct from the layout viewport. Therefore, it's generally only the `VisualViewport` object of the top-level window that's useful. For an {{htmlelement("iframe")}}, visual viewport metrics like {{domxref("VisualViewport.width")}} always correspond to layout viewport metrics like {{domxref("Element.clientWidth", "document.documentElement.clientWidth")}}.
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from its parent interface, {{domxref("EventTarget")}}._
- {{domxref("VisualViewport.offsetLeft")}} {{ReadOnlyInline}}
- : Returns the offset of the left edge of the visual viewport from the left edge of the layout viewport in CSS pixels.
- {{domxref("VisualViewport.offsetTop")}} {{ReadOnlyInline}}
- : Returns the offset of the top edge of the visual viewport from the top edge of the layout viewport in CSS pixels.
- {{domxref("VisualViewport.pageLeft")}} {{ReadOnlyInline}}
- : Returns the x coordinate of the visual viewport relative to the initial containing block origin of the top edge in CSS pixels.
- {{domxref("VisualViewport.pageTop")}} {{ReadOnlyInline}}
- : Returns the y coordinate of the visual viewport relative to the initial containing block origin of the top edge in CSS pixels.
- {{domxref("VisualViewport.width")}} {{ReadOnlyInline}}
- : Returns the width of the visual viewport in CSS pixels.
- {{domxref("VisualViewport.height")}} {{ReadOnlyInline}}
- : Returns the height of the visual viewport in CSS pixels.
- {{domxref("VisualViewport.scale")}} {{ReadOnlyInline}}
- : Returns the pinch-zoom scaling factor applied to the visual viewport.
## Instance methods
_Also inherits methods from its parent interface, {{domxref("EventTarget")}}._
## Events
Listen to these events using {{domxref("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the relevant `oneventname` property of this interface.
- {{domxref("VisualViewport/resize_event", "resize")}}
- : Fired when the visual viewport is resized.
Also available via the `onresize` property.
- {{domxref("VisualViewport/scroll_event", "scroll")}}
- : Fired when the visual viewport is scrolled.
Also available via the `onscroll` property.
## Examples
### Hiding an overlaid box on zoom
This example, taken from the [Visual Viewport README](https://github.com/WICG/visual-viewport), shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) when the user zooms in. This is a nice way to improve the user experience when zooming in on pages. A [live sample](https://wicg.github.io/visual-viewport/examples/hide-on-zoom.html) is also available.
```js
const bottomBar = document.getElementById("bottombar");
const viewport = window.visualViewport;
function resizeHandler() {
bottomBar.style.display = viewport.scale > 1.3 ? "none" : "block";
}
window.visualViewport.addEventListener("resize", resizeHandler);
```
### Simulating position: device-fixed
This example, also taken from the [Visual Viewport README](https://github.com/WICG/visual-viewport), shows how to use this API to simulate `position: device-fixed`, which fixes elements to the visual viewport. A [live sample](https://wicg.github.io/visual-viewport/examples/fixed-to-viewport.html) is also available.
```js
const bottomBar = document.getElementById("bottombar");
const viewport = window.visualViewport;
function viewportHandler() {
const layoutViewport = document.getElementById("layoutViewport");
// Since the bar is position: fixed we need to offset it by the visual
// viewport's offset from the layout viewport origin.
const offsetLeft = viewport.offsetLeft;
const offsetTop =
viewport.height -
layoutViewport.getBoundingClientRect().height +
viewport.offsetTop;
// You could also do this by setting style.left and style.top if you
// use width: 100% instead.
bottomBar.style.transform = `translate(${offsetLeft}px, ${offsetTop}px) scale(${
1 / viewport.scale
})`;
}
window.visualViewport.addEventListener("scroll", viewportHandler);
window.visualViewport.addEventListener("resize", viewportHandler);
```
> **Note:** This technique should be used with care; emulating `position: device-fixed` in this way can result in the fixed element flickering during scrolling.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Viewports Explainer](https://github.com/bokand/bokand.github.io/blob/master/web_viewports_explainer.md) — useful explanation of web viewports concepts, including the difference between visual viewport and layout viewport.
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/scale/index.md | ---
title: "VisualViewport: scale property"
short-title: scale
slug: Web/API/VisualViewport/scale
page-type: web-api-instance-property
browser-compat: api.VisualViewport.scale
---
{{APIRef("Visual Viewport")}}
The **`scale`** read-only property of the {{domxref("VisualViewport")}} interface returns the pinch-zoom scaling factor applied to the visual viewport, or `0` if current document is not fully active, or `1` if there is no output device.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/pageleft/index.md | ---
title: "VisualViewport: pageLeft property"
short-title: pageLeft
slug: Web/API/VisualViewport/pageLeft
page-type: web-api-instance-property
browser-compat: api.VisualViewport.pageLeft
---
{{APIRef("Visual Viewport")}}
The **`pageLeft`** read-only property of the {{domxref("VisualViewport")}} interface returns the x coordinate of the left edge of the visual viewport relative to the initial containing block origin, in CSS pixels, or `0` if current document is not fully active.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/resize_event/index.md | ---
title: "VisualViewport: resize event"
short-title: resize
slug: Web/API/VisualViewport/resize_event
page-type: web-api-event
browser-compat: api.VisualViewport.resize_event
---
{{APIRef("Visual Viewport")}}
The **`resize`** event of the {{domxref("VisualViewport")}} interface is fired when the visual viewport is resized.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("resize", (event) => {});
onresize = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
You can use the `resize` event in an {{domxref("EventTarget.addEventListener", "addEventListener()")}} method:
```js
visualViewport.addEventListener("resize", () => {
// …
});
```
Or use the `onresize` event handler property:
```js
visualViewport.onresize = () => {
// …
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/pagetop/index.md | ---
title: "VisualViewport: pageTop property"
short-title: pageTop
slug: Web/API/VisualViewport/pageTop
page-type: web-api-instance-property
browser-compat: api.VisualViewport.pageTop
---
{{APIRef("Visual Viewport")}}
The **`pageTop`** read-only property of the {{domxref("VisualViewport")}} interface returns the y coordinate of the top edge of the visual viewport relative to the initial containing block origin, in CSS pixels, or `0` if current document is not fully active.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/width/index.md | ---
title: "VisualViewport: width property"
short-title: width
slug: Web/API/VisualViewport/width
page-type: web-api-instance-property
browser-compat: api.VisualViewport.width
---
{{APIRef("Visual Viewport")}}
The **`width`** read-only property of the {{domxref("VisualViewport")}} interface returns the width of the visual viewport, in CSS pixels, or `0` if current document is not fully active.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/offsettop/index.md | ---
title: "VisualViewport: offsetTop property"
short-title: offsetTop
slug: Web/API/VisualViewport/offsetTop
page-type: web-api-instance-property
browser-compat: api.VisualViewport.offsetTop
---
{{APIRef("Visual Viewport")}}
The **`offsetTop`** read-only property of the {{domxref("VisualViewport")}} interface returns the offset of the top edge of the visual viewport from the top edge of the layout viewport in CSS pixels, or `0` if current document is not fully active.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/height/index.md | ---
title: "VisualViewport: height property"
short-title: height
slug: Web/API/VisualViewport/height
page-type: web-api-instance-property
browser-compat: api.VisualViewport.height
---
{{APIRef("Visual Viewport")}}
The **`height`** read-only property of the {{domxref("VisualViewport")}} interface returns the height of the visual viewport, in CSS pixels, or `0` if current document is not fully active.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/offsetleft/index.md | ---
title: "VisualViewport: offsetLeft property"
short-title: offsetLeft
slug: Web/API/VisualViewport/offsetLeft
page-type: web-api-instance-property
browser-compat: api.VisualViewport.offsetLeft
---
{{APIRef("Visual Viewport")}}
The **`offsetLeft`** read-only property of the {{domxref("VisualViewport")}} interface returns the offset of the left edge of the visual viewport from the left edge of the layout viewport in CSS pixels, or `0` if current document is not fully active.
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/visualviewport | data/mdn-content/files/en-us/web/api/visualviewport/scroll_event/index.md | ---
title: "VisualViewport: scroll event"
short-title: scroll
slug: Web/API/VisualViewport/scroll_event
page-type: web-api-event
browser-compat: api.VisualViewport.scroll_event
---
{{APIRef("Visual Viewport")}}
The **`scroll`** event of the {{domxref("VisualViewport")}} interface is fired when the visual viewport is scrolled.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("scroll", (event) => {});
onscroll = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
You can use the `scroll` event in an {{domxref("EventTarget.addEventListener", "addEventListener()")}} method:
```js
visualViewport.addEventListener("scroll", () => {
// …
});
```
Or use the `onscroll` event handler property:
```js
visualViewport.onscroll = () => {
// …
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/pushsubscriptionoptions/index.md | ---
title: PushSubscriptionOptions
slug: Web/API/PushSubscriptionOptions
page-type: web-api-interface
browser-compat: api.PushSubscriptionOptions
---
{{DefaultAPISidebar("Push API")}}{{SecureContext_Header}}
The **`PushSubscriptionOptions`** interface of the {{domxref('Push API','','',' ')}} represents the options associated with a push subscription.
The read-only `PushSubscriptionOptions` object is returned by calling {{domxref("PushSubscription.options")}} on a {{domxref("PushSubscription")}}. This interface has no constructor of its own.
## Instance properties
- {{domxref("PushSubscriptionOptions.userVisibleOnly")}} {{ReadOnlyInline}}
- : A boolean value indicating that the returned push
subscription will only be used for messages whose effect is made visible to the user.
- {{domxref("PushSubscriptionOptions.applicationServerKey")}} {{ReadOnlyInline}}
- : A public key your push server will use to send
messages to client apps via a push server.
## Examples
Calling {{domxref("PushSubscription.options")}} on a {{domxref("PushSubscription")}} returns a `PushSubscriptionOptions` object. In the example below this is printed to the console.
```js
navigator.serviceWorker.ready.then((reg) => {
reg.pushManager.getSubscription().then((subscription) => {
const options = subscription.options;
console.log(options); // a PushSubscriptionOptions object
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/pushsubscriptionoptions | data/mdn-content/files/en-us/web/api/pushsubscriptionoptions/uservisibleonly/index.md | ---
title: "PushSubscriptionOptions: userVisibleOnly property"
short-title: userVisibleOnly
slug: Web/API/PushSubscriptionOptions/userVisibleOnly
page-type: web-api-instance-property
browser-compat: api.PushSubscriptionOptions.userVisibleOnly
---
{{DefaultAPISidebar("Push API")}}{{SecureContext_Header}}
The **`userVisibleOnly`** read-only property of the {{domxref("PushSubscriptionOptions")}} interface indicates if the returned push subscription will only be used for messages whose effect is made visible to the user.
## Value
A boolean value that indicates whether the returned push subscription will only be used for messages whose effect is made visible to the user.
## Examples
In the example below the value of `userVisibleOnly` is printed to the console.
```js
navigator.serviceWorker.ready.then((reg) => {
reg.pushManager.getSubscription().then((subscription) => {
const options = subscription.options;
console.log(options.userVisibleOnly); // true if this is a user visible subscription
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/pushsubscriptionoptions | data/mdn-content/files/en-us/web/api/pushsubscriptionoptions/applicationserverkey/index.md | ---
title: "PushSubscriptionOptions: applicationServerKey property"
short-title: applicationServerKey
slug: Web/API/PushSubscriptionOptions/applicationServerKey
page-type: web-api-instance-property
browser-compat: api.PushSubscriptionOptions.applicationServerKey
---
{{DefaultAPISidebar("Push API")}}{{SecureContext_Header}}
The **`applicationServerKey`** read-only property of the {{domxref("PushSubscriptionOptions")}} interface contains the public key used by the push server.
## Value
A public key your push server uses to send messages to client apps via a push server. This value is part of a signing key pair generated by your application server, and usable with elliptic curve digital signature (ECDSA), over the P-256 curve. If no `applicationServerKey` member is passed when initialized, it will be set to `null`.
## Examples
In the example below the value of `applicationServerKey` is printed to the console.
```js
navigator.serviceWorker.ready.then((reg) => {
reg.pushManager.getSubscription().then((subscription) => {
const options = subscription.options;
console.log(options.applicationServerKey); // the public key
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediastream/index.md | ---
title: MediaStream
slug: Web/API/MediaStream
page-type: web-api-interface
browser-compat: api.MediaStream
---
{{APIRef("Media Capture and Streams")}}
The **`MediaStream`** interface of the {{domxref("Media Capture and Streams API", "", "", "nocode")}} represents a stream of media content. A stream consists of several **tracks**, such as video or audio tracks. Each track is specified as an instance of {{domxref("MediaStreamTrack")}}.
You can obtain a `MediaStream` object either by using the constructor or by calling functions such as {{domxref("MediaDevices.getUserMedia()")}}, {{domxref("MediaDevices.getDisplayMedia()")}}, or {{domxref("HTMLCanvasElement.captureStream()")}} and {{domxref("HTMLMediaElement.captureStream()")}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("MediaStream.MediaStream", "MediaStream()")}}
- : Creates and returns a new `MediaStream` object. You can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of {{domxref("MediaStreamTrack")}} objects).
## Instance properties
_This interface inherits properties from its parent, {{domxref("EventTarget")}}._
- {{domxref("MediaStream.active")}} {{ReadOnlyInline}}
- : A Boolean value that returns `true` if the `MediaStream` is active, or `false` otherwise.
- {{domxref("MediaStream.id")}} {{ReadOnlyInline}}
- : A string containing a 36-character universally unique identifier ({{Glossary("UUID")}}) for the object.
## Instance methods
_This interface inherits methods from its parent, {{domxref("EventTarget")}}._
- {{domxref("MediaStream.addTrack()")}}
- : Stores a copy of the {{domxref("MediaStreamTrack")}} given as argument. If the track has already been added to the `MediaStream` object, nothing happens.
- {{domxref("MediaStream.clone()")}}
- : Returns a clone of the `MediaStream` object. The clone will, however, have a unique value for {{domxref("MediaStream.id", "id")}}.
- {{domxref("MediaStream.getAudioTracks()")}}
- : Returns a list of the {{domxref("MediaStreamTrack")}} objects stored in the `MediaStream` object that have their `kind` attribute set to `audio`. The order is not defined, and may not only vary from one browser to another, but also from one call to another.
- {{domxref("MediaStream.getTrackById()")}}
- : Returns the track whose ID corresponds to the one given in parameters, `trackid`. If no parameter is given, or if no track with that ID does exist, it returns `null`. If several tracks have the same ID, it returns the first one.
- {{domxref("MediaStream.getTracks()")}}
- : Returns a list of all {{domxref("MediaStreamTrack")}} objects stored in the `MediaStream` object, regardless of the value of the `kind` attribute. The order is not defined, and may not only vary from one browser to another, but also from one call to another.
- {{domxref("MediaStream.getVideoTracks()")}}
- : Returns a list of the {{domxref("MediaStreamTrack")}} objects stored in the `MediaStream` object that have their `kind` attribute set to `"video"`. The order is not defined, and may not only vary from one browser to another, but also from one call to another.
- {{domxref("MediaStream.removeTrack()")}}
- : Removes the {{domxref("MediaStreamTrack")}} given as argument. If the track is not part of the `MediaStream` object, nothing happens.
## Events
- {{domxref("MediaStream/addtrack_event", "addtrack")}}
- : Fired when a new {{domxref("MediaStreamTrack")}} object is added.
- {{domxref("MediaStream/removetrack_event", "removetrack")}}
- : Fired when a {{domxref("MediaStreamTrack")}} object has been removed.
- {{domxref("MediaStream/active_event", "active")}} {{Non-standard_Inline}}
- : Fired when the MediaStream is activated.
- {{domxref("MediaStream/inactive_event", "inactive")}} {{Non-standard_Inline}}
- : Fired when the MediaStream is inactivated.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API)
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
- {{domxref("MediaStreamTrack")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/clone/index.md | ---
title: "MediaStream: clone() method"
short-title: clone()
slug: Web/API/MediaStream/clone
page-type: web-api-instance-method
browser-compat: api.MediaStream.clone
---
{{APIRef("Media Capture and Streams")}}
The **`clone()`** method of the {{domxref("MediaStream")}}
interface creates a duplicate of the `MediaStream`. This new
`MediaStream` object has a new unique {{domxref("MediaStream.id", "id")}} and
contains clones of every {{domxref("MediaStreamTrack")}} contained by the
`MediaStream` on which `clone()` was called.
## Syntax
```js-nolint
clone()
```
### Parameters
None.
### Return value
A new {{domxref("MediaStream")}} instance which has a new unique ID and contains clones
of every {{domxref("MediaStreamTrack")}} contained by the `MediaStream` on
which `clone()` was called.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/addtrack_event/index.md | ---
title: "MediaStream: addtrack event"
short-title: addtrack
slug: Web/API/MediaStream/addtrack_event
page-type: web-api-event
browser-compat: api.MediaStream.addtrack_event
---
{{APIRef("Media Capture and Streams")}}
The **`addtrack`** event is fired when a new [`MediaStreamTrack`](/en-US/docs/Web/API/MediaStreamTrack) object has been added to a [`MediaStream`](/en-US/docs/Web/API/MediaStream).
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("addtrack", (event) => {});
onaddtrack = (event) => {};
```
## Event type
A {{domxref("MediaStreamTrackEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MediaStreamTrackEvent")}}
## Event properties
_Also inherits properties from its parent interface, {{domxref("Event")}}._
- {{domxref("MediaStreamTrackEvent.track")}} {{ReadOnlyInline}}
- : A {{domxref("MediaStreamTrack")}} object representing the track which was added to the stream.
## Examples
Using `addEventListener()`:
```js
const stream = new MediaStream();
stream.addEventListener("addtrack", (event) => {
console.log(`New ${event.track.kind} track added`);
});
```
Using the `onaddtrack` event handler property:
```js
const stream = new MediaStream();
stream.onaddtrack = (event) => {
console.log(`New ${event.track.kind} track added`);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`removetrack`](/en-US/docs/Web/API/MediaStream/removetrack_event)
- This event on [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList) targets: [`addtrack`](/en-US/docs/Web/API/AudioTrackList/addtrack_event)
- This event on [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList) targets: [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_event)
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/removetrack_event/index.md | ---
title: "MediaStream: removetrack event"
short-title: removetrack
slug: Web/API/MediaStream/removetrack_event
page-type: web-api-event
browser-compat: api.MediaStream.removetrack_event
---
{{APIRef("Media Capture and Streams")}}
The **`removetrack`** event is fired when a new {{domxref("MediaStreamTrack")}} object has been removed from a {{domxref("MediaStream")}}.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("removetrack", (event) => {});
onremovetrack = (event) => {};
```
## Event type
A {{domxref("MediaStreamTrackEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MediaStreamTrackEvent")}}
## Event properties
_Also inherits properties from its parent interface, {{domxref("Event")}}._
- {{domxref("MediaStreamTrackEvent.track")}} {{ReadOnlyInline}}
- : A {{domxref("MediaStreamTrack")}} object representing the track which was removed from the stream.
## Examples
Using `addEventListener()`:
```js
const stream = new MediaStream();
stream.addEventListener("removetrack", (event) => {
console.log(`${event.track.kind} track removed`);
});
```
Using the `onremovetrack` event handler property:
```js
const stream = new MediaStream();
stream.onremovetrack = (event) => {
console.log(`${event.track.kind} track removed`);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`addtrack`](/en-US/docs/Web/API/MediaStream/addtrack_event)
- This event on [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList) targets: [`removetrack`](/en-US/docs/Web/API/AudioTrackList/removetrack_event)
- This event on [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList) targets: [`removetrack`](/en-US/docs/Web/API/VideoTrackList/removetrack_event)
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/mediastream/index.md | ---
title: "MediaStream: MediaStream() constructor"
short-title: MediaStream()
slug: Web/API/MediaStream/MediaStream
page-type: web-api-constructor
browser-compat: api.MediaStream.MediaStream
---
{{APIRef("Media Capture and Streams")}}
The **`MediaStream()`** constructor returns a newly-created {{domxref("MediaStream")}}, which serves as a collection of media tracks, each represented by a {{domxref("MediaStreamTrack")}} object.
If any parameters are given, the specified tracks are added to the new stream.
Otherwise, the stream has no tracks.
## Syntax
```js-nolint
new MediaStream()
new MediaStream(stream)
new MediaStream(tracks)
```
### Parameters
- `stream` {{optional_inline}}
- : A different {{domxref("MediaStream")}} object whose tracks are added to the
newly-created stream automatically. The tracks are not removed from the original
stream, so they're shared by the two streams.
- `tracks` {{optional_inline}}
- : An {{jsxref("Array")}} of {{domxref("MediaStreamTrack")}} objects, one for each
track to add to the stream.
### Return value
A newly-created {{domxref("MediaStream")}} object, either empty, or containing the
tracks provided, if any.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaStream")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/id/index.md | ---
title: "MediaStream: id property"
short-title: id
slug: Web/API/MediaStream/id
page-type: web-api-instance-property
browser-compat: api.MediaStream.id
---
{{APIRef("Media Capture and Streams")}}
The **`id`** read-only property of the {{domxref("MediaStream")}} interface is a
string containing 36 characters denoting a unique identifier (GUID)
for the object.
## Value
A string.
## Examples
```js
const promise = navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
});
promise.then((stream) => {
console.log(stream.id);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaStream")}}, the interface this property belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/getaudiotracks/index.md | ---
title: "MediaStream: getAudioTracks() method"
short-title: getAudioTracks()
slug: Web/API/MediaStream/getAudioTracks
page-type: web-api-instance-method
browser-compat: api.MediaStream.getAudioTracks
---
{{APIRef("Media Capture and Streams")}}
The **`getAudioTracks()`** method of the
{{domxref("MediaStream")}} interface returns a sequence that represents all the
{{domxref("MediaStreamTrack")}} objects in this
stream's [`track set`](https://www.w3.org/TR/mediacapture-streams/#track-set) where {{domxref("MediaStreamTrack.kind")}}
is `audio`.
## Syntax
```js-nolint
getAudioTracks()
```
### Parameters
None.
### Return value
An array of {{domxref("MediaStreamTrack")}} objects, one for each audio track contained
in the stream. Audio tracks are those tracks whose {{domxref("MediaStreamTrack.kind",
"kind")}} property is `audio`. The array is empty if the stream contains no
audio tracks.
> **Note:** The order of the returned tracks is not defined by the
> specification and may, in fact, change from one call to `getAudioTracks()`
> to the next.
Early versions of this API included a special `AudioStreamTrack` interface
which was used as the type for each entry in the list of audio streams; however, this
has since been merged into the main {{domxref("MediaStreamTrack")}} interface.
## Examples
This example gets a webcam's audio and video in a stream using
{{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}, attaches the stream to a
{{HTMLElement("video")}} element, then sets a timer that, upon expiring, will stop the
first audio track found on the stream.
```js
navigator.mediaDevices
.getUserMedia({ audio: true, video: true })
.then((mediaStream) => {
document.querySelector("video").srcObject = mediaStream;
// Stop the audio stream after 5 seconds
setTimeout(() => {
const tracks = mediaStream.getAudioTracks();
tracks[0].stop();
}, 5000);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/gettrackbyid/index.md | ---
title: "MediaStream: getTrackById() method"
short-title: getTrackById()
slug: Web/API/MediaStream/getTrackById
page-type: web-api-instance-method
browser-compat: api.MediaStream.getTrackById
---
{{APIRef("Media Capture and Streams")}}
The **`getTrackById()`** method of the {{domxref("MediaStream")}} interface
returns a {{domxref("MediaStreamTrack")}} object representing the track with the specified ID
string. If there is no track with the specified ID, this method returns `null`.
## Syntax
```js-nolint
getTrackById(id)
```
### Parameters
- `id`
- : A string which identifies the track to be returned.
### Return value
If a track is found for which {{domxref("MediaStreamTrack.id")}} matches the specified
`id` string, that {{domxref("MediaStreamTrack")}} object is returned.
Otherwise, the returned value is `null`.
## Examples
This example activates a commentary track on a video by ducking the audio level of the
main audio track to 50%, then enabling the commentary track.
```js
stream.getTrackById("primary-audio-track").applyConstraints({ volume: 0.5 });
stream.getTrackById("commentary-track").enabled = true;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaStream")}}
- {{domxref("MediaStreamTrack.id")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/gettracks/index.md | ---
title: "MediaStream: getTracks() method"
short-title: getTracks()
slug: Web/API/MediaStream/getTracks
page-type: web-api-instance-method
browser-compat: api.MediaStream.getTracks
---
{{APIRef("Media Capture and Streams")}}
The **`getTracks()`** method of the
{{domxref("MediaStream")}} interface returns a sequence that represents all the
{{domxref("MediaStreamTrack")}} objects in this
stream's [`track set`](https://www.w3.org/TR/mediacapture-streams/#track-set),
regardless of {{domxref("MediaStreamTrack.kind")}}.
## Syntax
```js-nolint
getTracks()
```
### Parameters
None.
### Return value
An array of {{domxref("MediaStreamTrack")}} objects.
## Examples
```js
navigator.mediaDevices
.getUserMedia({ audio: false, video: true })
.then((mediaStream) => {
document.querySelector("video").srcObject = mediaStream;
// Stop the stream after 5 seconds
setTimeout(() => {
const tracks = mediaStream.getTracks();
tracks[0].stop();
}, 5000);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/getvideotracks/index.md | ---
title: "MediaStream: getVideoTracks() method"
short-title: getVideoTracks()
slug: Web/API/MediaStream/getVideoTracks
page-type: web-api-instance-method
browser-compat: api.MediaStream.getVideoTracks
---
{{APIRef("Media Capture and Streams")}}
The **`getVideoTracks()`** method of the
{{domxref("MediaStream")}} interface returns a sequence of
{{domxref("MediaStreamTrack")}} objects representing the video tracks in this stream.
## Syntax
```js-nolint
getVideoTracks()
```
### Parameters
None.
### Return value
An array of {{domxref("MediaStreamTrack")}} objects, one for each video track contained
in the media stream. Video tracks are those tracks whose
{{domxref("MediaStreamTrack.kind", "kind")}} property is `video`. The array
is empty if the stream contains no video tracks.
> **Note:** The order of the tracks is not defined by the specification,
> and may not be the same from one call to `getVideoTracks()` to another.
## Examples
The following example, extracted from [Chrome's
Image Capture / Photo Resolution Sample](https://googlechrome.github.io/samples/image-capture/photo-resolution.html), uses `getVideoTracks()` to
retrieve a track for passing to the {{domxref("ImageCapture.ImageCapture",
"ImageCapture()")}} constructor.
```js
let imageCapture;
navigator.mediaDevices.getUserMedia({ video: true }).then((mediaStream) => {
document.querySelector("video").srcObject = mediaStream;
const track = mediaStream.getVideoTracks()[0];
imageCapture = new ImageCapture(track);
return imageCapture.getPhotoCapabilities();
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/addtrack/index.md | ---
title: "MediaStream: addTrack() method"
short-title: addTrack()
slug: Web/API/MediaStream/addTrack
page-type: web-api-instance-method
browser-compat: api.MediaStream.addTrack
---
{{APIRef("Media Capture and Streams")}}
The **`addTrack()`** method of the {{domxref("MediaStream")}} interface adds a new track to the
stream. The track is specified as a parameter of type {{domxref("MediaStreamTrack")}}.
> **Note:** If the specified track is already in the stream's track set, this method has no
> effect.
## Syntax
```js-nolint
addTrack(track)
```
### Parameters
- `track`
- : A {{domxref("MediaStreamTrack")}} to add to the stream.
### Return value
None ({{jsxref("undefined")}}).
## Examples
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaStream")}}, the interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/active/index.md | ---
title: "MediaStream: active property"
short-title: active
slug: Web/API/MediaStream/active
page-type: web-api-instance-property
browser-compat: api.MediaStream.active
---
{{APIRef("Media Capture and Streams")}}
The **`active`** read-only property of the
{{domxref("MediaStream")}} interface returns a Boolean value which is
`true` if the stream is currently active; otherwise, it returns
`false`. A stream is considered **active** if at least one of
its {{domxref("MediaStreamTrack")}}s does not have its property {{domxref("MediaStreamTrack.readyState")}}
set to `ended`. Once every track has ended, the stream's `active` property becomes
`false`.
## Value
A Boolean value which is `true` if the stream is currently active;
otherwise, the value is `false`.
## Examples
In this example, a new stream whose source is the user's local camera and microphone is
requested using {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}. When that
stream becomes available (that is, when the returned {{jsxref("Promise")}} is fulfilled,
a button on the page is updated based on whether or not the stream is currently active.
```js
const promise = navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
});
promise.then((stream) => {
const startBtn = document.querySelector("#startBtn");
startBtn.disabled = stream.active;
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastream | data/mdn-content/files/en-us/web/api/mediastream/removetrack/index.md | ---
title: "MediaStream: removeTrack() method"
short-title: removeTrack()
slug: Web/API/MediaStream/removeTrack
page-type: web-api-instance-method
browser-compat: api.MediaStream.removeTrack
---
{{APIRef("Media Capture and Streams")}}
The **`removeTrack()`** method of the {{domxref("MediaStream")}} interface removes a
{{domxref("MediaStreamTrack")}} from a stream.
## Syntax
```js-nolint
removeTrack(track)
```
### Parameters
- `track`
- : A {{domxref("MediaStreamTrack")}} that will be removed from the stream.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following example demonstrates how to remove the audio and video tracks from a {{domxref("MediaStream")}}.
`fetchStreamFunction` is an event handler for `fetchStreamButton`. When the button is clicked, audio
and video are captured from the system's devices. `removeTracksFunction` is the event handler for `removeTracksButton`.
When this button is clicked, the audio and video tracks are removed from the {{domxref("MediaStream")}}.
```js
let initialStream = null;
let newStream = null;
let fetchStreamButton = document.getElementById("fetchStream");
let removeTracksButton = document.getElementById("removeTracks");
async function fetchStreamFunction() {
initialStream = await navigator.mediaDevices.getUserMedia({
video: { width: 620, height: 310 },
audio: true,
});
if (initialStream) {
await attachToDOM(initialStream);
}
}
async function attachToDOM(stream) {
newStream = new MediaStream(stream.getTracks());
document.querySelector("video").srcObject = newStream;
}
async function removeTracksFunction() {
let videoTrack = newStream.getVideoTracks()[0];
let audioTrack = newStream.getAudioTracks()[0];
newStream.removeTrack(videoTrack);
newStream.removeTrack(audioTrack);
// Stream will be empty
console.log(newStream.getTracks());
}
fetchStreamButton.addEventListener("click", fetchStreamFunction);
removeTracksButton.addEventListener("click", removeTracksFunction);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/createimagebitmap/index.md | ---
title: createImageBitmap() global function
short-title: createImageBitmap()
slug: Web/API/createImageBitmap
page-type: web-api-global-function
browser-compat: api.createImageBitmap
---
{{APIRef("Canvas API")}}{{AvailableInWorkers}}
The **`createImageBitmap()`** method creates a bitmap from a
given source, optionally cropped to contain only a portion of that source. The method
exists on the global scope in both windows and workers. It accepts a variety of
different image sources, and returns a {{jsxref("Promise")}} which resolves to an
{{domxref("ImageBitmap")}}.
## Syntax
```js-nolint
createImageBitmap(image)
createImageBitmap(image, options)
createImageBitmap(image, sx, sy, sw, sh)
createImageBitmap(image, sx, sy, sw, sh, options)
```
### Parameters
- `image`
- : An image source, which can be any one of the following:
- {{domxref("HTMLImageElement")}}
- {{domxref("SVGImageElement")}}
- {{domxref("HTMLVideoElement")}}
- {{domxref("HTMLCanvasElement")}}
- {{domxref("Blob")}}
- {{domxref("ImageData")}}
- {{domxref("ImageBitmap")}}
- {{domxref("OffscreenCanvas")}}
- `sx`
- : The x coordinate of the reference point of the rectangle from which the
`ImageBitmap` will be extracted.
- `sy`
- : The y coordinate of the reference point of the rectangle from which the
`ImageBitmap` will be extracted.
- `sw`
- : The width of the rectangle from which the `ImageBitmap` will be
extracted. This value can be negative.
- `sh`
- : The height of the rectangle from which the `ImageBitmap` will be
extracted. This value can be negative.
- `options` {{optional_inline}}
- : An object that sets options for the image's extraction. The available options are:
- `imageOrientation`
- : Specifies whether the image should be presented
as is or flipped vertically. Either `none` (default) or
`flipY`.
- `premultiplyAlpha`
- : Specifies whether the bitmap's color channels
should be premultiplied by the alpha channel. One of `none`,
`premultiply`, or `default` (default).
- `colorSpaceConversion`
- : Specifies whether the image should be decoded
using color space conversion. Either `none` or `default`
(default). The value `default` indicates that implementation-specific
behavior is used.
- `resizeWidth`
- : A long integer that indicates the output width.
- `resizeHeight`
- : A long integer that indicates the output height.
- `resizeQuality`
- : Specifies the algorithm to be used for resizing the
input to match the output dimensions. One of `pixelated`,
`low` (default), `medium`, or `high`.
### Return value
A {{jsxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}} object
containing bitmap data from the given rectangle.
## Examples
### Creating sprites from a sprite sheet
This example loads a sprite sheet, extracts individual sprites, and then renders each
sprite to the canvas. A sprite sheet is an image containing multiple smaller images,
each of which you want to be able to render separately.
```js
const canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d"),
image = new Image();
// Wait for the sprite sheet to load
image.onload = () => {
Promise.all([
// Cut out two sprites from the sprite sheet
createImageBitmap(image, 0, 0, 32, 32),
createImageBitmap(image, 32, 0, 32, 32),
]).then((sprites) => {
// Draw each sprite onto the canvas
ctx.drawImage(sprites[0], 0, 0);
ctx.drawImage(sprites[1], 32, 32);
});
};
// Load the sprite sheet from an image file
image.src = "sprites.png";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CanvasRenderingContext2D.drawImage()")}}
- {{domxref("ImageData")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/ext_texture_norm16/index.md | ---
title: EXT_texture_norm16 extension
short-title: EXT_texture_norm16
slug: Web/API/EXT_texture_norm16
page-type: webgl-extension
browser-compat: api.EXT_texture_norm16
---
{{APIRef("WebGL")}}
The **`EXT_texture_norm16`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and provides a set of new 16-bit signed normalized and unsigned normalized formats (fixed-point texture, renderbuffer and texture buffer).
When this extension is enabled:
- The {{domxref("WebGLRenderingContext.texImage2D()")}} and {{domxref("WebGLRenderingContext.texSubImage2D()")}} methods accept new formats provided by this extension.
- The 16-bit normalized fixed-point types `ext.R16_EXT`, `ext.RG16_EXT` and `ext.RGBA16_EXT` become available as color-renderable formats and renderbuffers and be created in these formats.
WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
> **Note:** This extension is only available to {{domxref("WebGL2RenderingContext", "WebGL 2", "", 1)}} contexts.
## Constants
- `ext.R16_EXT`
- : Red 16-bit unsigned format. Color-renderable.
- `ext.RG16_EXT`
- : RG 16-bit unsigned format. Color-renderable.
- `ext.RGB16_EXT`
- : RGB 16-bit unsigned format.
- `ext.RGBA16_EXT`
- : RGBA 16-bit unsigned format. Color-renderable.
- `ext.R16_SNORM_EXT`
- : Red 16-bit signed normalized format.
- `ext.RG16_SNORM_EXT`
- : RG 16-bit signed normalized format.
- `ext.RGB16_SNORM_EXT`
- : RGB 16-bit signed normalized format.
- `ext.RGBA16_SNORM_EXT`
- : RGBA 16-bit signed normalized format.
## Examples
### Enabling the extension
```js
let ext = gl.getExtension("EXT_texture_norm16");
```
### Texture formats
The {{domxref("WebGLRenderingContext.texImage2D()")}} method accepts new formats when `EXT_texture_norm16` is enabled. Example calls:
```js-nolint
// imageData = Uint16Array
gl.texImage2D(gl.TEXTURE_2D, 0, ext.R16_EXT, 1, 1, 0, gl.RED, gl.UNSIGNED_SHORT, imageData);
gl.texImage2D(gl.TEXTURE_2D, 0, ext.RG16_EXT, 1, 1, 0, gl.RG, gl.UNSIGNED_SHORT, imageData);
gl.texImage2D(gl.TEXTURE_2D, 0, ext.RGB16_EXT, 1, 1, 0, gl.RGB, gl.UNSIGNED_SHORT, imageData);
gl.texImage2D(gl.TEXTURE_2D, 0, ext.RGBA16_EXT, 1, 1, 0, gl.RGBA, gl.UNSIGNED_SHORT, imageData);
// imageData = Int16Array
gl.texImage2D(gl.TEXTURE_2D, 0, ext.R16_SNORM_EXT, 1, 1, 0, gl.RED, gl.SHORT, imageData);
gl.texImage2D(gl.TEXTURE_2D, 0, ext.RG16_SNORM_EXT, 1, 1, 0, gl.RG, gl.SHORT, imageData);
gl.texImage2D(gl.TEXTURE_2D, 0, ext.RGB16_SNORM_EXT, 1, 1, 0, gl.RGB, gl.SHORT, imageData);
gl.texImage2D(gl.TEXTURE_2D, 0, ext.RGBA16_SNORM_EXT, 1, 1, 0, gl.RGBA, gl.SHORT, imageData);
```
### Renderbuffer formats
The {{domxref("WebGLRenderingContext.renderbufferStorage()")}} method accepts `ext.R16_EXT`,
`ext.RG16_EXT` and `ext.RGBA16_EXT` as internal formats to create renderbuffers in these formats. Example calls:
```js
gl.renderbufferStorage(gl.RENDERBUFFER, ext.R16_EXT, 1, 1);
gl.renderbufferStorage(gl.RENDERBUFFER, ext.RG16_EXT, 1, 1);
gl.renderbufferStorage(gl.RENDERBUFFER, ext.RGBA16_EXT, 1, 1);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.getExtension()")}}
- {{domxref("WebGLRenderingContext.texImage2D()")}}
- {{domxref("WebGLRenderingContext.renderbufferStorage()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/canvasgradient/index.md | ---
title: CanvasGradient
slug: Web/API/CanvasGradient
page-type: web-api-interface
browser-compat: api.CanvasGradient
---
{{APIRef("Canvas API")}}
The **`CanvasGradient`** interface represents an [opaque object](https://en.wikipedia.org/wiki/Opaque_data_type) describing a gradient. It is returned by the methods {{domxref("CanvasRenderingContext2D.createLinearGradient()")}}, {{domxref("CanvasRenderingContext2D.createConicGradient()")}} or {{domxref("CanvasRenderingContext2D.createRadialGradient()")}}.
It can be used as a {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} or {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}}.
## Instance properties
_As an opaque object, there is no exposed property._
## Instance methods
- {{domxref("CanvasGradient.addColorStop()")}}
- : Adds a new stop, defined by an `offset` and a `color`, to the gradient.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Creator methods in {{domxref("CanvasRenderingContext2D")}}.
- The {{HTMLElement("canvas")}} element and its associated interface, {{domxref("HTMLCanvasElement")}}.
| 0 |
data/mdn-content/files/en-us/web/api/canvasgradient | data/mdn-content/files/en-us/web/api/canvasgradient/addcolorstop/index.md | ---
title: "CanvasGradient: addColorStop() method"
short-title: addColorStop()
slug: Web/API/CanvasGradient/addColorStop
page-type: web-api-instance-method
browser-compat: api.CanvasGradient.addColorStop
---
{{APIRef("Canvas API")}}
The **`CanvasGradient.addColorStop()`** method adds a new color stop,
defined by an `offset` and a `color`, to a given canvas gradient.
## Syntax
```js-nolint
addColorStop(offset, color)
```
### Parameters
- `offset`
- : A number between `0` and `1`, inclusive, representing the
position of the color stop. `0` represents the start of the gradient and
`1` represents the end.
- `color`
- : A [CSS](/en-US/docs/Web/CSS) {{cssxref("<color>")}} value
representing the color of the stop.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `IndexSizeError` {{domxref("DOMException")}}
- : Thrown if `offset` is not between 0 and 1 (both included).
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if `color` cannot be parsed as a CSS {{cssxref("<color>")}} value.
## Examples
### Adding stops to a gradient
This example uses the `addColorStop` method to add stops to a linear
{{domxref("CanvasGradient")}} object. The gradient is then used to fill a rectangle.
#### HTML
```html
<canvas id="canvas"></canvas>
```
#### JavaScript
```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "green");
gradient.addColorStop(0.7, "white");
gradient.addColorStop(1, "pink");
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);
```
#### Result
{{ EmbedLiveSample('Adding_stops_to_a_gradient', 700, 180) }}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The interface defining this method: {{domxref("CanvasGradient")}}
- {{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
- {{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/ndefrecord/index.md | ---
title: NDEFRecord
slug: Web/API/NDEFRecord
page-type: web-api-interface
status:
- experimental
browser-compat: api.NDEFRecord
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`NDEFRecord`** interface of the [Web NFC API](/en-US/docs/Web/API/Web_NFC_API) provides data that can be read from, or written to, compatible NFC devices, e.g. NFC tags supporting NDEF.
## Constructor
- {{DOMxRef("NDEFRecord.NDEFRecord", "NDEFRecord()")}} {{Experimental_Inline}}
- : Returns a new `NDEFRecord`.
## Instance properties
- {{DOMxRef("NDEFRecord.recordType")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns the record type of the record. Records must have either a standardized well-known type name such as `"empty"`, `"text"`, `"url"`, `"smart-poster"`, `"absolute-url"`, `"mime"`, or `"unknown"` or else an external type name, which consists of a domain name and custom type name separated by a colon (":").
- {{DOMxRef("NDEFRecord.mediaType")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns the {{Glossary("MIME type")}} of the record. This value will be `null` if `recordType` is not equal to `"mime"`.
- {{DOMxRef("NDEFRecord.id")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns the record identifier, which is an absolute or relative URL used to identify the record.
> **Note:** The uniqueness of the identifier is enforced only by the generator of the record.
- {{DOMxRef("NDEFRecord.data")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns a {{jsxref("DataView")}} containing the raw bytes of the record's payload.
- {{DOMxRef("NDEFRecord.encoding")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns the encoding of a textual payload, or `null` otherwise.
- {{DOMxRef("NDEFRecord.lang")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns the language of a textual payload, or `null` if one was not supplied.
## Instance methods
- {{DOMxRef("NDEFRecord.toRecords", "NDEFRecord.toRecords()")}} {{Experimental_Inline}}
- : Converts {{DOMxRef("NDEFRecord.data")}} to a sequence of records. This allows parsing the payloads of record types which may contain nested records, such as smart poster and external type records.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefrecord | data/mdn-content/files/en-us/web/api/ndefrecord/data/index.md | ---
title: "NDEFRecord: data property"
short-title: data
slug: Web/API/NDEFRecord/data
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NDEFRecord.data
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`data`**
property of the {{DOMxRef("NDEFRecord")}} interface returns a
{{jsxref("DataView")}} containing the raw bytes of the record's payload.
## Syntax
```js-nolint
NDEFRecord.data
```
### Value
A {{jsxref("DataView")}} that contains encoded payload data of the record.
## Examples
The following example loops over the records in an {{domxref("NDEFMessage")}}
object, which is retrieved from {{domxref("NDEFReadingEvent.message")}}. After
selecting a record based on its {{domxref("NDEFRecord.mediaType",
"mediaType")}}, it then decodes what's stored in the `data` property.
```js
const ndef = new NDEFReader();
await ndef.scan();
ndef.onreading = (event) => {
const decoder = new TextDecoder();
for (const record of event.message.records) {
if (record.mediaType === "application/json") {
const json = JSON.parse(decoder.decode(record.data));
const article = /^[aeio]/i.test(json.title) ? "an" : "a";
console.log(`${json.name} is ${article} ${json.title}`);
}
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefrecord | data/mdn-content/files/en-us/web/api/ndefrecord/mediatype/index.md | ---
title: "NDEFRecord: mediaType property"
short-title: mediaType
slug: Web/API/NDEFRecord/mediaType
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NDEFRecord.mediaType
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`mediaType`**
property of the {{DOMxRef("NDEFRecord")}} interface returns the {{Glossary("MIME type")}} of the record. This value will be `null` if `recordType` is not equal to `"mime"`.
## Syntax
```js-nolint
NDEFRecord.mediaType
```
### Value
A string, containing the {{Glossary("MIME type")}} of the record
payload.
## Examples
The following example loops over the records in an {{domxref("NDEFMessage")}} object, which is retrieved from {{domxref("NDEFReadingEvent.message")}}. It then uses the `mediaType` property to determine which of the records to parse.
```js
const ndef = new NDEFReader();
await ndef.scan();
ndef.onreading = (event) => {
const decoder = new TextDecoder();
for (const record of event.message.records) {
if (record.mediaType === "application/json") {
const json = JSON.parse(decoder.decode(record.data));
const article = /^[aeio]/i.test(json.title) ? "an" : "a";
console.log(`${json.name} is ${article} ${json.title}`);
}
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefrecord | data/mdn-content/files/en-us/web/api/ndefrecord/recordtype/index.md | ---
title: "NDEFRecord: recordType property"
short-title: recordType
slug: Web/API/NDEFRecord/recordType
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NDEFRecord.recordType
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`recordType`**
property of the {{DOMxRef("NDEFRecord")}} interface returns the record type of the record.
## Syntax
```js-nolint
NDEFRecord.recordType
```
### Value
A string which can be one of the following:
- `"empty"`
- : An empty NDEF record.
- `"text"`
- : A text NDEF record.
- `"url"`
- : A URI NDEF record.
- `"smart-poster"`
- : A "smart poster" NDEF record.
- `"absolute-url"`
- : An absolute URL NDEF record.
- `"mime"`
- : A {{Glossary("MIME type")}} NDEF record.
- `"unknown"`
- : The NDEF record type is not known.
- local type name
- : Represents a local type name, frequently used to specify NDEF record embedded within
another record.
- external type name
- : A custom string consisting of a domain name and custom type name separated by a colon (":").
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefrecord | data/mdn-content/files/en-us/web/api/ndefrecord/lang/index.md | ---
title: "NDEFRecord: lang property"
short-title: lang
slug: Web/API/NDEFRecord/lang
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NDEFRecord.lang
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`lang`**
property of the {{DOMxRef("NDEFRecord")}} interface returns the language of
a textual payload, or `null` if one was not supplied.
The record might be missing a language tag, for example, if the recorded information is
not locale-specific.
## Syntax
```js-nolint
NDEFRecord.lang
```
### Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [HTML `lang` attribute](/en-US/docs/Web/HTML/Global_attributes/lang), that declares content language of the document or its elements
- HTTP headers that declare content language: {{HTTPHeader("Content-Language")}} and {{HTTPHEader("Accept-Language")}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefrecord | data/mdn-content/files/en-us/web/api/ndefrecord/encoding/index.md | ---
title: "NDEFRecord: encoding property"
short-title: encoding
slug: Web/API/NDEFRecord/encoding
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NDEFRecord.encoding
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`encoding`**
property of the {{DOMxRef("NDEFRecord")}} interface returns the encoding of
a textual payload, or `null` otherwise.
## Syntax
```js-nolint
NDEFRecord.encoding
```
### Value
A string which can be one of the following: `"utf-8"`,
`"utf-16"`, `"utf-16le"`, or `"utf-16be"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefrecord | data/mdn-content/files/en-us/web/api/ndefrecord/ndefrecord/index.md | ---
title: "NDEFRecord: NDEFRecord() constructor"
short-title: NDEFRecord()
slug: Web/API/NDEFRecord/NDEFRecord
page-type: web-api-constructor
status:
- experimental
browser-compat: api.NDEFRecord.NDEFRecord
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`NDEFRecord()`**
constructor of the [Web NFC API](/en-US/docs/Web/API/Web_NFC_API) returns a
newly constructed {{DOMxRef("NDEFRecord")}} object that represents data that can be
read from, or written to, compatible NFC devices; e.g. NFC tags supporting NDEF.
## Syntax
```js-nolint
new NDEFRecord(options)
```
### Parameters
- `options`
- : An object with the following properties:
- `data` {{optional_inline}}
- : Contains the data to be transmitted. It can be a string object or literal, an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}}, or an array of nested records.
- `encoding` {{optional_inline}}
- : A string specifying the record's encoding.
- `id` {{optional_inline}}
- : A developer-defined identifier for the record.
- `lang` {{optional_inline}}
- : A valid language tag according to {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}.
- `mediaType` {{optional_inline}}
- : A valid [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types).
- `recordType`
- : A string indicating the type of data stored in `data`. It must be one of the following values:
- `"absolute-url"`
An absolute URL to the data.
`"empty"`
- : An empty {{domxref("NDEFRecord")}}.
- `"mime"`
- : A valid [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types).
- `"smart-poster"`
- : A smart poster as defined by the [NDEF-SMARTPOSTER](https://w3c.github.io/web-nfc/#bib-ndef-smartposter) specification.
- `"text"`
- : Text as defined by the [NDEF-TEXT](https://w3c.github.io/web-nfc/#bib-ndef-text) specification.
- `"unknown"`
- : The record type is not known.
- `"URL"`
- : A URL as defined by the [NDEF-URI](https://w3c.github.io/web-nfc/#bib-ndef-uri) specification.
### Return value
A new {{DOMxRef("NDEFRecord")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefrecord | data/mdn-content/files/en-us/web/api/ndefrecord/torecords/index.md | ---
title: "NDEFRecord: toRecords() method"
short-title: toRecords()
slug: Web/API/NDEFRecord/toRecords
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.NDEFRecord.toRecords
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`toRecords()`**
method of the {{DOMxRef("NDEFRecord")}} interface converts
{{DOMxRef("NDEFRecord.data")}} to a sequence of records based on
{{DOMxRef("NDEFRecord.recordType")}}, and returns the result. This allows
parsing the payloads of record types which may contain nested records, such
as smart poster and external type records.
## Syntax
```js-nolint
toRecords()
```
### Parameters
None.
### Return value
A list of {{DOMxRef("NDEFRecord")}}s.
## Exceptions
- `NotSupported` {{domxref("DOMException")}}
- : Indicates that the {{Glossary("User Agent")}} does not know how to parse this combination of
{{DOMxRef("NDEFRecord.data")}} and {{DOMxRef("NDEFRecord.recordType")}}.
## Examples
Read an external record with an NDEF message as payload
The example uses external type records to create application-defined records.
These records may contain an {{domxref("NDEFMessage")}} as payload, with its own
{{domxref("NDEFRecord")}} objects, including local types that are used in the
context of the application. Notice that the smart poster record type also
contains an NDEF message as payload.
Because NDEF gives no guarantee on the ordering of records, using an external
type record with an NDEF message as payload can be useful for encapsulating
related data.
This example shows how to read an external record for social posts, which
contains an {{domxref("NDEFMessage")}}, containing a text record and a record
with the local type "act" (action), with a definition borrowed from smart
poster, but used in local application context.
```js
const ndefReader = new NDEFReader();
await ndefReader.scan();
ndefReader.onreading = (event) => {
const externalRecord = event.message.records.find(
(record) => record.type === "example.com:smart-poster",
);
let action, text;
for (const record of externalRecord.toRecords()) {
if (record.recordType === "text") {
const decoder = new TextDecoder(record.encoding);
text = decoder.decode(record.data);
} else if (record.recordType === ":act") {
action = record.data.getUint8(0);
}
}
switch (action) {
case 0: // do the action
console.log(`Post "${text}" to timeline`);
break;
case 1: // save for later
console.log(`Save "${text}" as a draft`);
break;
case 2: // open for editing
console.log(`Show editable post with "${text}"`);
break;
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefrecord | data/mdn-content/files/en-us/web/api/ndefrecord/id/index.md | ---
title: "NDEFRecord: id property"
short-title: id
slug: Web/API/NDEFRecord/id
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NDEFRecord.id
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`id`** property of the
{{DOMxRef("NDEFRecord")}} interface returns the record identifier, which is an
absolute or relative URL used to identify the record.
This identifier is created by the generator of the record which is solely responsible
for enforcing record identifier uniqueness. Web NFC does not sign the NFC content, thus
record consumer should not make any assumptions about integrity or authenticity of the
identifier or any other part of the records.
## Syntax
```js-nolint
NDEFRecord.id
```
### Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/ext_srgb/index.md | ---
title: EXT_sRGB extension
short-title: EXT_sRGB
slug: Web/API/EXT_sRGB
page-type: webgl-extension
browser-compat: api.EXT_sRGB
---
{{APIRef("WebGL")}}
The **`EXT_sRGB`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and adds sRGB support to textures and framebuffer objects.
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 only available to {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} contexts. In {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}}, the functionality of this extension is available on the WebGL2 context by default. The constants in WebGL2 are: `gl.SRGB`, `gl.SRGB8`, `gl.SRGB8_ALPHA8` and `gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING`.
## Constants
This extension exposes the following constants, which can be used in the {{domxref("WebGLRenderingContext.texImage2D()", "texImage2D()")}}, {{domxref("WebGLRenderingContext.texSubImage2D()", "texSubImage2D()")}}, {{domxref("WebGLRenderingContext.renderbufferStorage()", "renderbufferStorage()")}} and {{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()", "getFramebufferAttachmentParameter()")}} methods.
- `ext.SRGB_EXT`
- : Unsized sRGB format that leaves the precision up to the driver.
- `ext.SRGB_ALPHA_EXT`
- : Unsized sRGB format with unsized alpha component.
- `ext.SRGB8_ALPHA8_EXT`
- : Sized (8-bit) sRGB and alpha formats.
- `ext.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT`
- : Returns the framebuffer color encoding (`gl.LINEAR` or `ext.SRGB_EXT`).
## Examples
```js
const ext = gl.getExtension("EXT_sRGB");
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
ext.SRGB_EXT,
512,
512,
0,
ext.SRGB_EXT,
gl.UNSIGNED_BYTE,
image,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.getExtension()")}}
- {{domxref("WebGLRenderingContext.texImage2D()")}}
- {{domxref("WebGLRenderingContext.texSubImage2D()")}}
- {{domxref("WebGLRenderingContext.renderbufferStorage()")}}
- {{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer/index.md | ---
title: RTCRtpScriptTransformer
slug: Web/API/RTCRtpScriptTransformer
page-type: web-api-interface
browser-compat: api.RTCRtpScriptTransformer
---
{{APIRef("WebRTC")}}
The **`RTCRtpScriptTransformer`** interface of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) provides a worker-side [Stream API](/en-US/docs/Web/API/Streams_API) interface that a [WebRTC Encoded Transform](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms) can use to modify encoded media frames in the incoming and outgoing WebRTC pipelines.
> **Note:** This feature is available in [_Dedicated_ Web Workers](/en-US/docs/Web/API/Web_Workers_API#worker_types).
## Instance properties
- {{domxref("RTCRtpScriptTransformer.readable")}} {{ReadOnlyInline}}
- : A {{domxref("ReadableStream")}} on which encoded frames from the WebRTC sender or receiver pipelines may be enqueued.
- {{domxref("RTCRtpScriptTransformer.writable")}} {{ReadOnlyInline}}
- : A {{domxref("WritableStream")}} that encoded frames should be piped to.
- {{domxref("RTCRtpScriptTransformer.options")}} {{ReadOnlyInline}}
- : Options passed from the [`RTCRtpScriptTransform` constructor](/en-US/docs/Web/API/RTCRtpScriptTransform/RTCRtpScriptTransform), which are used to configure transform code based on whether incoming or outgoing frames are being processed.
## Instance methods
- {{domxref("RTCRtpScriptTransformer.generateKeyFrame()")}}
- : Requests a video encoder generate a key frame. May be called by a transformer in the sender pipeline when processing outgoing frames.
- {{domxref("RTCRtpScriptTransformer.sendKeyFrameRequest()")}}
- : Requests the sender send a key frame. May be called by a transformer in the receiver pipeline when processing incoming encoded video frames.
## Description
A `RTCRtpScriptTransformer` instance is created as part of construction of an associated {{DOMxRef("RTCRtpScriptTransform")}}, which specifies the worker in which the transformer is created and options that will be passed to it.
The transformer is made available to a worker through the {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event `transformer` property.
This event is fired on construction of the associated {{DOMxRef("RTCRtpScriptTransform")}} and when an encoded frame is enqueued on the {{domxref("RTCRtpScriptTransformer.readable")}} from a codec (outgoing) or from the packetizer (incoming).
The transformer exposes a {{domxref("RTCRtpScriptTransformer.readable","readable")}} and {{domxref("RTCRtpScriptTransformer.writable","writable")}} stream into the worker, along with an {{domxref("RTCRtpScriptTransformer.options", "options")}} object provided to the {{DOMxRef("RTCRtpScriptTransform")}} on construction.
When the associated `RTCRtpScriptTransform` is assigned to a {{DOMxRef("RTCRtpSender")}} or {{DOMxRef("RTCRtpReceiver")}}, encoded media frames from the WebRTC sender or receiver pipelines are enqueued on the `readable` stream.
A WebRTC Encoded Transform must read encoded frames from `transformer.readable`, modify them as needed, and write them to `transformer.writable` in the same order, and without any duplication.
The {{domxref("RTCRtpScriptTransformer.options","transformer.options")}} allow an appropriate transform function to be used, based on whether the encoded media frames are incoming or outgoing.
The transform is usually implemented by piping frames from the `readable` through one or more {{DOMxRef("TransformStream")}} instances to the `writable`, transforming them as needed.
The interface also provides methods for a sender to generate get a video encoder to generate a new keyframe, or for a receiver to request a new key frame from the sender's encoder (video encoders commonly send a key frame containing the full information needed to construct an image, and subsequently send delta frames containing just the information that has changed since the previous frame).
These methods are required in cases where a recipient would be unable to decode incoming frames until they receive a new key frame.
For example, a new recipient joining a conference call will not be able see video until they have received a new key frame, since delta frames can only be decoded if you have the last key frame and all subsequent delta frames.
Similarly, if frames are encrypted for a recipient, they will only be able to decode frames once they have received their first encrypted key frame.
## Examples
This example shows the code for a WebRTC Encoded Transform running in a worker.
The code uses `addEventListener()` to register a handler function for the {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event, which makes the **`RTCRtpScriptTransformer`** available as `event.transformer`.
The handler creates a {{DOMxRef("TransformStream")}} and pipes frames from the `event.transformer.readable` through it to `event.transformer.writable`.
The transform stream `transform()` implementation is called for each encoded frame queued on the stream: it can read the data from the frame and in this case negates the bytes and then enqueues the modifiable frame on the stream.
```js
addEventListener("rtctransform", (event) => {
const transform = new TransformStream({
start() {}, // Called on startup.
flush() {}, // Called when the stream is about to be closed.
async transform(encodedFrame, controller) {
// Reconstruct the original frame.
const view = new DataView(encodedFrame.data);
// Construct a new buffer
const newData = new ArrayBuffer(encodedFrame.data.byteLength);
const newView = new DataView(newData);
// Negate all bits in the incoming frame
for (let i = 0; i < encodedFrame.data.byteLength; ++i) {
newView.setInt8(i, ~view.getInt8(i));
}
encodedFrame.data = newData;
controller.enqueue(encodedFrame);
},
});
event.transformer.readable
.pipeThrough(transform)
.pipeTo(event.transformer.writable);
});
```
The only special things to note about the {{DOMxRef("TransformStream")}} above are that it queues encoded media frames ({{domxref("RTCEncodedVideoFrame")}} or {{domxref("RTCEncodedAudioFrame")}}) rather than arbitrary "chunks", and that `writableStrategy` and `readableStrategy` properties are not defined (because the queuing strategy is entirely managed by the user agent).
A transform can run in either the incoming or outgoing WebRTC pipelines.
This doesn't matter in the code above, because the same algorithm might be used in the sender to negate the frames, and in the receiver to revert them.
If the sender and receiver pipelines need to apply a different transform algorithm then information about the current pipeline must be passed from the main thread.
This is done by setting an `options` argument in the corresponding [`RTCRtpScriptTransform` constructor](/en-US/docs/Web/API/RTCRtpScriptTransform/RTCRtpScriptTransform#options), which is then made available to the worker in {{domxref("RTCRtpScriptTransformer.options")}}.
Below we use the `transformer.options` to choose either a sender transform or a receiver transform.
Note that the properties of the object are arbitrary (provided the values can be serialized) and it is also possible to transfer a {{domxref("MessageChannel")}} and use it to [communicate with a transform at runtime](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms#runtime_communication_with_the_transform) in order to, for example, share encryption keys.
```js
// Code to instantiate transform and attach them to sender/receiver pipelines.
onrtctransform = (event) => {
let transform;
if (event.transformer.options.name == "senderTransform")
transform = createSenderTransform();
// returns a TransformStream (not shown)
else if (event.transformer.options.name == "receiverTransform")
transform = createReceiverTransform();
// returns a TransformStream (not shown)
else return;
event.transformer.readable
.pipeThrough(transform)
.pipeTo(event.transformer.writable);
};
```
Note that the above code is part of more complete examples provided in [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms)
- {{domxref("TransformStream")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer | data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer/generatekeyframe/index.md | ---
title: "RTCRtpScriptTransformer: generateKeyFrame()"
short-title: generateKeyFrame()
slug: Web/API/RTCRtpScriptTransformer/generateKeyFrame
page-type: web-api-instance-method
browser-compat: api.RTCRtpScriptTransformer.generateKeyFrame
---
{{APIRef("WebRTC")}}
The **`generateKeyFrame()`** method of the {{domxref("RTCRtpScriptTransformer")}} interface causes a video encoder to generate a key frame.
## Syntax
```js-nolint
generateKeyFrame()
generateKeyFrame(rid)
```
### Parameters
- `rid` {{optional_inline}}
- : A string containing the "restriction identifier" ("RID") of the stream/encoder that must generate the new key frame.
The value must have between 1 and 255 characters (inclusive), and contain only the alphanumeric characters, underscore, and hyphen (`A-Z`, `a-z`, `0-9`, `-`, `_`).
RIDs are case sensitive and must be unique for the peer communication channel.
<!-- RFC8851 allows '-' and '_' and unlimited length. RFC 8852 disagrees (https://www.rfc-editor.org/errata/eid7132) -->
The first encoder that matches the specified `rid` is used.
If no encoder matches the `rid` then the first encoder is used, and `rid` is set to the encoder's restrictions.
### Return value
A {{jsxref("Promise")}} that fulfills with the timestamp of the frame, or rejects with an exception value.
### Exceptions
- `InvalidStateError`
- : The encoder is not processing video frames, or is `undefined`.
- `TypeError`
- : The provided `rid` but does not conform to the grammar requirements.
- `NotFoundError`
- : There are no video encoders. This might be raised if the corresponding `RTCRtpSender` is not active or its track is ended.
## Description
This method can be called by a transformer that is processing outgoing encoded video frames to force a new complete (key) frame to be sent.
It might be needed by a [WebRTC Encoded Transform](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms) that encrypts frames, to ensure that if a new encryption key is added, a key frame encrypted with that key is sent as soon as possible.
The sender can specify a RID (also referred to as a "restriction identifier" or "RTP stream ID") to control what codec generates the new key frame.
A stream might contain (simulcast) multiple versions of the same source, each with different properties such as resolution and frame rate.
The RID is used to indicate a specific RTP stream, and hence the encoder that needs to generate a new frame.
Note that the available RID values are set when the transceiver used by the connection is created.
The RID values being used can be queried by calling {{domxref("RTCRtpSender.getParameters()")}} and inspecting the [`encodings`](/en-US/docs/Web/API/RTCRtpSender/getParameters#encodings) property of the returned value.
The promise returned by the method will resolve just before enqueuing the corresponding key frame in a `RTCRtpScriptTransformer` readable.
> **Note:** Sending multiple streams (RID) at a time is called "simulcast".
> This feature provides a [middlebox](https://en.wikipedia.org/wiki/Middlebox) with the same stream in multiple levels of video quality, allowing it to manage bandwidth by selectively transmitting appropriate levels to participants and switch resolution rapidly on the fly (i.e. switching to forward low-quality video for everyone except the active speaker).
> The recipient only ever gets one stream, which is why the comparable receiver method {{domxref("RTCRtpScriptTransformer.sendKeyFrameRequest()")}} does not require that an RID is specified.
## Examples
### Sending a key frame
The example below shows how the main thread might pass an encryption key to a sender transform, and trigger the codec to generate a key frame.
Note that the main thread doesn't have direct access to the {{domxref("RTCRtpScriptTransformer")}} object, so it needs to pass the key and RID to the worker.
Here we do that with a `MessageChannel`, transferring the second port to the transformer code running in the worker.
The code assumes there is already a peer connection, and `videoSender` is an {{domxref("RTCRtpSender")}}.
```js
const worker = new Worker("worker.js");
const channel = new MessageChannel();
videoSender.transform = new RTCRtpScriptTransform(
worker,
{ name: "senderTransform", port: channel.port2 },
[channel.port2],
);
// Post RID and new key to the sender
channel.port1.start();
channel.port1.postMessage({
rid: "1",
key: "93ae0927a4f8e527f1gce6d10bc6ab6c",
});
```
The {{domxref("DedicatedWorkerGlobalScope/rtctransform_event", "rtctransform")}} event handler in the worker gets the port and uses it to listen for `message` events.
If an event is received it gets the `rid` and `key`, and then calls `generateKeyFrame()`.
```js
event.transformer.options.port.onmessage = (event) => {
const { rid, key } = event.data;
// key is used by the transformer to encrypt frames (not shown)
// Get codec to generate a new key frame using the rid
// Here 'rcevent' is the rtctransform event.
rcevent.transformer.generateKeyFrame(rid);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms)
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer | data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer/readable/index.md | ---
title: "RTCRtpScriptTransformer: readable property"
short-title: readable
slug: Web/API/RTCRtpScriptTransformer/readable
page-type: web-api-instance-property
browser-compat: api.RTCRtpScriptTransformer.readable
---
{{APIRef("WebRTC")}}
The **`readable`** read-only property of the {{domxref("RTCRtpScriptTransformer")}} interface returns a {{domxref("ReadableStream")}} instance is a source for encoded media frames.
When the corresponding {{domxref("RTCRtpScriptTransform")}} is inserted into the WebRTC sender and receiver pipelines, this stream may be enqueued with outgoing or incoming encoded media frames ({{domxref("RTCEncodedVideoFrame")}} or {{domxref("RTCEncodedAudioFrame")}}).
A WebRTC encoded transform can read the frames, modify them as needed, and then send them back into the WebRTC pipeline by writing them to {{domxref("RTCRtpScriptTransformer.writable")}}.
A common way to perform this operation is to pipe the frames through a {{domxref("TransformStream")}}.
## Value
A {{domxref("ReadableStream")}}.
## Examples
The following example shows how `readable` is piped through a {{domxref("TransformStream")}} to {{domxref("RTCRtpScriptTransformer.writable")}}.
```js
addEventListener("rtctransform", (event) => {
let transform;
// Select a transform based on passed options
if (event.transformer.options.name == "senderTransform")
transform = createSenderTransform(); // A TransformStream
else if (event.transformer.options.name == "receiverTransform")
transform = createReceiverTransform(); // A TransformStream
else return;
// Pipe frames from the readable to writeable through TransformStream
event.transformer.readable
.pipeThrough(transform)
.pipeTo(event.transformer.writable);
});
```
The code implements a handler for the {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event, which is fired at the global worker object on construction of the corresponding {{domxref("RTCRtpScriptTransform")}}, and when new frames are enqueued for processing.
`event.transformer` is the {{domxref("RTCRtpScriptTransformer")}} that has a `readable` and `writable` property.
An different {{domxref("TransformStream")}} is created to process outgoing and incoming frames, using `createSenderTransform()` or `createReceiverTransform()`, respectively (implementations not shown).
The event handler chooses the correct transform stream to use based on options passed through from the [`RTCRtpScriptTransform` constructor](/en-US/docs/Web/API/RTCRtpScriptTransform/RTCRtpScriptTransform) and assigns it to `transform`.
The code calls {{domxref("ReadableStream.pipeThrough()")}} on the `readable` to pipe encoded frames through the selected `TransformStream`, and then {{domxref("ReadableStream.pipeTo()")}} to pipe them to the {{domxref("RTCRtpScriptTransformer.writable")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms)
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer | data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer/sendkeyframerequest/index.md | ---
title: "RTCRtpScriptTransformer: sendKeyFrameRequest()"
short-title: sendKeyFrameRequest()
slug: Web/API/RTCRtpScriptTransformer/sendKeyFrameRequest
page-type: web-api-instance-method
browser-compat: api.RTCRtpScriptTransformer.sendKeyFrameRequest
---
{{APIRef("WebRTC")}}
The **`sendKeyFrameRequest()`** method of the {{domxref("RTCRtpScriptTransformer")}} interface may be called by a [WebRTC Encoded Transform](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms) that is processing incoming encoded video frames, in order to request a key frame from the sender.
The method may only be called when receiving _video_ (not audio) frames and if, for whatever reason, a recipient will not be able to decode the video without a new key frame.
Note that the user agent can decide that the request for a key frame is not necessary, in which case the returned promise will fulfill even though the request was not actually sent.
> **Note:** It might be called, for example, if a new user joins a WebRTC conference, in order to reduce the time before they receive a key frame and can hence start displaying video.
> For more information see [Triggering a key frame](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms#triggering_a_key_frame) in Using WebRTC Encoded Transforms.
## Syntax
```js-nolint
sendKeyFrameRequest()
```
### Parameters
None
### Return value
A {{jsxref("Promise")}} that fulfills with `undefined` once the request is sent, or the user agent decides that it does not need to.
### Exceptions
- `InvalidStateError`
- : The de-packetizer is not processing video packets, or is `undefined`.
## Examples
The example below shows how the main thread of a WebRTC application that is receiving encoded video might pass a decryption key to a receiver transform, and request the sender emit a key frame.
Note that the main thread doesn't have direct access to the {{domxref("RTCRtpScriptTransformer")}} object, so it needs to pass the key to the worker.
Here we do that with a `MessageChannel`, transferring the second port to the transformer code running in the worker.
The code assumes there is already a peer connection, and `videoReceiver` is an {{domxref("RTCRtpReceiver")}}.
```js
const worker = new Worker("worker.js");
const channel = new MessageChannel();
videoReceiver.transform = new RTCRtpScriptTransform(
worker,
{ name: "receiverTransform", port: channel.port2 },
[channel.port2],
);
// Post new key to the receiver
channel.port1.start();
channel.port1.postMessage({
key: "93ae0927a4f8e527f1gce6d10bc6ab6c",
});
```
The {{domxref("DedicatedWorkerGlobalScope/rtctransform_event", "rtctransform")}} event handler in the worker gets the port as `event.transformer.options.port`.
The code snippet below shows how that is used to listen for `message` events on the channel.
If an event is received the handler gets the `key`, and then calls `sendKeyFrameRequest()` on the transformer.
```js
event.transformer.options.port.onmessage = (event) => {
const { key } = event.data;
// key is used by the transformer to decrypt frames (not shown)
// Request sender to emit a key frame.
// Here 'rcevent' is the rtctransform event.
rcevent.transformer.sendKeyFrameRequest();
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms)
- {{DOMxRef("RTCRtpScriptTransformer")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer | data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer/writable/index.md | ---
title: "RTCRtpScriptTransformer: writable property"
short-title: writable
slug: Web/API/RTCRtpScriptTransformer/writable
page-type: web-api-instance-property
browser-compat: api.RTCRtpScriptTransformer.writable
---
{{APIRef("WebRTC")}}
The **`writable`** read-only property of the {{domxref("RTCRtpScriptTransformer")}} interface returns a {{domxref("WritableStream")}} instance that can be used as a sink for encoded media frames enqueued on the corresponding {{domxref("RTCRtpScriptTransformer.readable")}}.
When the corresponding {{domxref("RTCRtpScriptTransform")}} is inserted into the WebRTC sender and receiver pipelines, encoded media frames ({{domxref("RTCEncodedVideoFrame")}} or {{domxref("RTCEncodedAudioFrame")}}) may be enqueued on the {{domxref("RTCRtpScriptTransformer.readable")}}.
A WebRTC encoded transform can read the frames from `readable`, modify them as needed, and then send them back into the WebRTC pipeline by sending them to this `writable`.
A common way to perform this operation is to pipe the frames through a {{domxref("TransformStream")}}.
## Value
A {{domxref("WritableStream")}}.
## Examples
The following example shows how {{domxref("RTCRtpScriptTransformer.readable")}} is piped through a {{domxref("TransformStream")}} to {{domxref("RTCRtpScriptTransformer.writable")}}.
```js
addEventListener("rtctransform", (event) => {
let transform;
// Select a transform based on passed options
if (event.transformer.options.name == "senderTransform")
transform = createSenderTransform(); // A TransformStream
else if (event.transformer.options.name == "receiverTransform")
transform = createReceiverTransform(); // A TransformStream
else return;
// Pipe frames from the readable to writeable through TransformStream
event.transformer.readable
.pipeThrough(transform)
.pipeTo(event.transformer.writable);
});
```
The code implements a handler for the {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event, which is fired at the global worker object on construction of the corresponding {{domxref("RTCRtpScriptTransform")}}, and when new frames are enqueued for processing.
`event.transformer` is the {{domxref("RTCRtpScriptTransformer")}} that has the `writable` and `readable` properties.
An different {{domxref("TransformStream")}} is created to process outgoing and incoming frames, using `createSenderTransform()` or `createReceiverTransform()`, respectively (implementations not shown).
The event handler chooses the correct transform stream to use based on options passed through from the [`RTCRtpScriptTransform` constructor](/en-US/docs/Web/API/RTCRtpScriptTransform/RTCRtpScriptTransform) and assigns it to `transform`.
The code calls {{domxref("ReadableStream.pipeThrough()")}} on the `readable` to pipe encoded frames through the selected `TransformStream`, and then {{domxref("ReadableStream.pipeTo()")}} to pipe them to the {{domxref("RTCRtpScriptTransformer.writable")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer | data/mdn-content/files/en-us/web/api/rtcrtpscripttransformer/options/index.md | ---
title: "RTCRtpScriptTransformer: options property"
short-title: options
slug: Web/API/RTCRtpScriptTransformer/options
page-type: web-api-instance-property
browser-compat: api.RTCRtpScriptTransformer.options
---
{{APIRef("WebRTC")}}
The **`options`** read-only property of the {{domxref("RTCRtpScriptTransformer")}} interface returns the object that was (optionally) passed as the second argument [during construction](/en-US/docs/Web/API/RTCRtpScriptTransform/RTCRtpScriptTransform) of the corresponding {{domxref("RTCRtpScriptTransform")}}.
## Value
An object.
## Description
The simplest use of options is for the main thread to indicate whether the corresponding {{domxref("RTCRtpScriptTransform")}} is to be added to the WebRTC sender or receiver pipeline. This is important if the same worker is used for processing both incoming and outgoing encoded frames, as it allows code to determine what transform should be applied to the frames.
Options can also be used to send/transfer the second port of a [message channel](/en-US/docs/Web/API/Channel_Messaging_API) to the worker-side transform.
This channel can then be used to send dynamic information to a transform stream, such as when encryption keys are changed or added.
Note that you might also send messages to the transform using {{domxref("Worker.postMessage()")}}, but you would then have to appropriately redirect the messages if the worker is used in different contexts (while a message port option provides a direct channel for a specific transform).
## Examples
### How to indicate the current WebRTC pipeline
{{domxref("RTCRtpScriptTransform")}} is constructed with a particular {{domxref("Worker")}} and options, and then inserted into either the WebRTC outgoing or incoming pipeline by assigning it to {{domxref("RTCRtpSender.transform")}} or {{domxref("RTCRtpReceiver.transform")}}, respectively.
If the same worker is used in the transforms for the incoming and outgoing pipeline, then you need to supply options in the constructor to indicate whether encoded frames to be transformed are incoming or outgoing.
The example below shows how this might be done for a `RTCRtpScriptTransform` added to the sender pipeline after adding a track to the peer connection ({{domxref("RTCPeerConnection")}}), and then adding another transform to the receiver pipeline when a track is received.
```js
// videoSender is an RTCRtpSender.
const videoSender = peerConnection.addTrack(track, mediaStream);
videoSender.transform = new RTCRtpScriptTransform(worker, {
name: "senderTransform",
});
```
```js
peerConnection.ontrack = (event) => {
// event.receiver is an RTCRtpReceiver
event.receiver.transform = new RTCRtpScriptTransform(worker, {
someOption: "receiverTransform",
});
};
```
In each case above we supply an object with a different value for the option object's `name` property, which indicates the pipeline that the transform was added to.
Note that the names and values of properties in `options` is arbitrary: what matters is that the main thread and worker thread both know what properties and values are used.
The following code how the passed options are used in the worker.
First we implement a handler for the {{domxref("DedicatedWorkerGlobalScope.rtctransform_event", "rtctransform")}} event, which is fired at the global worker object on construction of the corresponding {{domxref("RTCRtpScriptTransform")}}, and when new frames are enqueued for processing.
`event.transformer` is a {{domxref("RTCRtpScriptTransformer")}} that has a `readable`, `writable`, and `options` property.
```js
addEventListener("rtctransform", (event) => {
let transform;
// Select a transform based on passed options
if (event.transformer.options.name == "senderTransform")
transform = createSenderTransform(); // A TransformStream
else if (event.transformer.options.name == "receiverTransform")
transform = createReceiverTransform(); // A TransformStream
else return;
// Pipe frames from the readable to writeable through TransformStream
event.transformer.readable
.pipeThrough(transform)
.pipeTo(event.transformer.writable);
});
```
The code creates a different {{domxref("TransformStream")}} to process outgoing and incoming frames, using `createSenderTransform()` or `createReceiverTransform()`, based on the passed options (it then pipes frames from the `readable`, through the selected `TransformStream`, to the `writable`).
### Passing a message port to a transform
This example shows how to create a [message channel](/en-US/docs/Web/API/Channel_Messaging_API) and transfer one of its ports to the WebRTC encoded transform running in the worker. This main thread can then send and transfer objects and messages to the transformer running in the worker after construction, and vice versa.
The code below first creates a {{domxref("MessageChannel")}} and then constructs a `RTCRtpScriptTransform` passing the {{domxref("MessageChannel.port2","port2")}} value as an property in the options argument.
The port is also included in the array passed as the third constructor argument, so that it is transferred into the worker context.
```js
const channel = new MessageChannel();
const transform = new RTCRtpScriptTransform(
worker,
{ purpose: "encrypter", port: channel.port2 },
[channel.port2],
);
```
The worker can then get the port from the `rtctransform` event fired at the global worker object.
```js
let messagePort;
addEventListener("rtctransform", (event) => {
messagePort = event.transformer.options.port;
// ... other transformer code
});
```
Code in each end of the channel can send and transfer objects to the other end using {{domxref("MessagePort.postMessage()")}}, and listen for incoming messages using its {{domxref("MessagePort/message_event", "message")}} event.
For example, assuming we had an encryption key in a {{jsxref("Uint8Array")}} typed array named `encryptionKey`, we could transfer it from the main thread to the worker as shown:
```js
const encryptionKeyBuffer = encryptionKey.buffer;
channel.port1.postMessage(encryptionKeyBuffer, [encryptionKeyBuffer]);
```
The worker would listen for the `message` event to get the key:
```js
messagePort.addEventListener("message", (event) => {
const encryptionKeyBuffer = event.data;
// ... Use the encryptionKeyBuffer for encryption or any other purpose
};
```
See [message channel](/en-US/docs/Web/API/Channel_Messaging_API) for more information and examples.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/speechrecognitionalternative/index.md | ---
title: SpeechRecognitionAlternative
slug: Web/API/SpeechRecognitionAlternative
page-type: web-api-interface
browser-compat: api.SpeechRecognitionAlternative
---
{{APIRef("Web Speech API")}}
The **`SpeechRecognitionAlternative`** interface of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) represents a single word that has been recognized by the speech recognition service.
## Instance properties
- {{domxref("SpeechRecognitionAlternative.transcript")}} {{ReadOnlyInline}}
- : Returns a string containing the transcript of the recognized word.
- {{domxref("SpeechRecognitionAlternative.confidence")}} {{ReadOnlyInline}}
- : Returns a numeric estimate between 0 and 1 of how confident the speech recognition system is that the recognition is correct.
## Examples
This code is excerpted from our
[Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example.
```js
recognition.onresult = (event) => {
// The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
// The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
// It has a getter so it can be accessed like an array
// The first [0] returns the SpeechRecognitionResult at position 0.
// Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
// that contain individual results.
// These also have getters so they can be accessed like arrays.
// The second [0] returns the SpeechRecognitionAlternative at position 0.
// We then return the transcript property of the SpeechRecognitionAlternative object
const color = event.results[0][0].transcript;
diagnostic.textContent = `Result received: ${color}.`;
bg.style.backgroundColor = color;
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
| 0 |
data/mdn-content/files/en-us/web/api/speechrecognitionalternative | data/mdn-content/files/en-us/web/api/speechrecognitionalternative/transcript/index.md | ---
title: "SpeechRecognitionAlternative: transcript property"
short-title: transcript
slug: Web/API/SpeechRecognitionAlternative/transcript
page-type: web-api-instance-property
browser-compat: api.SpeechRecognitionAlternative.transcript
---
{{APIRef("Web Speech API")}}
The **`transcript`** read-only property of the
{{domxref("SpeechRecognitionResult")}} interface returns a string containing the
transcript of the recognized word(s).
For continuous recognition, leading or trailing whitespace will be included where
necessary so that concatenation of consecutive {{domxref("SpeechRecognitionResult")}}s
produces a proper transcript of the session.
## Value
A string.
## Examples
This code is excerpted from our
[Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example.
```js
recognition.onresult = (event) => {
// The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
// The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
// It has a getter so it can be accessed like an array
// The first [0] returns the SpeechRecognitionResult at position 0.
// Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
// that contain individual results.
// These also have getters so they can be accessed like arrays.
// The second [0] returns the SpeechRecognitionAlternative at position 0.
// We then return the transcript property of the SpeechRecognitionAlternative object
const color = event.results[0][0].transcript;
diagnostic.textContent = `Result received: ${color}.`;
bg.style.backgroundColor = color;
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
| 0 |
data/mdn-content/files/en-us/web/api/speechrecognitionalternative | data/mdn-content/files/en-us/web/api/speechrecognitionalternative/confidence/index.md | ---
title: "SpeechRecognitionAlternative: confidence property"
short-title: confidence
slug: Web/API/SpeechRecognitionAlternative/confidence
page-type: web-api-instance-property
browser-compat: api.SpeechRecognitionAlternative.confidence
---
{{APIRef("Web Speech API")}}
The **`confidence`** read-only property of the
{{domxref("SpeechRecognitionResult")}} interface returns a numeric estimate of how
confident the speech recognition system is that the recognition is correct.
> **Note:** Mozilla's implementation of `confidence` is still
> being worked on — at the moment, it always seems to return 1.
## Value
A number between 0 and 1.
## Examples
This code is excerpted from our
[Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example.
```js
recognition.onresult = (event) => {
// The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
// The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
// It has a getter so it can be accessed like an array
// The first [0] returns the SpeechRecognitionResult at position 0.
// Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
// that contain individual results.
// These also have getters so they can be accessed like arrays.
// The second [0] returns the SpeechRecognitionAlternative at position 0.
// We then return the transcript property of the SpeechRecognitionAlternative object
const color = event.results[0][0].transcript;
diagnostic.textContent = `Result received: ${color}.`;
bg.style.backgroundColor = color;
console.log(`Confidence: ${event.results[0][0].confidence}`);
};
```
## 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/document_object_model/index.md | ---
title: Document Object Model (DOM)
slug: Web/API/Document_Object_Model
page-type: web-api-overview
spec-urls: https://dom.spec.whatwg.org/
---
{{DefaultAPISidebar("DOM")}}
The **Document Object Model** (**DOM**) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory. Usually it refers to JavaScript, even though modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript language.
The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content.
Nodes can also have event handlers attached to them. Once an event is triggered, the event handlers get executed.
To learn more about what the DOM is and how it represents documents, see our article [Introduction to the DOM](/en-US/docs/Web/API/Document_Object_Model/Introduction).
## DOM interfaces
- {{DOMxRef("AbortController")}}
- {{DOMxRef("AbortSignal")}}
- {{DOMxRef("AbstractRange")}}
- {{DOMxRef("Attr")}}
- {{DOMxRef("CDATASection")}}
- {{DOMxRef("CharacterData")}}
- {{DOMxRef("Comment")}}
- {{DOMxRef("CustomEvent")}}
- {{DOMxRef("Document")}}
- {{DOMxRef("DocumentFragment")}}
- {{DOMxRef("DocumentType")}}
- {{DOMxRef("DOMError")}} {{Deprecated_Inline}}
- {{DOMxRef("DOMException")}}
- {{DOMxRef("DOMImplementation")}}
- {{DOMxRef("DOMParser")}}
- {{DOMxRef("DOMPoint")}}
- {{DOMxRef("DOMPointReadOnly")}}
- {{DOMxRef("DOMRect")}}
- {{DOMxRef("DOMTokenList")}}
- {{DOMxRef("Element")}}
- {{DOMxRef("Event")}}
- {{DOMxRef("EventTarget")}}
- {{DOMxRef("HTMLCollection")}}
- {{DOMxRef("MutationObserver")}}
- {{DOMxRef("MutationRecord")}}
- {{DOMxRef("NamedNodeMap")}}
- {{DOMxRef("Node")}}
- {{DOMxRef("NodeIterator")}}
- {{DOMxRef("NodeList")}}
- {{DOMxRef("ProcessingInstruction")}}
- {{DOMxRef("Range")}}
- {{DOMxRef("StaticRange")}}
- {{DOMxRef("Text")}}
- {{DOMxRef("TextDecoder")}}
- {{DOMxRef("TextEncoder")}}
- {{DOMxRef("TimeRanges")}}
- {{DOMxRef("TreeWalker")}}
- {{DOMxRef("XMLDocument")}}
### Obsolete DOM interfaces
The Document Object Model has been highly simplified. To achieve this, the following interfaces in the different DOM level 3 or earlier specifications have been removed. They are no longer available to web developers.
- `DOMConfiguration`
- `DOMErrorHandler`
- `DOMImplementationList`
- `DOMImplementationRegistry`
- `DOMImplementationSource`
- `DOMLocator`
- `DOMObject`
- `DOMSettableTokenList`
- `DOMUserData`
- `ElementTraversal`
- `Entity`
- `EntityReference`
- `NameList`
- `Notation`
- `TypeInfo`
- `UserDataHandler`
## HTML DOM
A document containing HTML is described using the {{DOMxRef("Document")}} interface, which is extended by the HTML specification to include various HTML-specific features. In particular, the {{domxref("Element")}} interface is enhanced to become {{domxref("HTMLElement")}} and various subclasses, each representing one of (or a family of closely related) elements.
The HTML DOM API provides access to various browser features such as tabs and windows, CSS styles and stylesheets, browser history, etc. These interfaces are discussed further in the [HTML DOM API](/en-US/docs/Web/API/HTML_DOM_API) documentation.
## SVG DOM
Similarly, a document containing SVG is also described using the {{DOMxRef("Document")}} interface, which is extended by the SVG specification to include various SVG-specific features. In particular, the {{domxref("Element")}} interface is enhanced to become {{domxref("SVGElement")}} and various subclasses, each representing an element or a family of closely related elements. These interfaces are discussed further in the [SVG API](/en-US/docs/Web/API/SVG_API) documentation.
## Specifications
{{Specifications}}
## See also
- [DOM Examples](/en-US/docs/Web/API/Document_Object_Model/Examples)
- [CSS Object Model (CSSOM)](/en-US/docs/Web/API/CSS_Object_Model)
| 0 |
data/mdn-content/files/en-us/web/api/document_object_model | data/mdn-content/files/en-us/web/api/document_object_model/locating_dom_elements_using_selectors/index.md | ---
title: Locating DOM elements using selectors
slug: Web/API/Document_object_model/Locating_DOM_elements_using_selectors
page-type: guide
---
{{DefaultAPISidebar("DOM")}}
The Selectors API provides methods that make it quick and easy to retrieve {{domxref("Element")}} nodes from the DOM by matching against a set of [selectors](/en-US/docs/Web/CSS/CSS_selectors). This is much faster than past techniques, wherein it was necessary to, for example, use a loop in JavaScript code to locate the specific items you needed to find.
## The NodeSelector interface
This specification adds two new methods to any objects implementing the {{domxref("Document")}}, {{domxref("DocumentFragment")}}, or {{domxref("Element")}} interfaces:
- {{domxref("Element.querySelector", "querySelector()")}}
- : Returns the first matching {{domxref("Element")}} node within the node's subtree. If no matching node is found, `null` is returned.
- {{domxref("Element.querySelectorAll", "querySelectorAll()")}}
- : Returns a {{domxref("NodeList")}} containing all matching `Element` nodes within the node's subtree, or an empty `NodeList` if no matches are found.
> **Note:** The {{domxref("NodeList")}} returned by {{domxref("Element.querySelectorAll()", "querySelectorAll()")}} is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists.
You may find examples and details by reading the documentation for the {{domxref("Element.querySelector()")}} and {{domxref("Element.querySelectorAll()")}} methods.
## Selectors
The selector methods accept [selectors](/en-US/docs/Web/CSS/CSS_selectors) to determine what element or elements should be returned. This includes [selector lists](/en-US/docs/Web/CSS/Selector_list) so you can group multiple selectors in a single query.
To protect the user's privacy, some [pseudo-classes](/en-US/docs/Web/CSS/Pseudo-classes) are not supported or behave differently. For example {{cssxref(":visited")}} will return no matches and {{cssxref(":link")}} is treated as {{cssxref(":any-link")}}.
Only elements can be selected, so [pseudo-classes](/en-US/docs/Web/CSS/Pseudo-classes) are not supported.
## Examples
To select all paragraph (`p`) elements in a document whose classes include `warning` or `note`, you can do the following:
```js
const special = document.querySelectorAll("p.warning, p.note");
```
You can also query by ID. For example:
```js
const el = document.querySelector("#main, #basic, #exclamation");
```
After executing the above code, `el` contains the first element in the document whose ID is one of `main`, `basic`, or `exclamation`.
## See also
- [Selectors specification](https://drafts.csswg.org/selectors/)
- [CSS Selectors](/en-US/docs/Web/CSS/CSS_selectors)
- {{domxref("Element.querySelector()")}}
- {{domxref("Element.querySelectorAll()")}}
- {{domxref("Document.querySelector()")}}
- {{domxref("Document.querySelectorAll()")}}
| 0 |
data/mdn-content/files/en-us/web/api/document_object_model | data/mdn-content/files/en-us/web/api/document_object_model/using_the_document_object_model/index.md | ---
title: Using the Document Object Model
slug: Web/API/Document_object_model/Using_the_Document_Object_Model
page-type: guide
---
{{DefaultAPISidebar("DOM")}}
The _Document Object Model_ (DOM) is an API for manipulating DOM trees of HTML and XML documents (among other tree-like documents). This API is at the root of the description of a page and serves as a base for scripting on the web.
## What is a DOM tree?
A **DOM tree** is a [tree structure](https://en.wikipedia.org/wiki/Tree_structure) whose nodes represent an HTML or XML document's contents. Each HTML or XML document has a DOM tree representation. For example, consider the following document:
```html
<html lang="en">
<head>
<title>My Document</title>
</head>
<body>
<h1>Header</h1>
<p>Paragraph</p>
</body>
</html>
```
It has a DOM tree that looks like this:

Although the above tree is similar to the above document's DOM tree, it's not identical, as [the actual DOM tree preserves whitespace](/en-US/docs/Web/API/Document_Object_Model/Whitespace).
When a web browser parses an HTML document, it builds a DOM tree and then uses it to display the document.
## What does the Document API do?
The Document API, also sometimes called the DOM API, allows you to modify a DOM tree in _any way you want_. It enables you to create any HTML or XML document from scratch or to change any contents of a given HTML or XML document. Web page authors can edit the DOM of a document using JavaScript to access the `document` property of the global object. This `document` object implements the {{domxref("Document")}} interface.
## A simple example
Suppose the author wants to change the header of the above document and write two paragraphs instead of one. The following script would do the job:
### HTML
```html
<html lang="en">
<head>
<title>My Document</title>
</head>
<body>
<input type="button" value="Change this document." onclick="change()" />
<h2>Header</h2>
<p>Paragraph</p>
</body>
</html>
```
### JavaScript
```js
function change() {
// document.getElementsByTagName("h2") returns a NodeList of the <h2>
// elements in the document, and the first is number 0:
const header = document.getElementsByTagName("h2").item(0);
// The firstChild of the header is a Text node:
header.firstChild.data = "A dynamic document";
// Now header is "A dynamic document".
// Access the first paragraph
const para = document.getElementsByTagName("p").item(0);
para.firstChild.data = "This is the first paragraph.";
// Create a new Text node for the second paragraph
const newText = document.createTextNode("This is the second paragraph.");
// Create a new Element to be the second paragraph
const newElement = document.createElement("p");
// Put the text in the paragraph
newElement.appendChild(newText);
// Put the paragraph on the end of the document by appending it to
// the body (which is the parent of para)
para.parentNode.appendChild(newElement);
}
```
{{ EmbedLiveSample('A_simple_example', 800, 300) }}
## How can I learn more?
Now that you are familiar with the basic concepts of the DOM, you may want to learn about the more about fundamental features of the Document API by reading [how to traverse an HTML table with JavaScript and DOM interfaces](/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces).
## See also
- The [Document Object Model](/en-US/docs/Web/API/Document_Object_Model) (DOM).
| 0 |
data/mdn-content/files/en-us/web/api/document_object_model/using_the_document_object_model | data/mdn-content/files/en-us/web/api/document_object_model/using_the_document_object_model/example/index.md | ---
title: Example
slug: Web/API/Document_object_model/Using_the_Document_Object_Model/Example
page-type: guide
---
```html
<html>
<head>
<title>My Document</title>
<script>
function change() {
// document.getElementsByTagName("H1") returns a NodeList of the h1
// elements in the document, and the first is number 0:
const header = document.getElementsByTagName("H1").item(0);
// the firstChild of the header is a Text node:
header.firstChild.data = "A dynamic document";
// now the header is "A dynamic document".
const para = document.getElementsByTagName("P").item(0);
para.firstChild.data = "This is the first paragraph.";
// create a new Text node for the second paragraph
const newText = document.createTextNode(
"This is the second paragraph.",
);
// create a new Element to be the second paragraph
const newElement = document.createElement("P");
// put the text in the paragraph
newElement.appendChild(newText);
// and put the paragraph on the end of the document by appending it to
// the BODY (which is the parent of para)
para.parentNode.appendChild(newElement);
}
</script>
</head>
<body>
<input type="button" value="Change this document." onclick="change()" />
<h1>Header</h1>
<p>Paragraph</p>
</body>
</html>
```
| 0 |
data/mdn-content/files/en-us/web/api/document_object_model | data/mdn-content/files/en-us/web/api/document_object_model/traversing_an_html_table_with_javascript_and_dom_interfaces/index.md | ---
title: Traversing an HTML table with JavaScript and DOM Interfaces
slug: Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
page-type: guide
---
{{DefaultAPISidebar("DOM")}}
This article is an overview of some powerful, fundamental DOM level 1 methods and how to use them from JavaScript. You will learn how to create, access and control, and remove HTML elements dynamically. The DOM methods presented here are not specific to HTML; they also apply to XML. The demonstrations provided here will work fine in any modern browser.
> **Note:** The DOM methods presented here are part of the Document Object Model (Core) level 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML).
## Creating an HTML table dynamically
### Example
In this example we add a new table to the page when a button is clicked.
#### HTML
```html
<input type="button" value="Generate a table" onclick="generateTable()" />
```
#### JavaScript
```js
function generateTable() {
// creates a <table> element and a <tbody> element
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
// creating all cells
for (let i = 0; i < 2; i++) {
// creates a table row
const row = document.createElement("tr");
for (let j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
const cell = document.createElement("td");
const cellText = document.createTextNode(`cell in row ${i}, column ${j}`);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
document.body.appendChild(tbl);
// sets the border attribute of tbl to '2'
tbl.setAttribute("border", "2");
}
```
```css hidden
table {
margin: 1rem auto;
}
td {
padding: 0.5rem;
}
```
#### Result
{{ EmbedLiveSample('Example') }}
### Explanation
Note the order in which we created the elements and the text node:
1. First we created the `<table>` element.
2. Next, we created the `<tbody>` element, which is a child of the `<table>` element.
3. Next, we used a loop to create the `<tr>` elements, which are children of the `<tbody>` element.
4. For each `<tr>` element, we used a loop to create the `<td>` elements, which are children of `<tr>` elements.
5. For each `<td>` element, we then created the text node with the table cell's text.
Once we have created the `<table>`, `<tbody>`, `<tr>`, and `<td>` elements, and then the text node, we then append each object to its parent in the opposite order:
1. First, we attach each text node to its parent `<td>` element using
```js
cell.appendChild(cellText);
```
2. Next, we attach each `<td>` element to its parent `<tr>` element using
```js
row.appendChild(cell);
```
3. Next, we attach each `<tr>` element to the parent `<tbody>` element using
```js
tblBody.appendChild(row);
```
4. Next, we attach the `<tbody>` element to its parent `<table>` element using
```js
tbl.appendChild(tblBody);
```
5. Next, we attach the `<table>` element to its parent `<body>` element using
```js
document.body.appendChild(tbl);
```
Remember this technique. You will use it frequently in programming for the W3C DOM. First, you create elements from the top down; then you attach the children to the parents from the bottom up.
Here's the HTML markup generated by the JavaScript code:
```html
<table border="2">
<tbody>
<tr>
<td>cell is row 0 column 0</td>
<td>cell is row 0 column 1</td>
</tr>
<tr>
<td>cell is row 1 column 0</td>
<td>cell is row 1 column 1</td>
</tr>
</tbody>
</table>
```
Here's the DOM object tree generated by the code for the `<table>` element and its child elements:

You can build this table and its internal child elements by using just a few DOM methods. Remember to keep in mind the tree model for the structures you are planning to create; this will make it easier to write the necessary code. In the `<table>` tree of Figure 1 the element `<table>` has one child: the element `<tbody>`. `<tbody>` has two children. Each `<tbody>`'s child (`<tr>`) has two children (`<td>`). Finally, each `<td>` has one child: a text node.
## Setting the background color of a paragraph
### Example
In this example we change the background color of a paragraph when a button is clicked.
#### HTML
```html
<body>
<input
type="button"
value="Set paragraph background color"
onclick="setBackground()" />
<p>hi</p>
<p>hello</p>
</body>
```
#### JavaScript
```js
function setBackground() {
// now, get all the p elements in the document
const paragraphs = document.getElementsByTagName("p");
// get the second paragraph from the list
const secondParagraph = paragraphs[1];
// set the inline style
secondParagraph.style.background = "red";
}
```
#### Result
{{ EmbedLiveSample('Example_2') }}
### Explanation
`getElementsByTagName(tagNameValue)` is a method available in any DOM {{domxref("Element")}} or the root {{domxref("Document")}} element. When called, it returns an array with all of the element's descendants matching the tag name. The first element of the list is located at position `[0]` in the array.
We've performed following steps:
1. First, we get all the `p` elements in the document:
```js
const paragraphs = document.getElementsByTagName("p");
```
2. Then we get the second paragraph element from the list of `p` elements:
```js
const secondParagraph = paragraphs[1];
```

3. Finally, we set background color to red using the {{domxref("HTMLElement.style", "style")}} property of the {{domxref("HTMLParagraphElement", "paragraph")}} object:
```js
secondParagraph.style.background = "red";
```
### Creating TextNodes with document.createTextNode("..")
Use the document object to invoke the `createTextNode` method and create your text node. You just need to pass the text content. The return value is an object that represents the text node.
```js
myTextNode = document.createTextNode("world");
```
This means that you have created a node of the type `TEXT_NODE` (a piece of text) whose text data is `"world"`, and `myTextNode` is your reference to this node object. To insert this text into your HTML page, you need to make this text node a child of some other node element.
### Inserting Elements with appendChild(..)
So, by calling `secondParagraph.appendChild(node_element)`, you are making the element a new child of the second `<p>` element.
```js
secondParagraph.appendChild(myTextNode);
```
After testing this sample, note that the words hello and world are together: helloworld. So visually, when you see the HTML page it seems like the two text nodes hello and world are a single node, but remember that in the document model, there are two nodes. The second node is a new node of type `TEXT_NODE`, and it is the second child of the second `<p>` tag. The following figure shows the recently created Text Node object inside the document tree.

> **Note:** `createTextNode()` and `appendChild()` is a simple way to include white space between the words _hello_ and _world_. Another important note is that the `appendChild` method will append the child after the last child, just like the word _world_ has been added after the word _hello_. So if you want to append a text node between _hello_ and _world_, you will need to use `insertBefore` instead of `appendChild`.
### Creating New Elements with the document object and the createElement(..) method
You can create new HTML elements or any other element you want with `createElement`. For example, if you want to create a new `<p>` element as a child of the `<body>` element, you can use the `myBody` in the previous example and append a new element node. To create a node call `document.createElement("tagname")`. For example:
```js
myNewPTagNode = document.createElement("p");
myBody.appendChild(myNewPTagNode);
```

### Removing nodes with the removeChild(..) method
Nodes can be removed. The following code removes text node `myTextNode` (containing the word "world") from the second `<p>` element, `secondParagraph`.
```js
secondParagraph.removeChild(myTextNode);
```
Text node `myTextNode` (containing the word "world") still exists. The following code attaches `myTextNode` to the recently created `<p>` element, `myNewPTagNode`.
```js
myNewPTagNode.appendChild(myTextNode);
```
The final state for the modified object tree looks like this:

## Creating a table dynamically (back to Sample1.html)
For the rest of this article we will continue working with sample1.html. The following figure shows the table object tree structure for the table created in the sample.
### Reviewing the HTML Table structure

### Creating element nodes and inserting them into the document tree
The basic steps to create the table in sample1.html are:
- Get the body object (first item of the document object).
- Create all the elements.
- Finally, append each child according to the table structure (as in the above figure). The following source code is a commented version for the sample1.html.
> **Note:** At the end of the `start` function, there is a new line of code. The table's `border` property was set using another DOM method, `setAttribute()`. `setAttribute()` has two arguments: the attribute name and the attribute value. You can set any attribute of any element using the `setAttribute` method.
```html
<html lang="en">
<head>
<title>
Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces
</title>
<script>
function start() {
// get the reference for the body
const myBody = document.getElementsByTagName("body")[0];
// creates <table> and <tbody> elements
const myTable = document.createElement("table");
const myTableBody = document.createElement("tbody");
// creating all cells
for (let j = 0; j < 3; j++) {
// creates a <tr> element
const myCurrentRow = document.createElement("tr");
for (let i = 0; i < 4; i++) {
// creates a <td> element
const myCurrentCell = document.createElement("td");
// creates a Text Node
const currentText = document.createTextNode(
`cell is row ${j}, column ${i}`,
);
// appends the Text Node we created into the cell <td>
myCurrentCell.appendChild(currentText);
// appends the cell <td> into the row <tr>
myCurrentRow.appendChild(myCurrentCell);
}
// appends the row <tr> into <tbody>
myTableBody.appendChild(myCurrentRow);
}
// appends <tbody> into <table>
myTable.appendChild(myTableBody);
// appends <table> into <body>
myBody.appendChild(myTable);
// sets the border attribute of myTable to 2;
myTable.setAttribute("border", "2");
}
</script>
</head>
<body onload="start()"></body>
</html>
```
## Manipulating the table with DOM and CSS
### Getting a text node from the table
This example introduces two new DOM attributes. First it uses the `childNodes` attribute to get the list of child nodes of myCell. The `childNodes` list includes all child nodes, regardless of what their name or type is. Like `getElementsByTagName()`, it returns a list of nodes.
The differences are that (a) `getElementsByTagName()` only returns elements of the specified tag name; and (b) `childNodes` includes all descendants at any level, not just immediate children.
Once you have the returned list, use `[x]` method to retrieve the desired child item. This example stores in `myCellText` the text node of the second cell in the second row of the table.
Then, to display the results in this example, it creates a new text node whose content is the data of `myCellText`, and appends it as a child of the `<body>` element.
> **Note:** If your object is a text node, you can use the data attribute and retrieve the text content of the node.
```js
myBody = document.getElementsByTagName("body")[0];
myTable = myBody.getElementsByTagName("table")[0];
myTableBody = myTable.getElementsByTagName("tbody")[0];
myRow = myTableBody.getElementsByTagName("tr")[1];
myCell = myRow.getElementsByTagName("td")[1];
// first item element of the childNodes list of myCell
myCellText = myCell.childNodes[0];
// content of currentText is the data content of myCellText
currentText = document.createTextNode(myCellText.data);
myBody.appendChild(currentText);
```
### Getting an attribute value
At the end of sample1 there is a call to `setAttribute` on the `myTable` object. This call was used to set the border property of the table. To retrieve the value of the attribute, use the `getAttribute` method:
```js
myTable.getAttribute("border");
```
### Hiding a column by changing style properties
Once you have the object in your JavaScript variable, you can set `style` properties directly. The following code is a modified version of sample1.html in which each cell of the second column is hidden and each cell of the first column is changed to have a red background. Note that the `style` property was set directly.
```html
<html lang="en">
<body onload="start()"></body>
<script>
function start() {
const myBody = document.getElementsByTagName("body")[0];
const myTable = document.createElement("table");
const myTableBody = document.createElement("tbody");
for (let row = 0; row < 2; row++) {
const myCurrentRow = document.createElement("tr");
for (let col = 0; col < 2; col++) {
const myCurrentCell = document.createElement("td");
const currentText = document.createTextNode(`cell is: ${row}${col}`);
myCurrentCell.appendChild(currentText);
myCurrentRow.appendChild(myCurrentCell);
// set the cell background color
// if the column is 0. If the column is 1 hide the cell
if (col === 0) {
myCurrentCell.style.background = "rgb(255 0 0)";
} else {
myCurrentCell.style.display = "none";
}
}
myTableBody.appendChild(myCurrentRow);
}
myTable.appendChild(myTableBody);
myBody.appendChild(myTable);
}
</script>
</html>
```
| 0 |
data/mdn-content/files/en-us/web/api/document_object_model | data/mdn-content/files/en-us/web/api/document_object_model/how_to_create_a_dom_tree/index.md | ---
title: How to create a DOM tree
slug: Web/API/Document_object_model/How_to_create_a_DOM_tree
page-type: guide
---
{{DefaultAPISidebar("DOM")}}
This page describes how to use the DOM API in JavaScript to create XML documents.
Consider the following XML document:
```xml
<?xml version="1.0"?>
<people>
<person first-name="eric" middle-initial="H" last-name="jung">
<address street="321 south st" city="denver" state="co" country="usa"/>
<address street="123 main st" city="arlington" state="ma" country="usa"/>
</person>
<person first-name="jed" last-name="brown">
<address street="321 north st" city="atlanta" state="ga" country="usa"/>
<address street="123 west st" city="seattle" state="wa" country="usa"/>
<address street="321 south avenue" city="denver" state="co" country="usa"/>
</person>
</people>
```
You can use the DOM API to create an in-memory representation of this document:
```js
const doc = document.implementation.createDocument("", "", null);
const peopleElem = doc.createElement("people");
const personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");
const addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);
const addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);
const personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");
const addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);
const addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);
const addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);
peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);
```
DOM trees can be:
- [Queried using XPath expressions](/en-US/docs/Web/XPath/Introduction_to_using_XPath_in_JavaScript).
- Converted to strings using [XMLSerializer](/en-US/docs/Web/XML/Parsing_and_serializing_XML).
- [Posted to a web server](/en-US/docs/Web/API/Fetch_API) using the Fetch API.
- Transformed using [XSLT](/en-US/docs/Web/XSLT) or [XLink](/en-US/docs/Glossary/XLink).
## See also
- [XML](/en-US/docs/Web/XML)
- [XPath](/en-US/docs/Web/XPath)
- [Parsing and serializing XML](/en-US/docs/Web/XML/Parsing_and_serializing_XML)
- [Fetch API](/en-US/docs/Web/API/Fetch_API)
| 0 |
data/mdn-content/files/en-us/web/api/document_object_model | data/mdn-content/files/en-us/web/api/document_object_model/examples/index.md | ---
title: Examples of web and XML development using the DOM
slug: Web/API/Document_Object_Model/Examples
page-type: guide
---
{{DefaultAPISidebar("DOM")}}
This chapter provides some longer examples of web and XML development using the DOM. Wherever possible, the examples use common APIs, tricks, and patterns in JavaScript for manipulating the document object.
## Example 1: height and width
The following example shows the use of the `height` and `width` properties alongside images of varying dimensions:
```html
<!doctype html>
<html lang="en">
<head>
<title>width/height example</title>
<script>
function init() {
const arrImages = new Array(3);
arrImages[0] = document.getElementById("image1");
arrImages[1] = document.getElementById("image2");
arrImages[2] = document.getElementById("image3");
const objOutput = document.getElementById("output");
let strHtml = "<ul>";
for (let i = 0; i < arrImages.length; i++) {
strHtml +=
"<li>image" +
(i + 1) +
": height=" +
arrImages[i].height +
", width=" +
arrImages[i].width +
", style.height=" +
arrImages[i].style.height +
", style.width=" +
arrImages[i].style.width +
"<\/li>";
}
strHtml += "<\/ul>";
objOutput.innerHTML = strHtml;
}
</script>
</head>
<body onload="init();">
<p>
Image 1: no height, width, or style
<img id="image1" src="http://www.mozilla.org/images/mozilla-banner.gif" />
</p>
<p>
Image 2: height="50", width="500", but no style
<img
id="image2"
src="http://www.mozilla.org/images/mozilla-banner.gif"
height="50"
width="500" />
</p>
<p>
Image 3: no height, width, but style="height: 50px; width: 500px;"
<img
id="image3"
src="http://www.mozilla.org/images/mozilla-banner.gif"
style="height: 50px; width: 500px;" />
</p>
<div id="output"></div>
</body>
</html>
```
## Example 2: Image Attributes
```html
<!doctype html>
<html lang="en">
<head>
<title>Modifying an image border</title>
<script>
function setBorderWidth(width) {
document.getElementById("img1").style.borderWidth = width + "px";
}
</script>
</head>
<body>
<p>
<img
id="img1"
src="image1.gif"
style="border: 5px solid green;"
width="100"
height="100"
alt="border test" />
</p>
<form name="FormName">
<input
type="button"
value="Make border 20px-wide"
onclick="setBorderWidth(20);" />
<input
type="button"
value="Make border 5px-wide"
onclick="setBorderWidth(5);" />
</form>
</body>
</html>
```
## Example 3: Manipulating Styles
In this simple example, some basic style properties of an HTML paragraph element are accessed using the style object on the element and that object's CSS style properties, which can be retrieved and set from the DOM. In this case, you are manipulating the individual styles directly. In the next example (see Example 4), you can use stylesheets and their rules to change styles for whole documents.
```html
<!doctype html>
<html lang="en">
<head>
<title>Changing color and font-size example</title>
<script>
function changeText() {
const p = document.getElementById("pid");
p.style.color = "blue";
p.style.fontSize = "18pt";
}
</script>
</head>
<body>
<p id="pid" onclick="window.location.href = 'http://www.cnn.com/';">
linker
</p>
<form>
<p><input value="rec" type="button" onclick="changeText();" /></p>
</form>
</body>
</html>
```
## Example 4: Using Stylesheets
The {{domxref("document.styleSheets", "styleSheets")}} property on the {{domxref("document")}} object returns a list of the stylesheets that have been loaded on that document. You can access these stylesheets and their rules individually using the stylesheet, style, and {{domxref("CSSRule")}} objects, as demonstrated in this example, which prints out all of the style rule selectors to the console.
```js
const ss = document.styleSheets;
for (let i = 0; i < ss.length; i++) {
for (let j = 0; j < ss[i].cssRules.length; j++) {
dump(`${ss[i].cssRules[j].selectorText}\n`);
}
}
```
For a document with a single stylesheet in which the following three rules are defined:
```css
body {
background-color: darkblue;
}
p {
font-family: Arial;
font-size: 10pt;
margin-left: 0.125in;
}
#lumpy {
display: none;
}
```
This script outputs the following:
```plain
BODY
P
#LUMPY
```
## Example 5: Event Propagation
This example demonstrates how events fire and are handled in the DOM in a very simple way. When the BODY of this HTML document loads, an event listener is registered with the top row of the TABLE. The event listener handles the event by executing the function stopEvent, which changes the value in the bottom cell of the table.
However, stopEvent also calls an event object method, {{domxref("event.stopPropagation")}}, which keeps the event from bubbling any further up into the DOM. Note that the table itself has an {{domxref("Element.click_event","onclick")}} event handler that ought to display a message when the table is clicked. But the stopEvent method has stopped propagation, and so after the data in the table is updated, the event phase is effectively ended, and an alert box is displayed to confirm this.
```html
<!doctype html>
<html lang="en">
<head>
<title>Event Propagation</title>
<style>
#t-daddy {
border: 1px solid red;
}
#c1 {
background-color: pink;
}
</style>
<script>
function stopEvent(event) {
const c2 = document.getElementById("c2");
c2.textContent = "hello";
// this ought to keep t-daddy from getting the click.
event.stopPropagation();
alert("event propagation halted.");
}
function load() {
const elem = document.getElementById("tbl1");
elem.addEventListener("click", stopEvent, false);
}
</script>
</head>
<body onload="load();">
<table id="t-daddy" onclick="alert('hi');">
<tr id="tbl1">
<td id="c1">one</td>
</tr>
<tr>
<td id="c2">two</td>
</tr>
</table>
</body>
</html>
```
## Example 6: getComputedStyle
This example demonstrates how the {{domxref("window.getComputedStyle")}} method can be used to get the styles of an element that are not set using the `style` attribute or with JavaScript (e.g., `elt.style.backgroundColor="rgb(173 216 230)"`). These latter types of styles can be retrieved with the more direct {{domxref("HTMLElement.style", "elt.style")}} property, whose properties are listed in the [DOM CSS Properties List](/en-US/docs/Web/CSS/Reference).
`getComputedStyle()` returns a {{domxref("CSSStyleDeclaration")}} object, whose individual style properties can be referenced with this object's {{domxref("CSSStyleDeclaration.getPropertyValue()", "getPropertyValue()")}} method, as the following example document shows.
```html
<!doctype html>
<html lang="en">
<head>
<title>getComputedStyle example</title>
<script>
function cStyles() {
const RefDiv = document.getElementById("d1");
const txtHeight = document.getElementById("t1");
const h_style = document.defaultView
.getComputedStyle(RefDiv, null)
.getPropertyValue("height");
txtHeight.value = h_style;
const txtWidth = document.getElementById("t2");
const w_style = document.defaultView
.getComputedStyle(RefDiv, null)
.getPropertyValue("width");
txtWidth.value = w_style;
const txtBackgroundColor = document.getElementById("t3");
const b_style = document.defaultView
.getComputedStyle(RefDiv, null)
.getPropertyValue("background-color");
txtBackgroundColor.value = b_style;
}
</script>
<style>
#d1 {
margin-left: 10px;
background-color: rgb(173 216 230);
height: 20px;
max-width: 20px;
}
</style>
</head>
<body>
<div id="d1"> </div>
<form action="">
<p>
<button type="button" onclick="cStyles();">getComputedStyle</button>
height<input id="t1" type="text" value="1" /> max-width<input
id="t2"
type="text"
value="2" />
bg-color<input id="t3" type="text" value="3" />
</p>
</form>
</body>
</html>
```
## Example 7: Displaying Event Object Properties
This example uses DOM methods to display all the properties of the {{domxref("Window.load_event", "onload")}} {{domxref("event")}} object and their values in a table. It also shows a useful technique of using a [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop to iterate over the properties of an object to get their values.
The properties of event objects differs greatly between browsers, the [WHATWG DOM Standard](https://dom.spec.whatwg.org) lists the standard properties, however many browsers have extended these greatly.
Put the following code into a blank text file and load it into a variety of browsers, you'll be surprised at the different number and names of properties. You might also like to add some elements in the page and call this function from different event handlers.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Show Event properties</title>
<style>
table {
border-collapse: collapse;
}
thead {
font-weight: bold;
}
td {
padding: 2px 10px 2px 10px;
}
.odd {
background-color: #efdfef;
}
.even {
background-color: #ffffff;
}
</style>
<script>
function showEventProperties(e) {
function addCell(row, text) {
const cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(text));
}
const event = e || window.event;
document.getElementById("eventType").innerHTML = event.type;
const table = document.createElement("table");
const thead = table.createTHead();
let row = thead.insertRow(-1);
const labelList = ["#", "Property", "Value"];
const len = labelList.length;
for (let i = 0; i < len; i++) {
addCell(row, labelList[i]);
}
const tbody = document.createElement("tbody");
table.appendChild(tbody);
for (const p in event) {
row = tbody.insertRow(-1);
row.className = row.rowIndex % 2 ? "odd" : "even";
addCell(row, row.rowIndex);
addCell(row, p);
addCell(row, event[p]);
}
document.body.appendChild(table);
}
window.onload = (event) => {
showEventProperties(event);
};
</script>
</head>
<body>
<h1>Properties of the DOM <span id="eventType"></span> Event Object</h1>
</body>
</html>
```
## Example 8: Using the DOM Table Interface
The DOM {{domxref("HTMLTableElement")}} interface provides some convenience methods for creating and manipulating tables. Two frequently used methods are {{domxref("HTMLTableElement.insertRow")}} and {{domxref("HTMLTableRowElement.insertCell")}}.
To add a row and some cells to an existing table:
```html
<table id="table0">
<tr>
<td>Row 0 Cell 0</td>
<td>Row 0 Cell 1</td>
</tr>
</table>
<script>
const table = document.getElementById("table0");
const row = table.insertRow(-1);
let cell;
let text;
for (let i = 0; i < 2; i++) {
cell = row.insertCell(-1);
text = "Row " + row.rowIndex + " Cell " + i;
cell.appendChild(document.createTextNode(text));
}
</script>
```
### Notes
- A table's {{domxref("element.innerHTML","innerHTML")}} property should never be used to modify a table, although you can use it to write an entire table or the content of a cell.
- If DOM Core methods {{domxref("document.createElement")}} and {{domxref("Node.appendChild")}} are used to create rows and cells, IE requires that they are appended to a {{HTMLElement("tbody")}} element, whereas other browsers will allow appending to a {{HTMLElement("table")}} element (the rows will be added to the last `<tbody>` element).
- There are a number of other convenience methods belonging to the [`HTMLTableElement` interface](/en-US/docs/Web/API/HTMLTableElement#methods) that can be used for creating and modifying tables.
| 0 |
data/mdn-content/files/en-us/web/api/document_object_model | data/mdn-content/files/en-us/web/api/document_object_model/whitespace/index.md | ---
title: How whitespace is handled by HTML, CSS, and in the DOM
slug: Web/API/Document_Object_Model/Whitespace
page-type: guide
---
{{DefaultAPISidebar("DOM")}}
The presence of whitespace in the [DOM](/en-US/docs/Web/API/Document_Object_Model) can cause layout problems and make manipulation of the content tree difficult in unexpected ways, depending on where it is located. This article explores when difficulties can occur, and looks at what can be done to mitigate resulting problems.
## What is whitespace?
Whitespace is any string of text composed only of spaces, tabs or line breaks (to be precise, CRLF sequences, carriage returns or line feeds). These characters allow you to format your code in a way that will make it easily readable by yourself and other people. In fact, much of our source code is full of these whitespace characters, and we only tend to get rid of it in a production build step to reduce code download sizes.
### HTML largely ignores whitespace?
In the case of HTML, whitespace is largely ignored — whitespace in between words is treated as a single character, and whitespace at the start and end of elements and outside elements is ignored. Take the following minimal example:
```html-nolint
<!DOCTYPE html>
<h1> Hello World! </h1>
```
This source code contains a couple of line feeds after the `DOCTYPE` and a bunch of space characters before, after, and inside the `<h1>` element, but the browser doesn't seem to care at all and just shows the words "Hello World!" as if these characters didn't exist at all:
{{EmbedLiveSample('HTML_largely_ignores_whitespace')}}
This is so that whitespace characters don't impact the layout of your page. Creating space around and inside elements is the job of CSS.
### What happens to whitespace?
They don't just disappear, however.
Any whitespace characters that are outside of HTML elements in the original document are represented in the DOM. This is needed internally so that the editor can preserve formatting of documents. This means that:
- There will be some text nodes that contain only whitespace, and
- Some text nodes will have whitespace at the beginning or end.
Take the following document, for example:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>My Document</title>
</head>
<body>
<h1>Header</h1>
<p>Paragraph</p>
</body>
</html>
```
The DOM tree for this looks like so:

Conserving whitespace characters in the DOM is useful in many ways, but there are certain places where this makes certain layouts more difficult to implement, and causes problems for developers who want to iterate through nodes in the DOM. We'll look at these, and some solutions, later on.
### How does CSS process whitespace?
Most whitespace characters are ignored, not all of them are. In the earlier example one of the spaces between "Hello" and "World!" still exists when the page is rendered in a browser. There are rules in the browser engine that decide which whitespace characters are useful and which aren't — these are specified at least in part in [CSS Text Module Level 3](https://www.w3.org/TR/css-text-3/), and especially the parts about the [CSS `white-space` property](https://www.w3.org/TR/css-text-3/#white-space-property) and [whitespace processing details](https://www.w3.org/TR/css-text-3/#white-space-processing), but we also offer an easier explanation below.
#### Example
Let's take another example. To make it easier, we've added a comment that shows all spaces with ◦, all tabs with ⇥, and all line breaks with ⏎:
This example:
```html-nolint
<h1> Hello
<span> World!</span> </h1>
<!--
<h1>◦◦◦Hello◦⏎
⇥⇥⇥⇥<span>◦World!</span>⇥◦◦</h1>
-->
```
is rendered in the browser like so:
{{EmbedLiveSample('Example')}}
#### Explanation
The `<h1>` element contains only inline elements. In fact it contains:
- A text node (consisting of some spaces, the word "Hello" and some tabs).
- An inline element (the `<span>`, which contains a space, and the word "World!").
- Another text node (consisting only of tabs and spaces).
Because of this, it establishes what is called an [inline formatting context](/en-US/docs/Web/CSS/Inline_formatting_context). This is one of the possible layout rendering contexts that browser engines work with.
Inside this context, whitespace character processing can be summarized as follows:
1. First, all spaces and tabs immediately before and after a line break are ignored so, if we take our example markup from before:
```html-nolint
<h1>◦◦◦Hello◦⏎
⇥⇥⇥⇥<span>◦World!</span>⇥◦◦</h1>
```
...and apply this first rule, we get:
```html-nolint
<h1>◦◦◦Hello⏎
<span>◦World!</span>⇥◦◦</h1>
```
2. Next, all tab characters are handled as space characters, so the example becomes:
```html-nolint
<h1>◦◦◦Hello⏎
<span>◦World!</span>◦◦◦</h1>
```
3. Next, line breaks are converted to spaces:
```html-nolint
<h1>◦◦◦Hello◦<span>◦World!</span>◦◦◦</h1>
```
4. After that, any space immediately following another space (even across two separate inline elements) is ignored, so we end up with:
```html-nolint
<h1>◦Hello◦<span>World!</span>◦</h1>
```
5. And finally, sequences of spaces at the beginning and end of an element are removed, so we finally get this:
```html-nolint
<h1>Hello◦<span>World!</span></h1>
```
This is why people visiting the web page will see the phrase "Hello World!" nicely written at the top of the page, rather than a weirdly indented "Hello" followed but an even more weirdly indented "World!" on the line below that.
> **Note:** [Firefox DevTools](https://firefox-source-docs.mozilla.org/devtools-user/index.html) have supported highlighting text nodes since version 52, making it easier to see exactly what nodes whitespace characters are contained within. Pure whitespace nodes are marked with a "whitespace" label.
### Whitespace in block formatting contexts
Above we just looked at elements that contain inline elements, and inline formatting contexts. If an element contains at least one block element, then it instead establishes what is called a [block formatting context](/en-US/docs/Web/CSS/CSS_display/Block_formatting_context).
Within this context, whitespace is treated very differently.
#### Example
Let's take a look at an example to explain how. We've marked the whitespace characters as before.
We have 3 text nodes that contain only whitespace, one before the first `<div>`, one between the 2 `<div>`s, and one after the second `<div>`.
```html-nolint
<body>
<div> Hello </div>
<div> World! </div>
</body>
<!--
<body>⏎
⇥<div>◦◦Hello◦◦</div>⏎
⏎
◦◦◦<div>◦◦World!◦◦</div>◦◦⏎
</body>
-->
```
This renders like so:
{{EmbedLiveSample('Example_2')}}
#### Explanation
We can summarize how the whitespace here is handled as follows (there may be some slight differences in exact behavior between browsers, but this basically works):
1. Because we're inside a block formatting context, everything must be a block, so our 3 text nodes also become blocks, just like the 2 `<div>`s. Blocks occupy the full width available and are stacked on top of each other, which means that, starting from the example above:
```html-nolint
<body>⏎
⇥<div>◦◦Hello◦◦</div>⏎
⏎
◦◦◦<div>◦◦World!◦◦</div>◦◦⏎
</body>
```
...we end up with a layout composed of this list of blocks:
```html
<block>⏎⇥</block>
<block>◦◦Hello◦◦</block>
<block>⏎◦◦◦</block>
<block>◦◦World!◦◦</block>
<block>◦◦⏎</block>
```
2. This is then simplified further by applying the processing rules for whitespace in inline formatting contexts to these blocks:
```html
<block></block>
<block>Hello</block>
<block></block>
<block>World!</block>
<block></block>
```
3. The 3 empty blocks we now have are not going to occupy any space in the final layout, because they don't contain anything, so we'll end up with only 2 blocks taking up space in the page. People viewing the web page see the words "Hello" and "World!" on 2 separate lines as you'd expect 2 `<div>`s to be laid out. The browser engine has essentially ignored all of the whitespace that was added in the source code.
## Spaces in between inline and inline-block elements
Let's move on to look at a few issues that can arise due to whitespace, and what can be done about them. First of all, we'll look at what happens with spaces in between inline and inline-block elements. In fact, we saw this already in our very first example, when we described how whitespace is processed inside inline formatting contexts.
We said that there were rules to ignore most characters but that word-separating characters remain. When you're only dealing with block-level elements such as `<p>` that only contain inline elements such as `<em>`, `<strong>`, `<span>`, etc., you don't normally care about this because the extra whitespace that does make it to the layout is helpful to separate the words in the sentence.
It gets more interesting however when you start using `inline-block` elements. These elements behave like inline elements on the outside, and blocks on the inside, and are often used to display more complex pieces of UI than just text, side-by-side on the same line, for example navigation menu items.
Because they are blocks, many people expect that they will behave as such, but really they don't. If there is formatting whitespace between adjacent inline elements, this will result in space in the layout, just like the spaces between words in text.
### Example
Consider this example (again, we've included an HTML comment that shows the whitespace characters in the HTML):
```css
.people-list {
list-style-type: none;
margin: 0;
padding: 0;
}
.people-list li {
display: inline-block;
width: 2em;
height: 2em;
background: #f06;
border: 1px solid;
}
```
```html
<ul class="people-list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<!--
<ul class="people-list">⏎
◦◦<li></li>⏎
⏎
◦◦<li></li>⏎
⏎
◦◦<li></li>⏎
⏎
◦◦<li></li>⏎
⏎
◦◦<li></li>⏎
</ul>
-->
```
This renders as follows:
{{EmbedLiveSample('Example_3')}}
You probably don't want the gaps in between the blocks — depending on the use case (is this a list of avatars, or horizontal nav buttons?), you probably want the element sides flush with each other, and to be able to control any spacing yourself.
The Firefox DevTools HTML Inspector will highlight text nodes, and also show you exactly what area the elements are taking up — useful if you are wondering what is causing the problem, and are maybe thinking you've got some extra margin in there or something!

### Solutions
There are a few ways of getting around this problem:
Use [Flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox) to create the horizontal list of items instead of trying an `inline-block` solution. This handles everything for you, and is definitely the preferred solution:
```css
ul {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
}
```
If you need to rely on `inline-block`, you could set the [`font-size`](/en-US/docs/Web/CSS/font-size) of the list to 0. This only works if your blocks are not sized with ems (based on the `font-size`, so the block size would also end up being 0). rems would be a good choice here:
```css
ul {
font-size: 0;
/* … */
}
li {
display: inline-block;
width: 2rem;
height: 2rem;
/* … */
}
```
Or you could set negative margin on the list items:
```css
li {
display: inline-block;
width: 2rem;
height: 2rem;
margin-right: -0.25rem;
}
```
You can also solve this problem by putting your list items all on the same line in the source, which causes the whitespace nodes to not be created in the first place:
```html-nolint
<li></li><li></li><li></li><li></li><li></li>
```
## DOM traversal and whitespace
When trying to do [DOM](/en-US/docs/Web/API/Document_Object_Model) manipulation in JavaScript, you can also encounter problems because of whitespace nodes. For example, if you have a reference to a parent node and want to affect its first element child using [`Node.firstChild`](/en-US/docs/Web/API/Node/firstChild), if there is a rogue whitespace node just after the opening parent tag you will not get the result you are expecting. The text node would be selected instead of the element you want to affect.
As another example, if you have a certain subset of elements that you want to do something to based on whether they are empty (have no child nodes) or not, you could check whether each element is empty using something like [`Node.hasChildNodes()`](/en-US/docs/Web/API/Node/hasChildNodes), but again, if any target elements contain text nodes, you could end up with false results.
## Whitespace helper functions
The JavaScript code below defines several functions that make it easier to deal with whitespace in the DOM:
```js
/**
* Throughout, whitespace is defined as one of the characters
* "\t" TAB \u0009
* "\n" LF \u000A
* "\r" CR \u000D
* " " SPC \u0020
*
* This does not use JavaScript's "\s" because that includes non-breaking
* spaces (and also some other characters).
*/
/**
* Determine whether a node's text content is entirely whitespace.
*
* @param nod A node implementing the |CharacterData| interface (i.e.,
* a |Text|, |Comment|, or |CDATASection| node
* @return True if all of the text content of |nod| is whitespace,
* otherwise false.
*/
function is_all_ws(nod) {
return !/[^\t\n\r ]/.test(nod.textContent);
}
/**
* Determine if a node should be ignored by the iterator functions.
*
* @param nod An object implementing the DOM1 |Node| interface.
* @return true if the node is:
* 1) A |Text| node that is all whitespace
* 2) A |Comment| node
* and otherwise false.
*/
function is_ignorable(nod) {
return (
nod.nodeType === 8 || // A comment node
(nod.nodeType === 3 && is_all_ws(nod))
); // a text node, all ws
}
/**
* Version of |previousSibling| that skips nodes that are entirely
* whitespace or comments. (Normally |previousSibling| is a property
* of all DOM nodes that gives the sibling node, the node that is
* a child of the same parent, that occurs immediately before the
* reference node.)
*
* @param sib The reference node.
* @return Either:
* 1) The closest previous sibling to |sib| that is not
* ignorable according to |is_ignorable|, or
* 2) null if no such node exists.
*/
function node_before(sib) {
while ((sib = sib.previousSibling)) {
if (!is_ignorable(sib)) {
return sib;
}
}
return null;
}
/**
* Version of |nextSibling| that skips nodes that are entirely
* whitespace or comments.
*
* @param sib The reference node.
* @return Either:
* 1) The closest next sibling to |sib| that is not
* ignorable according to |is_ignorable|, or
* 2) null if no such node exists.
*/
function node_after(sib) {
while ((sib = sib.nextSibling)) {
if (!is_ignorable(sib)) {
return sib;
}
}
return null;
}
/**
* Version of |lastChild| that skips nodes that are entirely
* whitespace or comments. (Normally |lastChild| is a property
* of all DOM nodes that gives the last of the nodes contained
* directly in the reference node.)
*
* @param sib The reference node.
* @return Either:
* 1) The last child of |sib| that is not
* ignorable according to |is_ignorable|, or
* 2) null if no such node exists.
*/
function last_child(par) {
let res = par.lastChild;
while (res) {
if (!is_ignorable(res)) {
return res;
}
res = res.previousSibling;
}
return null;
}
/**
* Version of |firstChild| that skips nodes that are entirely
* whitespace and comments.
*
* @param sib The reference node.
* @return Either:
* 1) The first child of |sib| that is not
* ignorable according to |is_ignorable|, or
* 2) null if no such node exists.
*/
function first_child(par) {
let res = par.firstChild;
while (res) {
if (!is_ignorable(res)) {
return res;
}
res = res.nextSibling;
}
return null;
}
/**
* Version of |data| that doesn't include whitespace at the beginning
* and end and normalizes all whitespace to a single space. (Normally
* |data| is a property of text nodes that gives the text of the node.)
*
* @param txt The text node whose data should be returned
* @return A string giving the contents of the text node with
* whitespace collapsed.
*/
function data_of(txt) {
let data = txt.textContent;
data = data.replace(/[\t\n\r ]+/g, " ");
if (data[0] === " ") {
data = data.substring(1, data.length);
}
if (data[data.length - 1] === " ") {
data = data.substring(0, data.length - 1);
}
return data;
}
```
### Example
The following code demonstrates the use of the functions above. It iterates over the children of an element (whose children are all elements) to find the one whose text is `"This is the third paragraph"`, and then changes the class attribute and the contents of that paragraph.
```js
let cur = first_child(document.getElementById("test"));
while (cur) {
if (data_of(cur.firstChild) === "This is the third paragraph.") {
cur.className = "magic";
cur.firstChild.textContent = "This is the magic paragraph.";
}
cur = node_after(cur);
}
```
| 0 |
data/mdn-content/files/en-us/web/api/document_object_model | data/mdn-content/files/en-us/web/api/document_object_model/introduction/index.md | ---
title: Introduction to the DOM
slug: Web/API/Document_Object_Model/Introduction
page-type: guide
spec-urls: https://dom.spec.whatwg.org/
---
{{DefaultAPISidebar("DOM")}}
The **Document Object Model** (_DOM_) is the data representation of the objects
that comprise the structure and content of a document on the web.
This guide will introduce the DOM,
look at how the DOM represents an {{Glossary("HTML")}} document in memory
and how to use APIs to create web content and applications.
## What is the DOM?
The Document Object Model (DOM) is a programming interface for web documents.
It represents the page so that programs can change the document structure, style, and content.
The DOM represents the document as nodes and objects;
that way, programming languages can interact with the page.
A web page is a document that can be either displayed in the browser window or as the HTML source. In both cases, it is the same document but the Document Object Model (DOM) representation allows it to be manipulated. As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript.
For example, the DOM specifies that the `querySelectorAll` method in this code snippet must return a list of all the {{HTMLElement("p")}} elements in the document:
```js
const paragraphs = document.querySelectorAll("p");
// paragraphs[0] is the first <p> element
// paragraphs[1] is the second <p> element, etc.
alert(paragraphs[0].nodeName);
```
All of the properties, methods, and events available for manipulating and creating web pages are organized into objects. For example, the `document` object that represents the document itself, any `table` objects that implement the {{domxref("HTMLTableElement")}} DOM interface for accessing HTML tables, and so forth, are all objects.
The DOM is built using multiple APIs that work together.
The core [DOM](/en-US/docs/Web/API/Document_Object_Model) defines the entities
describing any document and the objects within it.
This is expanded upon as needed by other APIs that add new features and capabilities to the DOM.
For example, the [HTML DOM API](/en-US/docs/Web/API/HTML_DOM_API) adds support for representing HTML documents to the core DOM,
and the SVG API adds support for representing SVG documents.
## DOM and JavaScript
The previous short example, like nearly all examples, is {{glossary("JavaScript")}}. That is to say, it is _written_ in JavaScript, but _uses_ the DOM to access the document and its elements. The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of web pages, HTML documents, SVG documents, and their component parts. The document as a whole, the head, tables within the document, table headers, text within the table cells, and all other elements in a document are parts of the document object model for that document. They can all be accessed and manipulated using the DOM and a scripting language like JavaScript.
The DOM is not part of the JavaScript language,
but is instead a Web API used to build websites.
JavaScript can also be used in other contexts.
For example, Node.js runs JavaScript programs on a computer,
but provides a different set of APIs,
and the DOM API is not a core part of the Node.js runtime.
The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API.
Even if most web developers will only use the DOM through JavaScript, implementations of the DOM can be built for any language, as this Python example demonstrates:
```python
# Python DOM example
import xml.dom.minidom as m
doc = m.parse(r"C:\Projects\Py\chap1.xml")
doc.nodeName # DOM property of document object
p_list = doc.getElementsByTagName("para")
```
For more information on what technologies are involved in writing JavaScript on the web, see [JavaScript technologies overview](/en-US/docs/Web/JavaScript/JavaScript_technologies_overview).
## Accessing the DOM
You don't have to do anything special to begin using the DOM.
You use the API directly in JavaScript from within what is called a _script_, a program run by a browser.
When you create a script, whether inline in a `<script>` element or included in the web page, you can immediately begin using the API for the {{domxref("document")}} or {{domxref("Window", "window")}} objects to manipulate the document itself, or any of the various elements in the web page (the descendant elements of the document). Your DOM programming may be something as simple as the following example, which displays a message on the console by using the {{domxref("console/log_static", "console.log()")}} function:
```html
<body onload="console.log('Welcome to my home page!');">
…
</body>
```
As it is generally not recommended to mix the structure of the page (written in HTML)
and manipulation of the DOM (written in JavaScript),
the JavaScript parts will be grouped together here,
and separated from the HTML.
For example, the following function creates a new {{HTMLElement("Heading_Elements", "h1")}} element,
adds text to that element,
and then adds it to the tree for the document:
```html
<html lang="en">
<head>
<script>
// run this function when the document is loaded
window.onload = () => {
// create a couple of elements in an otherwise empty HTML page
const heading = document.createElement("h1");
const headingText = document.createTextNode("Big Head!");
heading.appendChild(headingText);
document.body.appendChild(heading);
};
</script>
</head>
<body></body>
</html>
```
## Fundamental data types
This page tries to describe the various objects and types in simple terms. But there are a number of different data types being passed around the API that you should be aware of.
> **Note:** Because the vast majority of code that uses the DOM revolves around manipulating HTML documents, it's common to refer to the nodes in the DOM as **elements**, although strictly speaking not every node is an element.
The following table briefly describes these data types.
<table class="standard-table">
<thead>
<tr>
<th>Data type (Interface)</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{domxref("Document")}}</td>
<td>
When a member returns an object of type <code>document</code> (e.g., the
<code>ownerDocument</code> property of an element returns the
<code>document</code> to which it belongs), this object is the root
<code>document</code> object itself. The
<a href="/en-US/docs/Web/API/Document">DOM <code>document</code> Reference</a>
chapter describes the <code>document</code> object.
</td>
</tr>
<tr>
<td>{{domxref("Node")}}</td>
<td>
Every object located within a document is a node of some kind. In an
HTML document, an object can be an element node but also a text node or
attribute node.
</td>
</tr>
<tr>
<td>{{domxref("Element")}}</td>
<td>
The <code>element</code> type is based on <code>node</code>. It refers
to an element or a node of type <code>element</code> returned by a
member of the DOM API. Rather than saying, for example, that the
{{domxref("document.createElement()")}} method returns an
object reference to a <code>node</code>, we just say that this method
returns the <code>element</code> that has just been created in the DOM.
<code>element</code> objects implement the DOM
<code>Element</code> interface and also the more basic
<code>Node</code> interface, both of which are included together in this
reference. In an HTML document, elements are further enhanced by the
HTML DOM API's {{domxref("HTMLElement")}} interface as well as
other interfaces describing capabilities of specific kinds of elements
(for instance, {{domxref("HTMLTableElement")}} for
{{HTMLElement("table")}} elements).
</td>
</tr>
<tr>
<td>{{domxref("NodeList")}}</td>
<td>
A <code>nodeList</code> is an array of elements, like the kind that is
returned by the method
{{domxref("document.querySelectorAll()")}}. Items in a
<code>nodeList</code> are accessed by index in either of two ways:
<ul>
<li>list.item(1)</li>
<li>list[1]</li>
</ul>
These two are equivalent. In the first, <code>item()</code> is the
single method on the <code>nodeList</code> object. The latter uses the
typical array syntax to fetch the second item in the list.
</td>
</tr>
<tr>
<td>{{domxref("Attr")}}</td>
<td>
When an <code>attribute</code> is returned by a member (e.g., by the
<code>createAttribute()</code> method), it is an object reference that
exposes a special (albeit small) interface for attributes. Attributes
are nodes in the DOM just like elements are, though you may rarely use
them as such.
</td>
</tr>
<tr>
<td>{{domxref("NamedNodeMap")}}</td>
<td>
A <code>namedNodeMap</code> is like an array, but the items are accessed
by name or index, though this latter case is merely a convenience for
enumeration, as they are in no particular order in the list. A
<code>namedNodeMap</code> has an <code>item()</code> method for this
purpose, and you can also add and remove items from a
<code>namedNodeMap</code>.
</td>
</tr>
</tbody>
</table>
There are also some common terminology considerations to keep in mind. It's common to refer to any {{domxref("Attr")}} node as an `attribute`, for example, and to refer to an array of DOM nodes as a `nodeList`. You'll find these terms and others to be introduced and used throughout the documentation.
## DOM interfaces
This guide is about the objects and the actual _things_ you can use to manipulate the DOM hierarchy. There are many points where understanding how these work can be confusing. For example, the object representing the HTML `form` element gets its `name` property from the `HTMLFormElement` interface but its `className` property from the `HTMLElement` interface. In both cases, the property you want is in that form object.
But the relationship between objects and the interfaces that they implement in the DOM can be confusing, and so this section attempts to say a little something about the actual interfaces in the DOM specification and how they are made available.
### Interfaces and objects
Many objects implement several different interfaces. The table object, for example, implements a specialized {{domxref("HTMLTableElement")}} interface, which includes such methods as `createCaption` and `insertRow`. But since it's also an HTML element, `table` implements the `Element` interface described in the DOM {{domxref("Element")}} Reference chapter. And finally, since an HTML element is also, as far as the DOM is concerned, a node in the tree of nodes that make up the object model for an HTML or XML page, the table object also implements the more basic `Node` interface, from which `Element` derives.
When you get a reference to a `table` object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it.
```js
const table = document.getElementById("table");
const tableAttrs = table.attributes; // Node/Element interface
for (let i = 0; i < tableAttrs.length; i++) {
// HTMLTableElement interface: border attribute
if (tableAttrs[i].nodeName.toLowerCase() === "border") {
table.border = "1";
}
}
// HTMLTableElement interface: summary attribute
table.summary = "note: increased border";
```
### Core interfaces in the DOM
This section lists some of the most commonly-used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM. These common APIs are used in the longer examples in the [DOM Examples](/en-US/docs/Web/API/Document_Object_Model/Examples) chapter at the end of this book.
The `document` and `window` objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the `window` object represents something like the browser, and the `document` object is the root of the document itself. `Element` inherits from the generic `Node` interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the `table` object example in the previous section.
The following is a brief list of common APIs in web and XML page scripting using the DOM.
- {{domxref("document.querySelector()")}}
- {{domxref("document.querySelectorAll()")}}
- {{domxref("document.createElement()")}}
- {{domxref("Element.innerHTML")}}
- {{domxref("Element.setAttribute()")}}
- {{domxref("Element.getAttribute()")}}
- {{domxref("EventTarget.addEventListener()")}}
- {{domxref("HTMLElement.style")}}
- {{domxref("Node.appendChild()")}}
- {{domxref("Window.load_event", "window.onload")}}
- {{domxref("window.scrollTo()")}}
## Examples
### Setting text content
This example uses a {{HTMLElement("div")}} element containing a {{HTMLElement("textarea")}} and two {{HTMLElement("button")}} elements. When the user clicks the first button we set some text in the `<textarea>`. When the user clicks the second button we clear the text. We use:
- {{domxref("Document.querySelector()")}} to access the `<textarea>` and the button
- {{domxref("EventTarget.addEventListener()")}} to listen for button clicks
- {{domxref("Node.textContent")}} to set and clear the text.
#### HTML
```html
<div class="container">
<textarea class="story"></textarea>
<button id="set-text" type="button">Set text content</button>
<button id="clear-text" type="button">Clear text content</button>
</div>
```
#### CSS
```css
.container {
display: flex;
gap: 0.5rem;
flex-direction: column;
}
button {
width: 200px;
}
```
#### JavaScript
```js
const story = document.body.querySelector(".story");
const setText = document.body.querySelector("#set-text");
setText.addEventListener("click", () => {
story.textContent = "It was a dark and stormy night...";
});
const clearText = document.body.querySelector("#clear-text");
clearText.addEventListener("click", () => {
story.textContent = "";
});
```
#### Result
{{EmbedLiveSample("Setting text content", "", "150px")}}
### Adding a child element
This example uses a {{HTMLElement("div")}} element containing a {{HTMLElement("div")}} and two {{HTMLElement("button")}} elements. When the user clicks the first button we create a new element and add it as a child of the `<div>`. When the user clicks the second button we remove the child element. We use:
- {{domxref("Document.querySelector()")}} to access the `<div>` and the buttons
- {{domxref("EventTarget.addEventListener()")}} to listen for button clicks
- {{domxref("Document.createElement")}} to create the element
- {{domxref("Node.appendChild()")}} to add the child
- {{domxref("Node.removeChild()")}} to remove the child.
#### HTML
```html
<div class="container">
<div class="parent">parent</div>
<button id="add-child" type="button">Add a child</button>
<button id="remove-child" type="button">Remove child</button>
</div>
```
#### CSS
```css
.container {
display: flex;
gap: 0.5rem;
flex-direction: column;
}
button {
width: 100px;
}
div.parent {
border: 1px solid black;
padding: 5px;
width: 100px;
height: 100px;
}
div.child {
border: 1px solid red;
margin: 10px;
padding: 5px;
width: 80px;
height: 60px;
box-sizing: border-box;
}
```
#### JavaScript
```js
const parent = document.body.querySelector(".parent");
const addChild = document.body.querySelector("#add-child");
addChild.addEventListener("click", () => {
// Only add a child if we don't already have one
// in addition to the text node "parent"
if (parent.childNodes.length > 1) {
return;
}
const child = document.createElement("div");
child.classList.add("child");
child.textContent = "child";
parent.appendChild(child);
});
const removeChild = document.body.querySelector("#remove-child");
removeChild.addEventListener("click", () => {
const child = document.body.querySelector(".child");
parent.removeChild(child);
});
```
#### Result
{{EmbedLiveSample("Adding a child element", "", "180px")}}
## Specifications
{{Specifications}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/ndefmessage/index.md | ---
title: NDEFMessage
slug: Web/API/NDEFMessage
page-type: web-api-interface
status:
- experimental
browser-compat: api.NDEFMessage
---
{{securecontext_header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The **`NDEFMessage`** interface of the [Web NFC API](/en-US/docs/Web/API/Web_NFC_API) represents the content of an NDEF message that has been read from or could be written to an NFC tag. An instance is acquired by calling the `NDEFMessage()` constructor or from the {{domxref("NDEFReadingEvent.message")}} property, which is passed to the {{domxref("NDEFReader.reading_event", "reading")}} event.
## Constructor
- {{DOMxRef("NDEFMessage.NDEFMessage", "NDEFMessage()")}} {{Experimental_Inline}}
- : Creates a new `NDEFMessage` object, initialized with the given NDEF records.
## Attributes
- {{DOMxRef("NDEFMessage.records")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the list of NDEF records contained in the message.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefmessage | data/mdn-content/files/en-us/web/api/ndefmessage/records/index.md | ---
title: "NDEFMessage: records property"
short-title: records
slug: Web/API/NDEFMessage/records
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.NDEFMessage.records
---
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The `records` property of
{{DOMxRef("NDEFMessage")}} interface represents a list of {{DOMxRef("NDEFRecord")}}s
present in the NDEF message.
## Value
A list of {{DOMxRef("NDEFRecord")}} object that represent data recorded in the message.
## Examples
The following example shows how to read the contents of an NDEF message. It first sets up an event handler for {{domxref("NDEFReader.reading_event", "onreading")}}, which is passed an instance of {{domxref("NDEFReadingEvent")}}. An `NDEFMessage` object is returned from {{domxref("NDEFReadingEvent.message")}}. It loops through `message.records` and processes each record based on its message type. The data member is a {{jsxref("DataView")}}, which allows handling data encoded in UTF-16.
```js
ndefReaderInst.onreading = (event) => {
const ndefMessage = event.message;
for (const record of ndefMessage.records) {
console.log(`Record type: ${record.recordType}`);
console.log(`MIME type: ${record.mediaType}`);
console.log(`Record id: ${record.id}`);
switch (record.recordType) {
case "text":
// TODO: Read text record with record data, lang, and encoding.
break;
case "url":
// TODO: Read URL record with record data.
break;
default:
// TODO: Handle other records with record data.
}
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/ndefmessage | data/mdn-content/files/en-us/web/api/ndefmessage/ndefmessage/index.md | ---
title: "NDEFMessage: NDEFMessage() constructor"
short-title: NDEFMessage()
slug: Web/API/NDEFMessage/NDEFMessage
page-type: web-api-constructor
status:
- experimental
browser-compat: api.NDEFMessage.NDEFMessage
---
{{SecureContext_Header}}{{APIRef("Web NFC API")}}{{SeeCompatTable}}
The **`NDEFMessage()`** constructor creates a new {{domxref("NDEFMessage")}} object, initialized with the given NDEF records.
## Syntax
```js-nolint
new NDEFMessage(records)
```
### Parameters
- `records`
- : An array of objects with the following members:
- `data` {{optional_inline}}
- : Contains the data to be transmitted; one of a string, n {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}}, or an array of nested records.
- `encoding` {{optional_inline}}
- : A string specifying the record's encoding.
- `id` {{optional_inline}}
- : A developer-defined identifier for the record.
- `lang` {{optional_inline}}
- : A valid language tag according to {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}.
- `mediaType` {{optional_inline}}
- : A valid [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types).
- `recordType`
- : A string indicating the type of data stored in `data`. It must be one of the following values:
- `"absolute-url"`
An absolute URL to the data.
`"empty"`
- : An empty {{domxref("NDEFRecord")}}.
- `"mime"`
- : A valid [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types).
- `"smart-poster"`
- : A smart poster as defined by the [NDEF-SMARTPOSTER](https://w3c.github.io/web-nfc/#bib-ndef-smartposter) specification.
- `"text"`
- : Text as defined by the [NDEF-TEXT](https://w3c.github.io/web-nfc/#bib-ndef-text) specification.
- `"unknown"`
- : The record type is not known.
- `"URL"`
- : A URL as defined by the [NDEF-URI](https://w3c.github.io/web-nfc/#bib-ndef-uri) specification.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cookiestore/index.md | ---
title: CookieStore
slug: Web/API/CookieStore
page-type: web-api-interface
browser-compat: api.CookieStore
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`CookieStore`** interface of the {{domxref("Cookie Store API", "", "", "nocode")}} provides methods for getting and setting cookies asynchronously from either a page or a service worker.
The `CookieStore` is accessed via attributes in the global scope in a {{domxref("Window")}} or {{domxref("ServiceWorkerGlobalScope")}} context. Therefore there is no constructor.
{{InheritanceDiagram}}
{{AvailableInWorkers}}
## Instance methods
- {{domxref("CookieStore.delete()")}}
- : The `delete()` method deletes a cookie with the given name or options object, it returns a {{jsxref("Promise")}} that resolves when the deletion completes.
- {{domxref("CookieStore.get()")}}
- : The `get()` method gets a single cookie with the given name or options object, it returns a {{jsxref("Promise")}} that resolves with details of a single cookie.
- {{domxref("CookieStore.getAll()")}}
- : The `getAll()` method gets all matching cookies, it returns a {{jsxref("Promise")}} that resolves with a list of cookies.
- {{domxref("CookieStore.set()")}}
- : The `set()` method sets a cookie with the given name and value or options object, it returns a {{jsxref("Promise")}} that resolves when the cookie is set.
## Events
- {{domxref("CookieStore.change_event", "change")}}
- : The `change` event fires when a change is made to any cookie.
## Examples
In this example, we set a cookie and write to the console feedback as to whether the operation succeeded or failed.
```js
const day = 24 * 60 * 60 * 1000;
cookieStore
.set({
name: "cookie1",
value: "cookie1-value",
expires: Date.now() + day,
domain: "example.com",
})
.then(
() => {
console.log("It worked!");
},
(reason) => {
console.error("It failed: ", reason);
},
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cookiestore | data/mdn-content/files/en-us/web/api/cookiestore/get/index.md | ---
title: "CookieStore: get() method"
short-title: get()
slug: Web/API/CookieStore/get
page-type: web-api-instance-method
browser-compat: api.CookieStore.get
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`get()`** method of the {{domxref("CookieStore")}} interface returns a single cookie with the given name or options object. The method will return the first matching cookie for the passed parameters.
{{AvailableInWorkers}}
## Syntax
```js-nolint
get(name)
get(options)
```
### Parameters
This method requires one of the following:
- `name` {{optional_inline}}
- : A string with the name of a cookie.
Or
- `options` {{optional_inline}}
- : An object containing:
- `name`
- : A string with the name of a cookie.
- `url`
- : A string with the URL of a cookie.
> **Note:** The `url` option enables the modification of a cookie scoped under a particular URL. Service workers can obtain cookies that would be sent to any URL under their scope. From a document you may only obtain the cookies at the current URL, so the only valid URL in a document context is the document's URL.
### Return value
A {{jsxref("Promise")}} that resolves with an object representing the first cookie matching the submitted name or options. This object contains the following properties:
- `domain`
- : A string containing the domain of the cookie.
- `expires`
- : A timestamp, given as {{glossary("Unix time")}} in milliseconds, containing the expiration date of the cookie.
- `name`
- : A string containing the name of the cookie.
- `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.
- `path`
- : A string containing the path of the cookie.
- `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.
- `secure`
- : A boolean value indicating whether the cookie is to be used in secure contexts only (`true`) or not (`false`).
- `value`
- : A string containing the value of the cookie.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the origin does not {{glossary("Serialization", "serialize")}} to a URL.
- {{jsxref("TypeError")}}
- : Thrown if:
- The `options` parameter is an empty object.
- The `url` option is present and is not equal with the creation URL, if in main thread.
- The `url` option is present and its origin is not the same as the origin of the creation URL.
- Querying cookies represented by the given `name` or `options` fails.
## Examples
In this example, we return a cookie named "cookie1". If the cookie is found the result of the Promise is an object containing the details of a single cookie.
```js
const cookie = await cookieStore.get("cookie1");
if (cookie) {
console.log(cookie);
} else {
console.log("Cookie not found");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cookiestore | data/mdn-content/files/en-us/web/api/cookiestore/set/index.md | ---
title: "CookieStore: set() method"
short-title: set()
slug: Web/API/CookieStore/set
page-type: web-api-instance-method
browser-compat: api.CookieStore.set
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`set()`** method of the {{domxref("CookieStore")}} interface sets a cookie with the given name and value or options object.
{{AvailableInWorkers}}
## Syntax
```js-nolint
set(name, value)
set(options)
```
### Parameters
This method requires one of the following:
- `name` {{optional_inline}}
- : A string with the name of the cookie.
- `value` {{optional_inline}}
- : A string with the value of the cookie.
Or
- `options` {{optional_inline}}
- : An object containing:
- `domain` {{Optional_Inline}}
- : A string containing the domain of the cookie. Defaults to `null`.
- `expires` {{Optional_Inline}}
- : A timestamp, given as {{glossary("Unix time")}} in milliseconds, containing the expiration date of the cookie. Defaults to `null`.
- `name`
- : A string with the name of a cookie.
- `partitioned` {{Optional_Inline}}
- : A boolean value that defaults to `false`. If set to `true`, the set cookie will be a partitioned cookie. See [Cookies Having Independent Partitioned State (CHIPS)](/en-US/docs/Web/Privacy/Partitioned_cookies) for more information.
- `path` {{Optional_Inline}}
- : A string containing the path of the cookie. Defaults to `/`.
- `sameSite` {{Optional_Inline}}
- : 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 along with requests initiated by third party websites. This is the default.
- `"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 to the origin site (i.e. when following a link).
- `"none"`
- : Cookies will be sent in all contexts.
- `value`
- : A string with the value of the cookie.
### Return value
A {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}} when setting the cookie completes.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the origin can not be {{glossary("Serialization", "serialized")}} to a URL.
- {{jsxref("TypeError")}}
- : Thrown if setting the cookie with the given `name` and `value` or `options` fails.
## Examples
The following example sets a cookie by passing an object with `name`, `value`, `expires`, and `domain`.
```js
const day = 24 * 60 * 60 * 1000;
cookieStore.set({
name: "cookie1",
value: "cookie1-value",
expires: Date.now() + day,
domain: "example.com",
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cookiestore | data/mdn-content/files/en-us/web/api/cookiestore/delete/index.md | ---
title: "CookieStore: delete() method"
short-title: delete()
slug: Web/API/CookieStore/delete
page-type: web-api-instance-method
browser-compat: api.CookieStore.delete
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`delete()`** method of the {{domxref("CookieStore")}} interface deletes a cookie with the given name or options object. The `delete()` method expires the cookie by changing the date to one in the past.
{{AvailableInWorkers}}
## Syntax
```js-nolint
delete(name)
delete(options)
```
### Parameters
This method requires one of the following:
- `name` {{optional_inline}}
- : A string with the name of a cookie.
Or
- `options` {{optional_inline}}
- : An object containing:
- `name`
- : A string with the name of a cookie.
- `domain` {{Optional_Inline}}
- : A string with the domain of a cookie. Defaults to `null`.
- `path` {{Optional_Inline}}
- : A string containing a path. Defaults to `/`.
- `partitioned` {{Optional_Inline}}
- : A boolean value that defaults to `false`. Setting it to `true` specifies that the cookie to delete will be a partitioned cookie. See [Cookies Having Independent Partitioned State (CHIPS)](/en-US/docs/Web/Privacy/Partitioned_cookies) for more information.
> **Note:** The `url` option enables the modification of a cookie scoped under a particular URL. Service workers can obtain cookies that would be sent to any URL under their scope. From a document you may only obtain the cookies at the current URL, so the only valid URL in a document context is the document's URL.
### Return value
A {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}} when deletion completes.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the origin can not be {{glossary("Serialization", "serialized")}} to a URL.
- {{jsxref("TypeError")}}
- : Thrown if deleting the cookie represented by the given `name` or `options` fails.
## Examples
In this example, a cookie is deleted by passing the name to the `delete()` method.
```js
const result = cookieStore.delete("cookie1");
console.log(result);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cookiestore | data/mdn-content/files/en-us/web/api/cookiestore/change_event/index.md | ---
title: "CookieStore: change event"
short-title: change
slug: Web/API/CookieStore/change_event
page-type: web-api-event
browser-compat: api.CookieStore.change_event
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
A `change` event is fired at a {{domxref("CookieStore")}} object when a change is made to any cookie.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js-nolint
cookieStore.addEventListener("change", (event) => { })
cookieStore.onchange = (event) => { }
```
## Event type
A {{domxref("CookieChangeEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("CookieChangeEvent")}}
## Examples
To be informed when a cookie has changed, you can add a handler to the `cookieStore` instance using {{domxref("EventTarget.addEventListener", "addEventListener()")}}, like this:
```js
cookieStore.addEventListener("change", (event) => {
console.log("1 change event");
});
```
Alternatively, you can use the `onchange` event handler property to establish a handler for the `change` event:
```js
cookieStore.onchange = (event) => {
console.log("1 change event");
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cookiestore | data/mdn-content/files/en-us/web/api/cookiestore/getall/index.md | ---
title: "CookieStore: getAll() method"
short-title: getAll()
slug: Web/API/CookieStore/getAll
page-type: web-api-instance-method
browser-compat: api.CookieStore.getAll
---
{{securecontext_header}}{{APIRef("Cookie Store API")}}
The **`getAll()`** method of the {{domxref("CookieStore")}} interface returns a list of cookies that match the name or options passed to it. Passing no parameters will return all cookies for the current context.
{{AvailableInWorkers}}
## Syntax
```js-nolint
getAll(name)
getAll(options)
```
### Parameters
- `name` {{optional_inline}}
- : A string with the name of a cookie.
Or
- `options` {{optional_inline}}
- : An object containing:
- `name`
- : A string with the name of a cookie.
- `url`
- : A string with the URL of a cookie.
> **Note:** The `url` option enables the modification of a cookie scoped under a particular URL. Service workers can obtain cookies that would be sent to any URL under their scope. From a document you may only obtain the cookies at the current URL, so the only valid URL in a document context is the document's URL.
### Return value
A {{jsxref("Promise")}} that resolves with an array of objects representing cookies that match the given name or options.
Each object contains the following properties:
- `domain`
- : A string containing the domain 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.
- `name`
- : A string containing the name of the cookie.
- `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.
- `path`
- : A string containing the path of the cookie.
- `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.
- `secure`
- : A boolean value indicating whether the cookie is to be used in secure contexts only (`true`) or not (`false`).
- `value`
- : A string containing the value of the cookie.
### Exceptions
- `SecurityError` {{domxref("DOMException")}}
- : Thrown if the origin does not {{glossary("Serialization", "serialize")}} to a URL.
- {{jsxref("TypeError")}}
- : Thrown if:
- The `url` option is present and is not equal with the creation URL, if in main thread.
- The `url` option is present and its origin is not the same as the origin of the creation URL.
- Querying cookies represented by the given `name` or `options` fails.
## Examples
In this example, we use `getAll()` with no parameters. This returns all of the cookies for this context as an array of objects.
```js
const cookies = await cookieStore.getAll();
if (cookies.length > 0) {
console.log(cookies);
} else {
console.log("Cookie not found");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/caretposition/index.md | ---
title: CaretPosition
slug: Web/API/CaretPosition
page-type: web-api-interface
status:
- experimental
browser-compat: api.CaretPosition
---
{{SeeCompatTable}} {{ APIRef("CSSOM") }}
The `CaretPosition` interface represents the caret position, an indicator for the text insertion point. You can get a `CaretPosition` using the {{domxref("Document.caretPositionFromPoint()")}} method.
## Instance properties
_This interface doesn't inherit any properties._
- {{domxref("CaretPosition.offsetNode")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("Node")}} containing the found node at the caret's position.
- {{domxref("CaretPosition.offset")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a `long` representing the character offset in the caret position node.
## Instance methods
- {{domxref("CaretPosition.getClientRect")}} {{Experimental_Inline}}
- : Returns the client rectangle for the caret range.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Document.caretPositionFromPoint()")}}
- {{domxref("Range")}}
- {{domxref("Node")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/url_api/index.md | ---
title: URL API
slug: Web/API/URL_API
page-type: web-api-overview
browser-compat:
- api.URL
- api.URLSearchParams
spec-urls: https://url.spec.whatwg.org/#api
---
{{DefaultAPISidebar("URL API")}}
The URL API is a component of the URL standard, which defines what constitutes a valid {{Glossary("URL", "Uniform Resource Locator")}} and the API that accesses and manipulates URLs. The URL standard also defines concepts such as domains, hosts, and IP addresses, and also attempts to describe in a standard way the legacy `application/x-www-form-urlencoded` {{Glossary("MIME type")}} used to submit web forms' contents as a set of key/value pairs.
{{AvailableInWorkers}}
## Concepts and usage
The majority of the URL standard is taken up by the [definition of a URL](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL) and how it is structured and parsed. Also covered are definitions of various terms related to addressing of computers on a network, and the algorithms for parsing IP addresses and DOM addresses are specified. More interesting to most developers is the API itself.
### Accessing URL components
Creating an {{domxref("URL")}} object for a given URL parses the URL and provides quick access to its constituent parts through its properties.
```js
let addr = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL_API");
let host = addr.host;
let path = addr.pathname;
```
The snippet above creates a `URL` object for the article you're reading right now, then fetches the {{domxref("URL.host", "host")}} and {{domxref("URL.pathname", "pathname")}} properties. In this case, those strings are `developer.mozilla.org` and `/en-US/docs/Web/API/URL_API`, respectively.
### Changing the URL
Most of the properties of `URL` are settable; you can write new values to them to alter the URL represented by the object. For example, to create a URL and set its username:
```js
let myUsername = "someguy";
let addr = new URL("https://example.com/login");
addr.username = myUsername;
```
Setting the value of {{domxref("URL.username", "username")}} not only sets that property's value, but it updates the overall URL. After executing the code snippet above, the value returned by {{domxref("URL.href", "href")}} is `https://[email protected]/login`. This is true for any of the writable properties.
### Queries
The {{domxref("URL.search", "search")}} property on a `URL` contains the query string portion of the URL. For example, if the URL is `https://example.com/login?user=someguy&page=news`, then the value of the `search` property is `?user=someguy&page=news`. You can also look up the values of individual parameters with the {{domxref("URLSearchParams")}} object's {{domxref("URLSearchParams.get", "get()")}} method:
```js
let addr = new URL("https://example.com/login?user=someguy&page=news");
try {
loginUser(addr.searchParams.get("user"));
gotoPage(addr.searchParams.get("page"));
} catch (err) {
showErrorMessage(err);
}
```
For example, in the above snippet, the username and target page are taken from the query and passed to appropriate functions that are used by the site's code to log in and route the user to their desired destination within the site.
Other functions within `URLSearchParams` let you change the value of keys, add and delete keys and their values, and even sort the list of parameters.
## Interfaces
The URL API is a simple one, with only a couple of interfaces to its name:
- {{domxref("URL")}}
- : Can be used to parse, construct, normalize, and encode {{glossary("URL", "URLs")}}.
- {{domxref("URLSearchParams")}}
- : Defines utility methods to work with the query string of a URL.
## Examples
If you want to process the parameters included in a URL, you could do it manually, but it's much easier to create a `URL` object to do it for you. The `fillTableWithParameters()` function below takes as input a {{domxref("HTMLTableElement")}} object representing a {{HTMLElement("table")}}. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value.
Note the call to {{domxref("URLSearchParams.sort()")}} to sort the parameter list before generating the table.
```js
function fillTableWithParameters(tbl) {
const url = new URL(document.location.href);
url.searchParams.sort();
const keys = url.searchParams.keys();
for (const key of keys) {
const val = url.searchParams.get(key);
const row = document.createElement("tr");
const cell1 = document.createElement("td");
cell1.innerText = key;
row.appendChild(cell1);
const cell2 = document.createElement("td");
cell2.innerText = val;
row.appendChild(cell2);
tbl.appendChild(row);
}
}
```
A working version of this example can be [found on Glitch](https://url-api.glitch.me). Just add parameters to the URL when loading the page to see them in the table. For instance, try [`https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable`](https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Fetch API", "", "", "nocode")}}
- CSS {{cssxref("<url>")}} type
- {{jsxref("encodeURI", "encodeURI()")}}
- {{jsxref("encodeURIComponent", "encodeURIComponent()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmltablerowelement/index.md | ---
title: HTMLTableRowElement
slug: Web/API/HTMLTableRowElement
page-type: web-api-interface
browser-compat: api.HTMLTableRowElement
---
{{ APIRef("HTML DOM") }}
The **`HTMLTableRowElement`** interface provides special properties and methods (beyond the {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating the layout and presentation of rows in an HTML table.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLTableRowElement.cells")}} {{ReadOnlyInline}}
- : Returns a live {{domxref("HTMLCollection")}} containing the cells in the row. The `HTMLCollection` is live and is automatically updated when cells are added or removed.
- {{domxref("HTMLTableRowElement.rowIndex")}} {{ReadOnlyInline}}
- : Returns a `long` value which gives the logical position of the row within the entire table. If the row is not part of a table, returns `-1`.
- {{domxref("HTMLTableRowElement.sectionRowIndex")}} {{ReadOnlyInline}}
- : Returns a `long` value which gives the logical position of the row within the table section it belongs to. If the row is not part of a section, returns `-1`.
## Instance methods
_Inherits methods from its parent, {{domxref("HTMLElement")}}_.
- {{domxref("HTMLTableRowElement.deleteCell()", "deleteCell(index)")}}
- : Removes the cell corresponding to `index`. If `index` is `-1`, the last cell of the row is removed. If `index` is less than `-1` or greater than the amount of cells in the collection, a {{DOMxRef("DOMException")}} with the value `IndexSizeError` is raised.
- {{domxref("HTMLTableRowElement.insertCell()", "insertCell(index)")}}
- : Returns an {{DOMxRef("HTMLTableCellElement")}} representing a new cell of the row. The cell is inserted in the collection of cells immediately before the given `index` position in the row. If `index` is `-1`, the new cell is appended to the collection. If `index` is less than `-1` or greater than the number of cells in the collection, a {{DOMxRef("DOMException")}} with the value `IndexSizeError` is raised.
## Deprecated properties
> **Warning:** These properties have been deprecated and should no longer be used. They are documented primarily to help understand older code bases.
- {{domxref("HTMLTableRowElement.align")}} {{deprecated_inline}}
- : A string containing an enumerated value reflecting the [`align`](/en-US/docs/Web/HTML/Element/tr#align) attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, and `"center"`.
- {{domxref("HTMLTableRowElement.bgColor")}} {{deprecated_inline}}
- : A string containing the background color of the cells. It reflects the obsolete [`bgColor`](/en-US/docs/Web/HTML/Element/tr#bgcolor) attribute.
- {{domxref("HTMLTableRowElement.ch")}} {{deprecated_inline}}
- : A string containing one single character. This character is the one to align all the cell of a column on. It reflects the [`char`](/en-US/docs/Web/HTML/Element/tr#char) and default to the decimal points associated with the language, e.g. `'.'` for English, or `','` for French. This property was optional and was not very well supported.
- {{domxref("HTMLTableRowElement.chOff")}} {{deprecated_inline}}
- : A string containing an integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by `HTMLTableRowElement.ch`. This property was optional and was not very well supported.
- {{domxref("HTMLTableRowElement.vAlign")}} {{deprecated_inline}}
- : A string representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the [`valign`](/en-US/docs/Web/HTML/Element/tr#valign) attribute and can have one of the following values: `"top"`, `"middle"`, `"bottom"`, or `"baseline"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("tr")}}.
| 0 |
data/mdn-content/files/en-us/web/api/htmltablerowelement | data/mdn-content/files/en-us/web/api/htmltablerowelement/rowindex/index.md | ---
title: "HTMLTableRowElement: rowIndex property"
short-title: rowIndex
slug: Web/API/HTMLTableRowElement/rowIndex
page-type: web-api-instance-property
browser-compat: api.HTMLTableRowElement.rowIndex
---
{{ APIRef("HTML DOM") }}
The **`HTMLTableRowElement.rowIndex`** read-only property
represents the position of a row in relation to the whole {{HtmlElement("table")}}.
Even when the {{HtmlElement("thead")}}, {{HtmlElement("tbody")}}, and
{{HtmlElement("tfoot")}} elements are out of order in the HTML, browsers render the
table in the right order. Therefore the rows count from `<thead>` to
`<tbody>`, from `<tbody>` to
`<tfoot>`.
## Value
Returns the index of the row, or `-1` if the row is not part of a table.
## Examples
This example uses JavaScript to label all the row numbers in a table.
### HTML
```html
<table>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bananas</td>
<td>$2</td>
</tr>
<tr>
<td>Oranges</td>
<td>$8</td>
</tr>
<tr>
<td>Top Sirloin</td>
<td>$20</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$30</td>
</tr>
</tfoot>
</table>
```
### JavaScript
```js
let rows = document.querySelectorAll("tr");
rows.forEach((row) => {
let z = document.createElement("td");
z.textContent = `(row #${row.rowIndex})`;
row.appendChild(z);
});
```
### Result
{{EmbedLiveSample("Examples")}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmltablerowelement | data/mdn-content/files/en-us/web/api/htmltablerowelement/insertcell/index.md | ---
title: "HTMLTableRowElement: insertCell() method"
short-title: insertCell()
slug: Web/API/HTMLTableRowElement/insertCell
page-type: web-api-instance-method
browser-compat: api.HTMLTableRowElement.insertCell
---
{{APIRef("HTML DOM")}}
The **`HTMLTableRowElement.insertCell()`** method inserts a new
cell ({{HtmlElement("td")}}) into a table row ({{HtmlElement("tr")}}) and returns a
reference to the cell.
> **Note:** `insertCell()` inserts the cell directly into the
> row. The cell does not need to be appended separately
> with {{domxref("Node.appendChild()")}} as would be the case if
> {{domxref("Document.createElement()")}} had been used to create the new
> `<td>` element.
>
> You can not use `insertCell()` to create a new `<th>`
> element though.
## Syntax
```js-nolint
insertCell()
insertCell(index)
```
{{domxref("HTMLTableRowElement")}} is a reference to an HTML {{HtmlElement("tr")}}
element.
### Parameters
- `index` {{optional_inline}}
- : The cell index of the new cell. If `index` is `-1` or equal to the number of cells, the cell is appended as the last cell in the row. If `index` is omitted it defaults to `-1`.
### Return value
An {{domxref("HTMLTableCellElement")}} that references the new
cell.
### Exceptions
- `IndexSizeError` {{domxref("DOMException")}}
- : Thrown if `index` is greater than the number of cells.
## Examples
This example uses {{domxref("HTMLTableElement.insertRow()")}} to append a new row to a
table.
We then use `insertCell(0)` to insert a new cell in the new row. (To be
valid HTML, a `<tr>` must have at least one `<td>`
element.) Finally, we add some text to the cell using
{{domxref("Document.createTextNode()")}} and {{domxref("Node.appendChild()")}}.
### HTML
```html
<table id="my-table">
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
</tr>
</table>
```
### JavaScript
```js
function addRow(tableID) {
// Get a reference to the table
let tableRef = document.getElementById(tableID);
// Insert a row at the end of the table
let newRow = tableRef.insertRow(-1);
// Insert a cell in the row at index 0
let newCell = newRow.insertCell(0);
// Append a text node to the cell
let newText = document.createTextNode("New bottom row");
newCell.appendChild(newText);
}
// Call addRow() with the table's ID
addRow("my-table");
```
### Result
{{EmbedLiveSample("Examples")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLTableElement.insertRow()")}}
- The HTML element representing cells: {{domxref("HTMLTableCellElement")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/rtcsctptransport/index.md | ---
title: RTCSctpTransport
slug: Web/API/RTCSctpTransport
page-type: web-api-interface
browser-compat: api.RTCSctpTransport
---
{{APIRef("WebRTC")}}
The **`RTCSctpTransport`** interface provides information which describes a Stream Control Transmission Protocol (**{{Glossary("SCTP")}}**) transport. This provides information about limitations of the transport, but also provides a way to access the underlying Datagram Transport Layer Security (**{{Glossary("DTLS")}}**) transport over which SCTP packets for all of an {{DOMxRef("RTCPeerConnection")}}'s data channels are sent and received.
You don't create {{DOMxRef("RTCSctpTransport")}} objects yourself; instead, you get access to the `RTCSctpTransport` for a given `RTCPeerConnection` through its **{{DOMxRef("RTCPeerConnection.sctp", "sctp")}}** property.
Possibly the most useful property on this interface is its [`maxMessageSize`](#rtcsctptransport.maxmessagesize) property, which you can use to determine the upper limit on the size of messages you can send over a data channel on the peer connection.
{{InheritanceDiagram}}
## Instance properties
_Also inherits properties from: {{DOMxRef("EventTarget")}}_.
- {{DOMxRef("RTCSctpTransport.maxChannels")}} {{ReadOnlyInline}}
- : An integer value indicating the maximum number of [`RTCDataChannel`](/en-US/docs/Web/API/RTCDataChannel) objects that can be opened simultaneously.
- {{DOMxRef("RTCSctpTransport.maxMessageSize")}} {{ReadOnlyInline}}
- : An integer value indicating the maximum size, in bytes, of a message which can be sent using the {{DOMxRef("RTCDataChannel.send()")}} method.
- {{DOMxRef("RTCSctpTransport.state")}} {{ReadOnlyInline}}
- : A string enumerated value indicating the state of the SCTP transport.
- {{DOMxRef("RTCSctpTransport.transport")}} {{ReadOnlyInline}}
- : An {{DOMxRef("RTCDtlsTransport")}} object representing the {{Glossary("DTLS")}} transport used for the transmission and receipt of data packets.
## Events
Listen to these events using {{domxref("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface.
- {{domxref("RTCSctpTransport.statechange_event", "statechange")}}
- : Sent when the {{DOMxRef("RTCSctpTransport.state")}} changes.
## Instance methods
_This interface has no methods, but inherits methods from: {{DOMxRef("EventTarget")}}._
## Example
TBD
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
- {{DOMxRef("RTCPeerConnection")}}
- {{DOMxRef("RTCPeerConnection.sctp")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcsctptransport | data/mdn-content/files/en-us/web/api/rtcsctptransport/maxchannels/index.md | ---
title: "RTCSctpTransport: maxChannels property"
short-title: maxChannels
slug: Web/API/RTCSctpTransport/maxChannels
page-type: web-api-instance-property
browser-compat: api.RTCSctpTransport.maxChannels
---
{{APIRef("WebRTC")}}
The **`maxChannels`** read-only property of the {{DOMxRef("RTCSctpTransport")}} interface indicates the maximum number of {{DOMxRef("RTCDataChannel")}} objects that can be opened simultaneously.
## Value
An integer value indicating the maximum number of {{DOMxRef("RTCDataChannel")}} objects that can be opened simultaneously, or `null` before the SCTP transport goes into the "connected" [state](/en-US/docs/Web/API/RTCSctpTransport/state).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcsctptransport | data/mdn-content/files/en-us/web/api/rtcsctptransport/maxmessagesize/index.md | ---
title: "RTCSctpTransport: maxMessageSize property"
short-title: maxMessageSize
slug: Web/API/RTCSctpTransport/maxMessageSize
page-type: web-api-instance-property
browser-compat: api.RTCSctpTransport.maxMessageSize
---
{{APIRef("WebRTC")}}
The **`maxMessageSize`** read-only property of the {{DOMxRef("RTCSctpTransport")}} interface indicates the maximum size of a message that can be sent using the {{DOMxRef("RTCDataChannel.send()")}} method.
## Value
An integer value giving the maximum size, in bytes, of a message which can be sent using the {{DOMxRef("RTCDataChannel.send()")}} method.
## Examples
This example shows how you might split up a string into small enough parts to send based on maximum message size.
```js
// Function splits strings to a specified size and returns array.
function splitStringToMax(str, maxLength) {
const result = [];
let i = 0;
while (i < str.length) {
result.push(str.substring(i, i + maxLength));
i += maxLength;
}
return result;
}
const peerConnection = new RTCPeerConnection(options);
const channel = peerConnection.createDataChannel("chat");
channel.onopen = (event) => {
const maximumMessageSize = peerConnection.sctp.maxMessageSize;
const textToSend = "This is my possibly overly long string!";
splitStringToMax(textToSend, maximumMessageSize).forEach((elem) => {
channel.send(elem);
});
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("RTCSctpTransport")}}
- [Understanding message size limits](/en-US/docs/Web/API/WebRTC_API/Using_data_channels#understanding_message_size_limits) section of [Using WebRTC data channels](/en-US/docs/Web/API/WebRTC_API/Using_data_channels)
| 0 |
data/mdn-content/files/en-us/web/api/rtcsctptransport | data/mdn-content/files/en-us/web/api/rtcsctptransport/statechange_event/index.md | ---
title: "RTCSctpTransport: statechange event"
short-title: statechange
slug: Web/API/RTCSctpTransport/statechange_event
page-type: web-api-event
browser-compat: api.RTCSctpTransport.statechange_event
---
{{APIRef("WebRTC")}}
A **`statechange`** event is sent to an {{domxref("RTCSctpTransport")}} to provide notification when the {{domxref("RTCSctpTransport.state")}} property has changed.
<!-- This event is not cancelable and does not bubble. -->
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("statechange", (event) => {});
onstatechange = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
Given an {{domxref("RTCSctpTransport")}}, `transport`, and an `updateStatus()` function that presents connection state information to the user, this code sets up an event handler to let the user know when the transport is connected.
```js
pc.addEventListener(
"statechange",
(event) => {
switch (transport.state) {
case "connected":
updateStatus("Connection started");
break;
}
},
false,
);
```
Using `onstatechange`, it looks like this:
```js
transport.onstatechange = (event) => {
switch (transport.state) {
case "connected":
updateStatus("Connection started");
break;
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
- {{domxref("RTCSctpTransport.state")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcsctptransport | data/mdn-content/files/en-us/web/api/rtcsctptransport/state/index.md | ---
title: "RTCSctpTransport: state property"
short-title: state
slug: Web/API/RTCSctpTransport/state
page-type: web-api-instance-property
browser-compat: api.RTCSctpTransport.state
---
{{APIRef("WebRTC")}}
The **`state`** read-only property of the {{DOMxRef("RTCSctpTransport")}} interface provides information which describes a Stream Control Transmission Protocol ({{Glossary("SCTP")}}) transport state.
## Value
A string whose value is one of the following:
- `connecting`
- : The initial state when the connection is being established.
- `connected`
- : The connection is open for data transmission.
- `closed`
- : The connection is closed and can no longer be used.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("RTCSctpTransport")}}
| 0 |
data/mdn-content/files/en-us/web/api/rtcsctptransport | data/mdn-content/files/en-us/web/api/rtcsctptransport/transport/index.md | ---
title: "RTCSctpTransport: transport property"
short-title: transport
slug: Web/API/RTCSctpTransport/transport
page-type: web-api-instance-property
browser-compat: api.RTCSctpTransport.transport
---
{{APIRef("WebRTC")}}
The **`transport`** read-only property of the {{DOMxRef("RTCSctpTransport")}} interface returns a {{DOMxRef("RTCDtlsTransport")}} object representing the {{Glossary("DTLS")}} transport used for the transmission and receipt of data packets.
## Value
A {{DOMxRef("RTCDtlsTransport")}} object representing the {{Glossary("DTLS")}} transport used for the transmission and receipt of data packets.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("RTCSctpTransport")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/popover_api/index.md | ---
title: Popover API
slug: Web/API/Popover_API
page-type: web-api-overview
browser-compat: api.HTMLElement.popover
---
{{DefaultAPISidebar("Popover API")}}
The **Popover API** provides developers with a standard, consistent, flexible mechanism for displaying popover content on top of other page content. Popover content can be controlled either declaratively using HTML attributes, or via JavaScript.
## Concepts and usage
A very common pattern on the web is to show content over the top of other content, drawing the user's attention to specific important information or actions that need to be taken. This content can take several different names — overlays, popups, popovers, dialogs, etc. We will refer to them as popovers through the documentation. Generally speaking, these can be:
- **modal**, meaning that while a popover is being shown, the rest of the page is rendered non-interactive until the popover is actioned in some way (for example an important choice is made).
- **non-modal**, meaning that the rest of the page can be interacted with while the popover is being shown.
Popovers created using the Popover API are always non-modal. If you want to create a modal popover, a {{htmlelement("dialog")}} element is the right way to go. There is significant overlap between the two — you might for example want to create a popover that persists, but control it using declarative HTML. You can turn a `<dialog>` element into a popover (`<dialog popover>` is perfectly valid) if you want to combine popover control with dialog semantics.
Typical use cases for the popover API include user-interactive elements like action menus, custom "toast" notifications, form element suggestions, content pickers, or teaching UI.
You can create popovers in two different ways:
- Declaratively, via a set of new HTML attributes. A simple popover with a toggle button can be created using the following code:
```html
<button popovertarget="mypopover">Toggle the popover</button>
<div id="mypopover" popover>Popover content</div>
```
- Via a JavaScript API. For example, {{domxref("HTMLElement.togglePopover()")}} can be used to toggle a popover between shown and hidden.
There are also new events to react to a popover being toggled, and CSS features to aid in styling popovers. All the new features are listed below.
See [Using the popover API](/en-US/docs/Web/API/Popover_API/Using) for a detailed guide to using this API.
## HTML attributes
- [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover)
- : A global attribute that turns an element into a popover element; takes a popover state (`"auto"` or `"manual"`) as its value.
- [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget)
- : Turns a {{htmlelement("button")}} or {{htmlelement("input")}} element into a popover control button; takes the ID of the popover element to control as its value.
- [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction)
- : Specifies the action to be performed (`"hide"`, `"show"`, or `"toggle"`) on the popover element being controlled by a control {{htmlelement("button")}} or {{htmlelement("input")}}.
## CSS features
- {{cssxref("::backdrop")}}
- : The `::backdrop` pseudo-element is a full-screen element placed directly behind popover elements, allowing effects to be added to the page content behind the popover(s) if desired (for example blurring it out).
- {{cssxref(":popover-open")}}
- : The `:popover-open` pseudo-class matches a popover element only when it is in the showing state — it can be used to style popover elements when they are showing.
## Interfaces
- {{domxref("ToggleEvent")}}
- : Represents an event notifying the user when a popover element's state toggles between showing and hidden. It is the event object for the {{domxref("HTMLElement.beforetoggle_event", "beforetoggle")}} and {{domxref("HTMLElement.toggle_event", "toggle")}} events, which fire on popovers when their state changes.
## Extensions to other interfaces
### Instance properties
- {{domxref("HTMLElement.popover")}}
- : Gets and sets an element's popover state via JavaScript (`"auto"` or `"manual"`), and can be used for feature detection. Reflects the value of the [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) global HTML attribute.
- {{domxref("HTMLButtonElement.popoverTargetElement")}} and {{domxref("HTMLInputElement.popoverTargetElement")}}
- : Gets and sets the popover element being controlled by the control button. The JavaScript equivalent of the [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget) HTML attribute.
- {{domxref("HTMLButtonElement.popoverTargetAction")}} and {{domxref("HTMLInputElement.popoverTargetAction")}}
- : Gets and sets the action to be performed (`"hide"`, `"show"`, or `"toggle"`) on the popover element being controlled by the control button. Reflects the value of the [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction) HTML attribute.
### Instance methods
- {{domxref("HTMLElement.hidePopover()")}}
- : Hides a popover element by removing it from the top layer and styling it with `display: none`.
- {{domxref("HTMLElement.showPopover()")}}
- : Shows a popover element by adding it to the top layer.
- {{domxref("HTMLElement.togglePopover()")}}
- : Toggles a popover element between the showing and hidden states.
### Events
- `HTMLElement` {{domxref("HTMLElement.beforetoggle_event", "beforetoggle")}} event
- : Fired just before a popover element's state changes between showing and hidden, or vice versa.
- `HTMLElement` {{domxref("HTMLElement.toggle_event", "toggle")}} event
- : Fired just after a popover element's state changes between showing and hidden, or vice versa. This event already existed to signal state changes on {{htmlelement("details")}} elements, and it seemed logical to extend it for popover elements.
## Examples
See our [Popover API examples landing page](https://mdn.github.io/dom-examples/popover-api/) to access the full collection of MDN popover examples.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) HTML global attribute
- [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget) HTML attribute
- [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction) HTML attribute
- [`::backdrop`](/en-US/docs/Web/CSS/::backdrop) CSS pseudo-element
- [`:popover-open`](/en-US/docs/Web/CSS/:popover-open) CSS pseudo-class
| 0 |
data/mdn-content/files/en-us/web/api/popover_api | data/mdn-content/files/en-us/web/api/popover_api/using/index.md | ---
title: Using the Popover API
slug: Web/API/Popover_API/Using
page-type: guide
status:
- experimental
---
{{DefaultAPISidebar("Popover API")}}
The **Popover API** provides developers with a standard, consistent, flexible mechanism for displaying popover content on top of other page content. Popover content can be controlled either declaratively using HTML attributes, or via JavaScript. This article provides a detailed guide to using all of its features.
## Creating declarative popovers
In its simplest form, a popover is created by adding the [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) attribute to the element that you want to contain your popover content. An `id` is also needed to associate the popover with its controls.
```html
<div id="mypopover" popover>Popover content</div>
```
> **Note:** Setting the `popover` attribute with no value is equivalent to setting `popover="auto"`.
Adding this attribute causes the element to be hidden on page load by having {{cssxref("display", "display: none")}} set on it. To show/hide the popover, you need to add some control buttons. You can set a {{htmlelement("button")}} (or {{htmlelement("input")}} of `type="button"`) as a popover control button by giving it a [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget) attribute, the value of which should be the ID of the popover to control:
```html
<button popovertarget="mypopover">Toggle the popover</button>
<div id="mypopover" popover>Popover content</div>
```
The default behavior is for the button to be a toggle button — pressing it repeatedly will toggle the popover between showing and hidden.
If you want to change that behavior, you can use the [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction) attribute — this takes a value of `"hide"`, `"show"`, or `"toggle"`. For example, to create separate show and hide buttons, you could do this:
```html
<button popovertarget="mypopover" popovertargetaction="show">
Show popover
</button>
<button popovertarget="mypopover" popovertargetaction="hide">
Hide popover
</button>
<div id="mypopover" popover>Popover content</div>
```
You can see how the previous code snippet renders in our [Basic declarative popover example](https://mdn.github.io/dom-examples/popover-api/basic-declarative/) ([source](https://github.com/mdn/dom-examples/tree/main/popover-api/basic-declarative)).
> **Note:** If the `popovertargetaction` attribute is omitted, `"toggle"` is the default action that will be performed by a control button.
When a popover is shown, it has `display: none` removed from it and it is put into the {{glossary("top layer")}} so it will sit on top of all other page content.
## auto state, and "light dismiss"
When a popover element is set with `popover` or `popover="auto"` as shown above, it is said to have **auto state**. The two important behaviors to note about auto state are:
- The popover can be "light dismissed" — this means that you can hide the popover by clicking outside it.
- The popover can also be closed, using browser-specific mechanisms such as pressing the <kbd>Esc</kbd> key.
- Usually, only one popover can be shown at a time — showing a second popover when one is already shown will hide the first one. The exception to this rule is when you have nested auto popovers. See the [Nested popovers](#nested_popovers) section for more details.
> **Note:** `popover="auto"` popovers are also dismissed by successful {{domxref("HTMLDialogElement.showModal()")}} and {{domxref("Element.requestFullscreen()")}} calls on other elements in the document. Bear in mind however that calling these methods on a shown popover will result in failure because those behaviors don't make sense on an already-shown popover. You can however call them on an element with the `popover` attribute that isn't currently being shown.
Auto state is useful when you only want to show a single popover at once. Perhaps you have multiple teaching UI messages that you want to show, but don't want the display to start getting cluttered and confusing, or perhaps you are showing status messages where the new status overrides any previous status.
You can see the behavior described above in action in our [Multiple auto popovers example](https://mdn.github.io/dom-examples/popover-api/multiple-auto/) ([source](https://github.com/mdn/dom-examples/tree/main/popover-api/multiple-auto)). Try light dismissing the popovers after they are shown, and see what happens when you try to show both at the same time.
## Using manual popover state
The alternative to auto state is **manual state**, achieved by setting `popover="manual"` on your popover element:
```html
<div id="mypopover" popover="manual">Popover content</div>
```
In this state:
- The popover cannot be "light dismissed", although declarative show/hide/toggle buttons (as seen earlier) will still work.
- Multiple independent popovers can be shown at a time.
You can see this behavior in action in our [Multiple manual popovers example](https://mdn.github.io/dom-examples/popover-api/multiple-manual/) ([source](https://github.com/mdn/dom-examples/tree/main/popover-api/multiple-manual)).
## Showing popovers via JavaScript
You can also control popovers using a JavaScript API.
The {{domxref("HTMLElement.popover")}} property can be used to get or set the [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) attribute. This can be used to create a popover via JavaScript, and is also useful for feature detection. For example:
```js
function supportsPopover() {
return HTMLElement.prototype.hasOwnProperty("popover");
}
```
Similarly:
- {{domxref("HTMLButtonElement.popoverTargetElement")}} and {{domxref("HTMLInputElement.popoverTargetElement")}} provide an equivalent to the [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget) attribute, allowing you to set up the control button(s) for a popover, although the property value taken is a reference to the popover DOM element to control.
- {{domxref("HTMLButtonElement.popoverTargetAction")}} and {{domxref("HTMLInputElement.popoverTargetAction")}} provide an equivalent to the [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction) global HTML attribute, allowing you to specify the action taken by a control button.
Putting these three together, you can programmatically set up a popover and its control button, like so:
```js
const popover = document.getElementById("mypopover");
const toggleBtn = document.getElementById("toggleBtn");
const keyboardHelpPara = document.getElementById("keyboard-help-para");
const popoverSupported = supportsPopover();
if (popoverSupported) {
popover.popover = "auto";
toggleBtn.popoverTargetElement = popover;
toggleBtn.popoverTargetAction = "toggle";
} else {
toggleBtn.style.display = "none";
}
```
You also have several methods to control showing and hiding:
- {{domxref("HTMLElement.showPopover()")}} to show a popover.
- {{domxref("HTMLElement.hidePopover()")}} to hide a popover.
- {{domxref("HTMLElement.togglePopover()")}} to toggle a popover.
For example, you might want to provide the ability to toggle a help popover on and off by clicking a button or pressing a particular key on the keyboard. The first one could be achieved declaratively, or you could do it using JavaScript as shown above.
For the second one, you could create an event handler that programs two separate keys — one to open the popover and one to close it again:
```js
document.addEventListener("keydown", (event) => {
if (event.key === "h") {
if (popover.matches(":popover-open")) {
popover.hidePopover();
}
}
if (event.key === "s") {
if (!popover.matches(":popover-open")) {
popover.showPopover();
}
}
});
```
This example uses {{domxref("Element.matches()")}} to programmatically check whether a popover is currently showing. The {{cssxref(":popover-open")}} pseudo-class matches only popovers that are currently being shown. This is important to avoid the errors that are thrown if you try to show an already-shown popover, or hide an already-hidden popover.
Alternatively, you could program a single key to show _and_ hide the popover like this:
```js
document.addEventListener("keydown", (event) => {
if (event.key === "h") {
popover.togglePopover();
}
});
```
See our [Toggle help UI example](https://mdn.github.io/dom-examples/popover-api/toggle-help-ui/) ([source](https://github.com/mdn/dom-examples/tree/main/popover-api/toggle-help-ui)) to see the popover JavaScript properties, feature detection, and `togglePopover()` method in action.
## Dismissing popovers automatically via a timer
Another common pattern in JavaScript is dismissing popovers automatically after a certain amount of time. You might for example want to create a system of "toast" notifications, where you have multiple actions underway at a time (for example multiple files uploading), and want to show a notification when each one succeeds or fails. For this you'll want to use manual popovers so you can show several at the same time, and use {{domxref("setTimeout()")}} to remove them. A function for handling such popovers might look like so:
```js
function makeToast(result) {
const popover = document.createElement("article");
popover.popover = "manual";
popover.classList.add("toast");
popover.classList.add("newest");
let msg;
if (result === "success") {
msg = "Action was successful!";
popover.classList.add("success");
successCount++;
} else if (result === "failure") {
msg = "Action failed!";
popover.classList.add("failure");
failCount++;
} else {
return;
}
popover.textContent = msg;
document.body.appendChild(popover);
popover.showPopover();
updateCounter();
setTimeout(() => {
popover.hidePopover();
popover.remove();
}, 4000);
}
```
You can also use the {{domxref("HTMLElement.beforetoggle_event", "beforetoggle")}} event to perform a follow-up action when a popover shows or hides. In our example we execute a `moveToastsUp()` function to make the toasts all move up the screen to make way each time a new toast appears:
```js
popover.addEventListener("toggle", (event) => {
if (event.newState === "open") {
moveToastsUp();
}
});
function moveToastsUp() {
const toasts = document.querySelectorAll(".toast");
toasts.forEach((toast) => {
if (toast.classList.contains("newest")) {
toast.style.bottom = `5px`;
toast.classList.remove("newest");
} else {
const prevValue = toast.style.bottom.replace("px", "");
const newValue = parseInt(prevValue) + 50;
toast.style.bottom = `${newValue}px`;
}
});
}
```
See our [Toast popover example](https://mdn.github.io/dom-examples/popover-api/toast-popovers/) ([source](https://github.com/mdn/dom-examples/tree/main/popover-api/toast-popovers)) to see the above example snippets in action, and full comments for explanation.
## Nested popovers
There is an exception to the rule about not displaying multiple auto popovers at once — when they are nested inside one another. In such cases, multiple popovers are allowed to both be open at the same time, due to their relationship with each other. This pattern is supported to enable use cases such as nested popover menus.
There are three different ways to create nested popovers:
1. Direct DOM descendants:
```html
<div popover>
Parent
<div popover>Child</div>
</div>
```
2. Via invoking/control elements:
```html
<div popover>
Parent
<button popovertarget="foo">Click me</button>
</div>
<div popover id="foo">Child</div>
```
3. Via the `anchor` attribute:
```html
<div popover id="foo">Parent</div>
<div popover anchor="foo">Child</div>
```
See our [Nested popover menu example](https://mdn.github.io/dom-examples/popover-api/nested-popovers/) ([source](https://github.com/mdn/dom-examples/tree/main/popover-api/nested-popovers)) for an example. You'll notice that quite a few event handlers have been used to display and hide the subpopover appropriately during mouse and keyboard access, and also to hide both menus when an option is selected from either. Depending on how you handle loading of new content , either in an SPA or multi-page website, some of all of these may not be necessary, but they have been included in this demo for illustrative purposes.
## Styling popovers
The popover API has some related CSS features available that are worth looking at.
In terms of styling the actual popover, you can select all popovers with a simple attribute selector (`[popover]`), or you select popovers that are showing using a new pseudo-class — {{cssxref(":popover-open")}}.
When looking at the first couple of examples linked at the start of the article, you may have noticed that the popovers appear in the middle of the viewport. This is the default styling, achieved like this in the UA stylesheet:
```css
[popover] {
position: fixed;
inset: 0;
width: fit-content;
height: fit-content;
margin: auto;
border: solid;
padding: 0.25em;
overflow: auto;
color: CanvasText;
background-color: Canvas;
}
```
To override the default styles and get the popover to appear somewhere else on your viewport, you would need to override the above styles with something like this:
```css
:popover-open {
width: 200px;
height: 100px;
position: absolute;
inset: unset;
bottom: 5px;
right: 5px;
margin: 0;
}
```
You can see an isolated example of this in our [Popover positioning example](https://mdn.github.io/dom-examples/popover-api/popover-positioning/) ([source](https://github.com/mdn/dom-examples/tree/main/popover-api/popover-positioning)).
The {{cssxref("::backdrop")}} pseudo-element is a full-screen element placed directly behind showing popover elements in the {{glossary("top layer")}}, allowing effects to be added to the page content behind the popover(s) if desired. You might for example want to blur out the content behind the popover to help focus the user's attention on it:
```css
::backdrop {
backdrop-filter: blur(3px);
}
```
See our [Popover blur background example](https://mdn.github.io/dom-examples/popover-api/blur-background/) ([source](https://github.com/mdn/dom-examples/tree/main/popover-api/blur-background)) for an idea of how this renders.
## Animating popovers
Popovers are set to `display: none;` when hidden and `display: block;` when shown, as well as being removed from / added to the {{glossary("top layer")}} and the [accessibility tree](/en-US/docs/Web/Performance/How_browsers_work#building_the_accessibility_tree). Therefore, for popovers to be animated, the {{cssxref("display")}} property needs to be animatable. [Supporting browsers](/en-US/docs/Web/CSS/display#browser_compatibility) animate `display` with a variation on the [discrete animation type](/en-US/docs/Web/CSS/CSS_animated_properties#discrete). Specifically, the browser will flip between `none` and another value of `display` so that the animated content is shown for the entire animation duration. So, for example:
- When animating `display` from `none` to `block` (or another visible `display` value), the value will flip to `block` at `0%` of the animation duration so it is visible throughout.
- When animating `display` from `block` (or another visible `display` value) to `none`, the value will flip to `none` at `100%` of the animation duration so it is visible throughout.
> **Note:** When animating using [CSS transitions](/en-US/docs/Web/CSS/CSS_transitions), [`transition-behavior: allow-discrete`](/en-US/docs/Web/CSS/transition-behavior) needs to be set to enable the above behavior. When animating with [CSS animations](/en-US/docs/Web/CSS/CSS_animations), the above behavior is available by default; an equivalent step is not required.
### Transitioning a popover
When animating popovers with CSS transitions, the following features are required:
- {{CSSxRef("@starting-style")}} at-rule
- : Provides a set of starting values for properties set on the popover that you want to transition from when it is first shown. This is needed to avoid unexpected behavior. By default, CSS transitions only occur when a property changes from one value to another on a visible element; they are not triggered on an element's first style update, or when the `display` type changes from `none` to another type.
- {{CSSxRef("display")}} property
- : Add `display` to the transitions list so that the popover will remain as `display: block` (or another visible `display` value) for the duration of the transition, ensuring the other transitions are visible.
- {{CSSxRef("overlay")}} property
- : Include `overlay` in the transitions list to ensure the removal of the popover from the top layer is deferred until the transition completes, again ensuring the transition is visible.
- {{cssxref("transition-behavior")}} property
- : Set `transition-behavior: allow-discrete` on the `display` and `overlay` transitions (or on the {{cssxref("transition")}} shorthand) to enable discrete transitions on these two properties that are not by default animatable.
Let's have a look at an example so you can see what this looks like:
#### HTML
The HTML contains a {{htmlelement("div")}} element declared to be a popover via the global [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) HTML attribute, and a {{htmlelement("button")}} element designated as the popover's display control:
```html
<button popovertarget="mypopover">Show the popover</button>
<div popover="auto" id="mypopover">I'm a Popover! I should animate.</div>
```
#### CSS
The two popover properties we want to transition are [`opacity`](/en-US/docs/Web/CSS/opacity) and [`transform`](/en-US/docs/Web/CSS/transform). We want the popover to fade in or out while growing or shrinking horizontally. To achieve this, we set a starting state for these properties on the hidden state of the popover element (selected with the `[popover]` [attribute selector](/en-US/docs/Web/CSS/Attribute_selectors)) and an end state for the shown state of the popover (selected via the [`:popover-open`](/en-US/docs/Web/CSS/:popover-open) pseudo-class). We also use the [`transition`](/en-US/docs/Web/CSS/transition) property to define the properties to animate and the animation's duration as the popover gets shown or hidden.
```css
html {
font-family: Arial, Helvetica, sans-serif;
}
/* Transition for the popover itself */
[popover]:popover-open {
opacity: 1;
transform: scaleX(1);
}
[popover] {
font-size: 1.2rem;
padding: 10px;
/* Final state of the exit animation */
opacity: 0;
transform: scaleX(0);
transition:
opacity 0.7s,
transform 0.7s,
overlay 0.7s allow-discrete,
display 0.7s allow-discrete;
/* Equivalent to
transition: all 0.7s allow-discrete; */
}
/* Needs to be after the previous [popover]:popover-open rule
to take effect, as the specificity is the same */
@starting-style {
[popover]:popover-open {
opacity: 0;
transform: scaleX(0);
}
}
/* Transition for the popover's backdrop */
[popover]::backdrop {
background-color: rgb(0 0 0 / 0%);
transition:
display 0.7s allow-discrete,
overlay 0.7s allow-discrete,
background-color 0.7s;
/* Equivalent to
transition: all 0.7s allow-discrete; */
}
[popover]:popover-open::backdrop {
background-color: rgb(0 0 0 / 25%);
}
/* The nesting selector (&) cannot represent pseudo-elements
so this starting-style rule cannot be nested */
@starting-style {
[popover]:popover-open::backdrop {
background-color: rgb(0 0 0 / 0%);
}
}
```
As discussed earlier, we have also:
- Set a starting state for the `transition` inside the `@starting-style` block.
- Added `display` to the list of transitioned properties so that the animated element is visible (set to `display: block`) throughout the popover's entry and exit animations. Without this, the exit animation would not be visible; in effect, the popover would just disappear.
- Added `overlay` to the list of transitioned properties to make sure that the removal of the element from the top layer is deferred until the animation has been completed. The effect of this may not be noticeable for basic animations such as this one, but in more complex cases, omitting this property can result in the element being removed from the overlay before the transition completes.
- Set `allow-discrete` on both properties in the above transitions to enable [discrete transitions](/en-US/docs/Web/CSS/CSS_animated_properties#discrete).
You'll note that we've also included a transition on the [`::backdrop`](/en-US/docs/Web/CSS/::backdrop) appearing behind the popover when it opens, providing a nice darkening animation.
#### Result
The code renders as follows:
{{ EmbedLiveSample("Transitioning a popover", "100%", "200") }}
> **Note:** Because popovers change from `display: none` to `display: block` each time they are shown, the popover transitions from its `@starting-style` styles to its `[popover]:popover-open` styles every time the entry transition occurs. When the popover closes, it transitions from its `[popover]:popover-open` state to the default `[popover]` state.
>
> It is possible for the style transition on entry and exit to be different in such cases. See our [Demonstration of when starting styles are used](/en-US/docs/Web/CSS/@starting-style#demonstration_of_when_starting_styles_are_used) example for a proof of this.
### A popover keyframe animation
When animating a popover with CSS keyframe animations, there are some differences to note:
- You don't provide a `@starting-style`; you include your "to" and "from" `display` values in keyframes.
- You don't explicitly enable discrete animations; there is no equivalent to `allow-discrete` inside keyframes.
- You don't need to set `overlay` inside keyframes either; the `display` animation handles the animation of the popover from shown to hidden.
Let's look at an example.
#### HTML
The HTML contains a {{htmlelement("div")}} element declared as a popover, and a {{htmlelement("button")}} element designated as the popover's display control:
```html
<button popovertarget="mypopover">Show the popover</button>
<div popover="auto" id="mypopover">I'm a Popover! I should animate.</div>
```
#### CSS
We have defined keyframes that specify the desired entry and exit animations, and an entry animation for the backdrop only. Note that it wasn't possible to animate the backdrop fade out — the backdrop is immediately removed from the DOM when the popover is closed, so there is nothing to animate.
```css
html {
font-family: Arial, Helvetica, sans-serif;
}
[popover] {
font-size: 1.2rem;
padding: 10px;
animation: fade-out 0.7s ease-out;
}
[popover]:popover-open {
animation: fade-in 0.7s ease-out;
}
[popover]:popover-open::backdrop {
animation: backdrop-fade-in 0.7s ease-out forwards;
}
/* Animation keyframes */
@keyframes fade-in {
0% {
opacity: 0;
transform: scaleX(0);
}
100% {
opacity: 1;
transform: scaleX(1);
}
}
@keyframes fade-out {
0% {
opacity: 1;
transform: scaleX(1);
/* display needed on the closing animation to keep the popover
visible until the animation ends */
display: block;
}
100% {
opacity: 0;
transform: scaleX(0);
/* display: none not required here because it is the default value
for a closed popover, but including it so the behavior is clear */
display: none;
}
}
@keyframes backdrop-fade-in {
0% {
background-color: rgb(0 0 0 / 0%);
}
100% {
background-color: rgb(0 0 0 / 25%);
}
}
```
#### Result
The code renders as follows:
{{ EmbedLiveSample("A popover keyframe animation", "100%", "200") }}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediastreamtrack/index.md | ---
title: MediaStreamTrack
slug: Web/API/MediaStreamTrack
page-type: web-api-interface
browser-compat: api.MediaStreamTrack
---
{{APIRef("Media Capture and Streams")}}
The **`MediaStreamTrack`** interface of the {{domxref("Media Capture and Streams API", "", "", "nocode")}} represents a single media track within a stream; typically, these are audio or video tracks, but other track types may exist as well.
Some user agents subclass this interface to provide more precise information or functionality, such as {{domxref("CanvasCaptureMediaStreamTrack")}}.
{{InheritanceDiagram}}
## Instance properties
In addition to the properties listed below, `MediaStreamTrack` has constrainable properties which can be set using {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}} and accessed using {{domxref("MediaStreamTrack.getConstraints", "getConstraints()")}} and {{domxref("MediaStreamTrack.getSettings", "getSettings()")}}. See [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints) to learn how to correctly work with constrainable properties. Not doing so correctly will result in your code being unreliable.
- {{domxref("MediaStreamTrack.contentHint")}}
- : A string that may be used by the web application to provide a hint as to what type of content the track contains to guide how it should be treated by API consumers.
- {{domxref("MediaStreamTrack.enabled")}}
- : A Boolean whose value of `true` if the track is enabled, that is allowed to render the media source stream; or `false` if it is disabled, that is not rendering the media source stream but silence and blackness. If the track has been disconnected, this value can be changed but has no more effect.
> **Note:** You can implement standard "mute" functionality by setting `enabled` to `false`. The `muted` property refers to a condition in which there's no media because of a technical issue.
- {{domxref("MediaStreamTrack.id")}} {{ReadOnlyInline}}
- : Returns a string containing a unique identifier (GUID) for the track; it is generated by the browser.
- {{domxref("MediaStreamTrack.kind")}} {{ReadOnlyInline}}
- : Returns a string set to `"audio"` if the track is an audio track and to `"video"`, if it is a video track. It doesn't change if the track is disassociated from its source.
- {{domxref("MediaStreamTrack.label")}} {{ReadOnlyInline}}
- : Returns a string containing a user agent-assigned label that identifies the track source, as in `"internal microphone"`. The string may be left empty and is empty as long as no source has been connected. When the track is disassociated from its source, the label is not changed.
- {{domxref("MediaStreamTrack.muted")}} {{ReadOnlyInline}}
- : Returns a Boolean value indicating whether the track is unable to provide media data due to a technical issue.
> **Note:** You can implement standard "mute" functionality by setting `enabled` to `false`, and unmute the media by setting it back to `true` again.
- {{domxref("MediaStreamTrack.readyState")}} {{ReadOnlyInline}}
- : Returns an enumerated string giving the status of the track. This will be one of the following values:
- `"live"` which indicates that an input is connected and does its best-effort in providing real-time data. In that case, the output of data can be switched on or off using the {{domxref("MediaStreamTrack.enabled", "enabled")}} attribute.
- `"ended"` which indicates that the input is not giving any more data and will never provide new data.
## Instance methods
- {{domxref("MediaStreamTrack.applyConstraints()")}}
- : Lets the application specify the ideal and/or ranges of acceptable values for any number of the available constrainable properties of the `MediaStreamTrack`.
- {{domxref("MediaStreamTrack.clone()")}}
- : Returns a duplicate of the `MediaStreamTrack`.
- {{domxref("MediaStreamTrack.getCapabilities()")}}
- : Returns the a list of constrainable properties available for the `MediaStreamTrack`.
- {{domxref("MediaStreamTrack.getConstraints()")}}
- : Returns a {{domxref('MediaTrackConstraints')}} object containing the currently set constraints for the track; the returned value matches the constraints last set using {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}.
- {{domxref("MediaStreamTrack.getSettings()")}}
- : Returns a {{domxref("MediaTrackSettings")}} object containing the current values of each of the `MediaStreamTrack`'s constrainable properties.
- {{domxref("MediaStreamTrack.stop()")}}
- : Stops playing the source associated to the track, both the source and the track are disassociated. The track state is set to `ended`.
## Events
Listen to these events using {{domxref("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface:
- {{domxref("MediaStreamTrack/ended_event", "ended")}}
- : Sent when playback of the track ends (when the value {{domxref("MediaStreamTrack.readyState", "readyState")}} changes to `ended`).
- {{domxref("MediaStreamTrack/mute_event", "mute")}}
- : Sent to the `MediaStreamTrack` when the value of the {{domxref("MediaStreamTrack.muted", "muted")}} property is changed to `true`, indicating that the track is unable to provide data temporarily (such as when the network is experiencing a service malfunction).
- {{domxref("MediaStreamTrack/unmute_event", "unmute")}}
- : Sent to the track when data becomes available again, ending the `muted` state.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- {{domxref("MediaStream")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/clone/index.md | ---
title: "MediaStreamTrack: clone() method"
short-title: clone()
slug: Web/API/MediaStreamTrack/clone
page-type: web-api-instance-method
browser-compat: api.MediaStreamTrack.clone
---
{{APIRef("Media Capture and Streams")}}
The **`clone()`** method of the {{domxref("MediaStreamTrack")}}
interface creates a duplicate of the `MediaStreamTrack`. This new
`MediaStreamTrack` object is identical except for its unique
{{domxref("MediaStreamTrack.id", "id")}}.
## Syntax
```js-nolint
clone()
```
### Parameters
None.
### Return value
A new {{domxref("MediaStreamTrack")}} instance which is identical to the one
`clone()` was called, except for its new unique
{{domxref("MediaStreamTrack.id", "id")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/mute_event/index.md | ---
title: "MediaStreamTrack: mute event"
short-title: mute
slug: Web/API/MediaStreamTrack/mute_event
page-type: web-api-event
browser-compat: api.MediaStreamTrack.mute_event
---
{{APIRef("Media Capture and Streams")}}
The **`mute`** event is sent to a {{domxref("MediaStreamTrack")}} when the track's source is temporarily unable to provide media data.
When the track is once again able to produce media output, an {{domxref("MediaStreamTrack/unmute_event", "unmute")}} event is sent.
During the time between the `mute` event and the `unmute` event, the value of the track's {{domxref("MediaStreamTrack.muted", "muted")}} property is `true`.
> **Note:** The condition that most people think of as "muted" (that is, a user-toggled state of silencing a track) is actually managed using the {{domxref("MediaStreamTrack.enabled")}} property, for which there are no events.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("mute", (event) => {});
onmute = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
In this example, event handlers are established for the `mute` and {{domxref("MediaStreamTrack.unmute_event", "unmute")}} events in order to detect when the media is not flowing from the source for the {{domxref("MediaStreamTrack")}} referenced by `musicTrack`.
```js
musicTrack.addEventListener(
"mute",
(event) => {
document.getElementById("timeline-widget").style.backgroundColor = "#aaa";
},
false,
);
musicTrack.addEventListener(
"unmute",
(event) => {
document.getElementById("timeline-widget").style.backgroundColor = "#fff";
},
false,
);
```
With these event handlers in place, when the track `musicTrack` enters its {{domxref("MediaStreamTrack.muted", "muted")}} state, the element with the ID `timeline-widget` gets its background color changed to `#aaa`. When the track exits the muted state—detected by the arrival of an `unmute` event—the background color is restored to white.
You can also use the `onmute` event handler property to set up a handler for this event; similarly, the {{domxref("MediaStreamTrack.unmute_event", "onunmute")}} event handler is available for setting up a handler for the `unmute` event. The following example shows this:
```js
musicTrack.onmute = (event) => {
document.getElementById("timeline-widget").style.backgroundColor = "#aaa";
};
musicTrack.onunmute = (event) => {
document.getElementById("timeline-widget").style.backgroundColor = "#fff";
};
```
### Mute tracks through receivers
The following example shows how to mute tracks using receivers.
```js
// Peer 1 (Receiver)
audioTrack.addEventListener("mute", (event) => {
// Do something in UI
});
videoTrack.addEventListener("mute", (event) => {
// Do something in UI
});
// Peer 2 (Sender)
const transceivers = peer.getTransceivers();
const audioTrack = transceivers[0];
audioTrack.direction = "recvonly";
const videoTrack = transceivers[1];
videoTrack.direction = "recvonly";
```
`transceivers` is an array of {{domxref("RTCRtpTransceiver")}} where you can find the audio or video track sent and received. For more information, see the {{domxref("RTCRtpTransceiver.direction", "direction")}} article.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaStreamTrack/unmute_event", "unmute")}} event
- {{domxref("RTCRtpTransceiver.direction", "direction")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/enabled/index.md | ---
title: "MediaStreamTrack: enabled property"
short-title: enabled
slug: Web/API/MediaStreamTrack/enabled
page-type: web-api-instance-property
browser-compat: api.MediaStreamTrack.enabled
---
{{APIRef("Media Capture and Streams")}}
The **`enabled`** property of the
{{domxref("MediaStreamTrack")}} interface is a Boolean value which is
`true` if the track is allowed to render the source stream or
`false` if it is not. This can be used to intentionally mute a
track.
When enabled, a track's data is output from the source to the
destination; otherwise, empty frames are output.
In the case of audio, a disabled track generates frames of silence (that is, frames in
which every sample's value is 0). For video tracks, every frame is filled entirely with
black pixels.
The value of `enabled`, in essence, represents what a typical user would
consider the muting state for a track, whereas the {{domxref("MediaStreamTrack.muted",
"muted")}} property indicates a state in which the track is temporarily unable to output
data, such as a scenario in which frames have been lost in transit.
> **Note:** If the track has been disconnected, the value of this property
> can be changed, but has no effect.
## Value
When `true`, `enabled` indicates that the track is permitted to
render its actual media to the output. When `enabled` is set to
`false`, the track only generates empty frames.
Empty audio frames have every sample's value set to 0. Empty video frames have every
pixel set to black.
> **Note:** When implementing a mute/unmute feature, you should use the
> `enabled` property.
## Usage notes
If the {{domxref("MediaStreamTrack")}} represents the video input from a camera,
disabling the track by setting `enabled` to `false` also updates
device activity indicators to show that the camera is not currently recording or
streaming. For example, the green "in use" light next to the camera in iMac and MacBook
computers turns off while the track is muted in this way.
## Example
This example demonstrates a {{domxref("Element/click_event", "click")}} event handler for a pause button.
```js
pauseButton.onclick = (evt) => {
const newState = !myAudioTrack.enabled;
pauseButton.innerHTML = newState ? "▶️" : "⏸️";
myAudioTrack.enabled = newState;
};
```
This creates a variable, `newState`, which is the opposite of the current
value of `enabled`, then uses that to select either the Emoji character for
the "play" icon or the character for the "pause" icon as the new
{{domxref("Element.innerHTML", "innerHTML")}} of the pause button's element.
Finally, the new value of `enabled` is saved, making the change take effect.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- {{domxref("MediaStream")}}
- {{domxref("MediaStreamTrack")}}
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/stop/index.md | ---
title: "MediaStreamTrack: stop() method"
short-title: stop()
slug: Web/API/MediaStreamTrack/stop
page-type: web-api-instance-method
browser-compat: api.MediaStreamTrack.stop
---
{{APIRef("Media Capture and Streams")}}
The **`stop()`** method of the {{domxref("MediaStreamTrack")}} interface stops the track.
## Syntax
```js-nolint
stop()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Description
Calling `stop()` tells the {{glossary("user agent")}} that the track's
source—whatever that source may be, including files, network streams, or a local camera
or microphone—is no longer needed by the {{domxref("MediaStreamTrack")}}. Since multiple
tracks may use the same source (for example, if two tabs are using the device's
microphone), the source itself isn't necessarily immediately stopped. It is instead
disassociated from the track and the track object is stopped. Once no media tracks are
using the source, the source may actually be completely stopped.
Immediately after calling `stop()`, the
{{domxref("MediaStreamTrack.readyState", "readyState")}} property is set to
`ended`. Note that the [`ended`](/en-US/docs/Web/API/MediaStreamTrack/ended_event) event will not be fired in this situation.
## Examples
### Stopping a video stream
In this example, we see a function which stops a streamed video by calling
`stop()` on every track on a given {{HTMLElement("video")}}.
```js
function stopStreamedVideo(videoElem) {
const stream = videoElem.srcObject;
const tracks = stream.getTracks();
tracks.forEach((track) => {
track.stop();
});
videoElem.srcObject = null;
}
```
This works by obtaining the video element's stream from its
{{domxref("HTMLMediaElement.srcObject", "srcObject")}} property. Then the stream's track
list is obtained by calling its {{domxref("MediaStream.getTracks", "getTracks()")}}
method. From there, all that remains to do is to iterate over the track list using
{{jsxref("Array.forEach", "forEach()")}} and calling each track's `stop()`
method.
Finally, `srcObject` is set to `null` to sever the link to the
{{domxref("MediaStream")}} object so it can be released.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("MediaStreamTrack")}}, the interface it belongs to.
- {{domxref("MediaStreamTrack.readyState")}}
- {{domxref("MediaStreamTrack/ended_event", "ended")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/getconstraints/index.md | ---
title: "MediaStreamTrack: getConstraints() method"
short-title: getConstraints()
slug: Web/API/MediaStreamTrack/getConstraints
page-type: web-api-instance-method
browser-compat: api.MediaStreamTrack.getConstraints
---
{{APIRef("Media Capture and Streams")}}
The **`getConstraints()`** method of
the {{domxref("MediaStreamTrack")}} interface returns a
{{domxref('MediaTrackConstraints')}} object containing the set of constraints most
recently established for the track using a prior call to
{{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}. These
constraints indicate values and ranges of values that the website or application has
specified are required or acceptable for the included constrainable properties.
Constraints can be used to ensure that the media meets certain guidelines you prefer.
For example, you may prefer high definition video but require that the frame rate be a
little low to help keep the data rate low enough not overtax the network. Constraints
can also specify ideal and/or acceptable sizes or ranges of sizes. See [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints) for details on how to work with constrainable properties.
## Syntax
```js-nolint
getConstraints()
```
### Parameters
None.
### Return value
A {{domxref('MediaTrackConstraints')}} object which indicates the constrainable
properties the website or app most recently set using
{{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}}. The properties
in the returned object are listed in the same order as when they were set, and only
properties specifically set by the site or app are included.
> **Note:** The returned set of constraints doesn't necessarily describe
> the actual state of the media. Even if any of the constraints couldn't be met, they
> are still included in the returned object as originally set by the site's code. To get
> the currently active settings for all constrainable properties, you should instead
> call {{domxref("MediaStreamTrack.getSettings", "getSettings()")}}.
## Examples
This example obtains the current constraints for a track, sets the
{{domxref("MediaTrackConstraints.facingMode", "facingMode")}}, and applies the updated
constraints.
```js
function switchCameras(track, camera) {
const constraints = track.getConstraints();
constraints.facingMode = camera;
track.applyConstraints(constraints);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/unmute_event/index.md | ---
title: "MediaStreamTrack: unmute event"
short-title: unmute
slug: Web/API/MediaStreamTrack/unmute_event
page-type: web-api-event
browser-compat: api.MediaStreamTrack.unmute_event
---
{{APIRef("Media Capture and Streams")}}
The **`unmute`** event is sent to a {{domxref("MediaStreamTrack")}} when the track's source is once again able to provide media data after a period of not being able to do so.
This ends the {{domxref("MediaStreamTrack.muted", "muted")}} state that began with the {{domxref("MediaStreamTrack/mute_event", "mute")}} event.
> **Note:** The condition that most people think of as "muted" (that is, a user-controllable way to silence a track) is actually managed using the {{domxref("MediaStreamTrack.enabled")}} property, for which there are no events.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("unmute", (event) => {});
onunmute = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
In this example, event handlers are established for the {{domxref("MediaStreamTrack/mute_event", "mute")}} and `unmute` events in order to detect when the media is not flowing from the source for the {{domxref("MediaStreamTrack")}} stored in the variable `musicTrack`.
```js
musicTrack.addEventListener(
"mute",
(event) => {
document.getElementById("timeline-widget").style.backgroundColor = "#aaa";
},
false,
);
musicTrack.addEventListener(
"unmute",
(event) => {
document.getElementById("timeline-widget").style.backgroundColor = "#fff";
},
false,
);
```
With these event handlers in place, when the track `musicTrack` enters its {{domxref("MediaStreamTrack.muted", "muted")}} state, the element with the ID `timeline-widget` gets its background color changed to `#aaa`. When the track exits the muted state—detected by the arrival of an `unmuted` event—the background color is restored to white.
You can also use the `onunmute` event handler property to set up a handler for this event; similarly, the {{domxref("MediaStreamTrack.mute_event", "onmute")}} event handler is available for setting up a handler for the `mute` event. The following example shows this:
```js
musicTrack.onmute = (event) => {
document.getElementById("timeline-widget").style.backgroundColor = "#aaa";
};
musicTrack.mute = (event) => {
document.getElementById("timeline-widget").style.backgroundColor = "#fff";
};
```
### Unmute tracks through receivers
The following example shows how to unmute tracks using receivers.
```js
// Peer 1 (Receiver)
audioTrack.addEventListener("unmute", (event) => {
// Do something in UI
});
videoTrack.addEventListener("unmute", (event) => {
// Do something in UI
});
// Peer 2 (Sender)
const transceivers = peer.getTransceivers();
const audioTrack = transceivers[0];
audioTrack.direction = "sendrecv";
const videoTrack = transceivers[1];
videoTrack.direction = "sendrecv";
```
`transceivers` is an array of {{domxref("RTCRtpTransceiver")}} where you can find the audio or video track sent and received. For more information, see the {{domxref("RTCRtpTransceiver.direction", "direction")}} article.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("MediaStreamTrack/mute_event", "mute")}} event
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/muted/index.md | ---
title: "MediaStreamTrack: muted property"
short-title: muted
slug: Web/API/MediaStreamTrack/muted
page-type: web-api-instance-property
browser-compat: api.MediaStreamTrack.muted
---
{{APIRef("Media Capture and Streams")}}
The **`muted`** read-only property of the
{{domxref("MediaStreamTrack")}} interface returns a boolean value
indicating whether or not the track is currently unable to provide media output.
> **Note:** To implement a way for users to mute and unmute a track, use the
> {{domxref("MediaStreamTrack.enabled", "enabled")}} property. When a track is disabled
> by setting `enabled` to `false`, it generates only empty frames
> (audio frames in which every sample is 0, or video frames in which every pixel is
> black).
## Value
A boolean which is `true` if the track is currently muted, or
`false` if the track is currently unmuted.
> **Note:** When possible, avoid polling `muted` to monitor the track's muting status.
> Instead, add event listeners for the {{domxref("MediaStreamTrack.mute_event", "mute")}} and {{domxref("MediaStreamTrack.unmute_event", "unmute")}} events.
## Examples
This example counts the number of tracks in an array of {{domxref("MediaStreamTrack")}}
objects which are currently muted.
```js
let mutedCount = 0;
trackList.forEach((track) => {
if (track.muted) {
mutedCount += 1;
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/applyconstraints/index.md | ---
title: "MediaStreamTrack: applyConstraints() method"
short-title: applyConstraints()
slug: Web/API/MediaStreamTrack/applyConstraints
page-type: web-api-instance-method
browser-compat: api.MediaStreamTrack.applyConstraints
---
{{APIRef("Media Capture and Streams")}}
The **`applyConstraints()`** method of the {{domxref("MediaStreamTrack")}} interface applies a set of constraints to the track; these constraints let the website or app establish ideal values and acceptable ranges of values for the constrainable properties of the track, such as frame rate, dimensions, echo cancellation, and so forth.
Constraints can be used to ensure that the media meets certain guidelines you prefer.
For example, you may prefer high-density video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network.
Constraints can also specify ideal and/or acceptable sizes or ranges of sizes.
See [Applying constraints](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints#applying_constraints) in [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints) for more information on how to apply your preferred constraints.
## Syntax
```js-nolint
applyConstraints()
applyConstraints(constraints)
```
### Parameters
- `constraints` {{optional_inline}}
- : A {{domxref("MediaTrackConstraints")}} object listing the constraints to apply to the track's constrainable properties; any existing constraints are replaced with the new values specified, and any constrainable properties not included are restored to their default constraints.
If this parameter is omitted, all currently set custom constraints are cleared.
This object represents the basic set of constraints that must apply for the {{jsxref("Promise")}} to resolve.
The object may contain an advanced property containing an array of additional `MediaTrackConstraints` objects, which are treated as exact requires.
### Return value
A {{jsxref("Promise")}} which resolves when the constraints have been successfully applied.
If the constraints cannot be applied, the promise is rejected with a {{domxref("OverconstrainedError")}} that is a {{domxref("DOMException")}} whose name is `OverconstrainedError` with additional parameters, and, to indicate that the constraints could not be met.
This can happen if the specified constraints are too strict to find a match when attempting to configure the track.
## Examples
The following shows how to specify a basic and advanced set of constraints.
It specifies that the page or web app needs a width between 640 and 1280 and a height between 480 and 720, with the later number in each pair being preferred.
The advanced property further specifies that an image size of 1920 by 1280 is the preferred or an aspect ratio of 1.333 if that is not available.
Note that these constraints also illustrate what the spec refers to as a _backoff strategy_.
```js
const constraints = {
width: { min: 640, ideal: 1280 },
height: { min: 480, ideal: 720 },
advanced: [{ width: 1920, height: 1280 }, { aspectRatio: 1.333 }],
};
navigator.mediaDevices.getUserMedia({ video: true }).then((mediaStream) => {
const track = mediaStream.getVideoTracks()[0];
track
.applyConstraints(constraints)
.then(() => {
// Do something with the track such as using the Image Capture API.
})
.catch((e) => {
// The constraints could not be satisfied by the available devices.
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [MediaStream Image Capture API](/en-US/docs/Web/API/MediaStream_Image_Capture_API)
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/id/index.md | ---
title: "MediaStreamTrack: id property"
short-title: id
slug: Web/API/MediaStreamTrack/id
page-type: web-api-instance-property
browser-compat: api.MediaStreamTrack.id
---
{{APIRef("Media Capture and Streams")}}
The **`id`** read-only property of the {{domxref("MediaStreamTrack")}} interface returns a
string containing a unique identifier (GUID) for the track, which is
generated by the {{glossary("user agent")}}.
## Syntax
```js-nolint
const id = track.id
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/readystate/index.md | ---
title: "MediaStreamTrack: readyState property"
short-title: readyState
slug: Web/API/MediaStreamTrack/readyState
page-type: web-api-instance-property
browser-compat: api.MediaStreamTrack.readyState
---
{{APIRef("Media Capture and Streams")}}
The **`readyState`** read-only property of the {{domxref("MediaStreamTrack")}} interface returns an enumerated value giving the status of the track.
## Value
It takes one of the following values:
- `"live"` which indicates that an input is connected and does its
best-effort in providing real-time data. In that case, the output of data can be
switched on or off using the {{domxref("MediaStreamTrack.enabled")}} property.
- `"ended"` which indicates that the input is not giving any more data and
will never provide new data.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
- The {{domxref("MediaStreamTrack.ended_event", "ended")}} event
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/ended_event/index.md | ---
title: "MediaStreamTrack: ended event"
short-title: ended
slug: Web/API/MediaStreamTrack/ended_event
page-type: web-api-event
browser-compat: api.MediaStreamTrack.ended_event
---
{{APIRef("Media Capture and Streams")}}
The **`ended`** event of the {{domxref("MediaStreamTrack")}} interface is fired when playback or streaming has stopped because the end of the media was reached or because no further data is available.
This event is not cancelable and does not bubble.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("ended", (event) => {});
onended = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Usage notes
`ended` events fire when the media stream track's source permanently stops sending data on the stream. There are various ways this can happen, including:
- There is no more data left to send.
- The user revoked the permissions needed for the data to be sent.
- The hardware generating the source data has been removed or ejected.
- A remote peer has permanently stopped sending data; pausing media _does not_ generate an `ended` event.
## Examples
This example sets up an event handler for the `ended` event, which changes an on-screen icon to indicate that the track is no longer active.
```js
track.addEventListener("ended", () => {
let statusElem = document.getElementById("status-icon");
statusElem.src = "/images/stopped-icon.png";
});
```
You can also set up the event handler using the `onended` property:
```js
track.onended = () => {
let statusElem = document.getElementById("status-icon");
statusElem.src = "/images/stopped-icon.png";
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTMLMediaElement {{domxref("HTMLMediaElement.playing_event", 'playing')}} event
- The HTMLMediaElement {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} event
- The HTMLMediaElement {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} event
- {{HTMLElement("audio")}}
- {{HTMLElement("video")}}
- The HTMLMediaElement {{domxref("HTMLMediaElement.ended_event", 'ended')}} event
- The AudioScheduledSourceNode {{domxref("AudioScheduledSourceNode.ended_event", 'ended')}} event
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/label/index.md | ---
title: "MediaStreamTrack: label property"
short-title: label
slug: Web/API/MediaStreamTrack/label
page-type: web-api-instance-property
browser-compat: api.MediaStreamTrack.label
---
{{APIRef("Media Capture and Streams")}}
The **`label`** read-only property of the {{domxref("MediaStreamTrack")}} interface returns a string containing a {{glossary("user agent")}}-assigned label that identifies the track source, as in `"internal microphone"`.
The string may be left empty and is empty as long as no source has been connected.
When the track is disassociated from its source, the label is not changed.
## Syntax
```js-nolint
const label = track.label
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrack | data/mdn-content/files/en-us/web/api/mediastreamtrack/getcapabilities/index.md | ---
title: "MediaStreamTrack: getCapabilities() method"
short-title: getCapabilities()
slug: Web/API/MediaStreamTrack/getCapabilities
page-type: web-api-instance-method
browser-compat: api.MediaStreamTrack.getCapabilities
---
{{APIRef("Media Capture and Streams")}}
The **`getCapabilities()`** method of
the {{domxref("MediaStreamTrack")}} interface returns a
`MediaTrackCapabilities` object which specifies the values or range of
values which each constrainable property, based upon the platform and {{Glossary("user agent")}}.
Once you know what the browser's capabilities are, your script can use
{{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}} to ask for the
track to be configured to match ideal or acceptable settings. See [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints) for details on how to work with constrainable properties.
## Syntax
```js-nolint
getCapabilities()
```
### Parameters
None.
### Return value
A `MediaTrackCapabilities` object which specifies the value or range of values which are supported for each of the user agent's supported constrainable properties, containing the following members:
- `deviceId`
- : A [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) object containing the device ID.
- `groupId`
- : A [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) object containing a group ID.
- `autoGainControl`
- : A [`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) object reporting if the source can do auto gain control.
If the feature can be controlled by a script the source will report both true and false as possible values.
- `channelCount`
- : A [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) containing the channel count or range of channel counts.
- `echoCancellation`
- : A [`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) object reporting if the source can do echo cancellation.
If the feature can be controlled by a script the source will report both true and false as possible values.
- `latency`
- : A [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) containing the latency or range of latencies.
- `noiseSuppression`
- : A [`ConstrainBoolean`](/en-US/docs/Web/API/MediaTrackConstraints#constrainboolean) object reporting if the source can do noise suppression.
If the feature can be controlled by a script the source will report both true and false as possible values.
- `sampleRate`
- : A [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) containing the sample rate or range of sample rates.
- `sampleSize`
- : A [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) containing the sample size or range of sample sizes.
- `aspectRatio`
- : A [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) containing the video aspect ratio (width in pixels divided by height in pixels) or range of aspect ratios.
- `facingMode`
- : A [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) object containing the camera facing mode. A camera may report multiple facings, for example "left" and "user".
- `frameRate`
- : A [`ConstrainDouble`](/en-US/docs/Web/API/MediaTrackConstraints#constraindouble) containing the frame rate or range of frame rates which are acceptable.
- `height`
- : A [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) containing the video height or range of heights in pixels.
- `width`
- : A [`ConstrainULong`](/en-US/docs/Web/API/MediaTrackConstraints#constrainulong) containing the video width or range of widths in pixels.
- `resizeMode`
- : A [`ConstrainDOMString`](/en-US/docs/Web/API/MediaTrackConstraints#constraindomstring) object containing the mode or an array of modes the UA can use to derive the resolution of the video track.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("InputDeviceInfo.getCapabilities()")}}, which also return a `MediaTrackCapabilities` object.
| 0 |
Subsets and Splits