RTCPeerConnection: getIdentityAssertion() method - Web APIs

RTCPeerConnection: getIdentityAssertion() method
================================================

 The **`RTCPeerConnection.getIdentityAssertion()`** method
 initiates the gathering of an identity assertion. This has an effect only if the
 `signalingState` is not
 `"closed"`.

 The method returns a JavaScript `Promise` which resolves to an
 identity assertion encoded as a string.

 It is not expected for the application dealing with the `RTCPeerConnection`:
 this is automatically done; an explicit call only allows to anticipate the need.

Syntax
------

```js
getIdentityAssertion()
```

*There is neither parameter nor return value for this method.*

Example
-------

```js
const pc = new RTCPeerConnection();

pc.setIdentityProvider("developer.mozilla.org");
const assertion = await pc.getIdentityAssertion();
```

Specifications
--------------

| Specification |
| --- |
| Identity for WebRTC 1.0 # dom-rtcpeerconnection-getidentityassertion |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC


RTCPeerConnection: getReceivers() method - Web APIs

RTCPeerConnection: getReceivers() method
========================================

 The **`RTCPeerConnection.getReceivers()`** method returns an array of `RTCRtpReceiver` objects, each of which represents one RTP receiver.
 Each RTP receiver manages the reception and decoding of data for a `MediaStreamTrack` on an `RTCPeerConnection`.

Syntax
------

```js
getReceivers()
```

### Return value

 An array of `RTCRtpReceiver` objects, one for each track on the connection.
 The array is empty if there are no RTP receivers on the connection.

The order of the returned `RTCRtpReceiver` instances is not defined by the specification, and may change from one call to `getReceivers()` to the next.

The array does not include receivers associated with transceivers that have been stopped (following offer/answer).

Example
-------

tbd

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-getreceivers |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* `RTCRtpSender`


RTCPeerConnection: pendingLocalDescription property - Web APIs

RTCPeerConnection: pendingLocalDescription property
===================================================

 The read-only property
 **`RTCPeerConnection.pendingLocalDescription`** returns an
 `RTCSessionDescription` object describing a pending configuration change
 for the local end of the connection. This does not describe the connection as it
 currently stands, but as it may exist in the near future. Use
 `RTCPeerConnection.currentLocalDescription` or
 `RTCPeerConnection.localDescription` to get the current state of the
 endpoint. For details on the difference, see
 Pending and current descriptions in the WebRTC Connectivity page.

Value
-----

 If a local description change is in progress, this is an
 `RTCSessionDescription` describing the proposed configuration. Otherwise,
 this returns `null`.

Examples
--------

 This example looks at the `pendingLocalDescription` to determine whether or
 not there's a description change being processed.

```js
const pc = new RTCPeerConnection();
// ...
const sd = pc.pendingLocalDescription;
if (sd) {
  // There's a description change underway!
} else {
  // No description change pending
}
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-pendinglocaldesc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** The addition of `pendingLocalDescription` and
 `currentLocalDescription` to
 the WebRTC spec is relatively recent. In browsers which don't support them, only
 `localDescription` is available.

See also
--------

* `RTCPeerConnection.setLocalDescription()`,
 `RTCPeerConnection.currentLocalDescription`,
 `RTCPeerConnection.localDescription`
* `RTCPeerConnection.setRemoteDescription()`,
 `RTCPeerConnection.remoteDescription`,
 `RTCPeerConnection.pendingRemoteDescription`,
 `RTCPeerConnection.currentRemoteDescription`
* WebRTC


RTCPeerConnection: removeStream() method - Web APIs

RTCPeerConnection: removeStream() method
========================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The
 **`RTCPeerConnection.removeStream()`** method removes a
 `MediaStream` as a local source of audio or video. If the negotiation
 already happened, a new one will be needed for the remote peer to be able to use it.
 Because this method has been deprecated, you should instead use
 `removeTrack()` if your target browser
 versions have implemented it.

 If the `signalingState` is set to
 `"closed"`, an `InvalidStateError` is raised. If the
 `signalingState` is set to
 `"stable"`, the event `negotiationneeded` is sent on the
 `RTCPeerConnection`.

Syntax
------

```js
removeStream(mediaStream)
```

### Parameters

`mediaStream`

A `MediaStream` specifying the stream to remove from the connection.

### Return value

`undefined`.

Example
-------

```js
let pc;
let videoStream;
navigator.getUserMedia({ video: true }, (stream) => {
  pc = new RTCPeerConnection();
  videoStream = stream;
  pc.addStream(stream);
});
document.getElementById("closeButton").addEventListener(
  "click",
  (event) => {
    pc.removeStream(videoStream);
    pc.close();
  },
  false,
);
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* `RTCPeerConnection.removeTrack()`
* `RTCPeerConnection.addTrack()`
* `RTCPeerConnection.addStream()`


RTCPeerConnection: setRemoteDescription() method - Web APIs

RTCPeerConnection: setRemoteDescription() method
================================================

 The `RTCPeerConnection`
 method **`setRemoteDescription()`** sets the specified
 session description as the remote peer's current offer or answer. The description
 specifies the properties of the remote end of the connection, including the media
 format. The method takes a single parameter—the session description—and it
 returns a `Promise` which is fulfilled once the description has been
 changed, asynchronously.

 This is typically called after receiving an offer or answer from another peer over the
 signaling server. Keep in mind that if `setRemoteDescription()` is called
 while a connection is already in place, it means renegotiation is underway (possibly
 to adapt to changing network conditions).

 Because descriptions will be exchanged until the two peers agree on a configuration,
 the description submitted by calling `setRemoteDescription()` does not
 immediately take effect. Instead, the current connection configuration remains in
 place until negotiation is complete. Only then does the agreed-upon configuration take
 effect.

Syntax
------

```js
setRemoteDescription(sessionDescription)
```

### Parameters

`sessionDescription`

 An `RTCSessionDescriptionInit` or
 `RTCSessionDescription` which specifies the remote peer's current
 offer or answer. This value is an offer or answer received from the remote
 peer through your implementation of

 The `sessionDescription` parameter is technically of type
 `RTCSessionDescriptionInit`, but because
 `RTCSessionDescription` serializes to be indistinguishable from
 `RTCSessionDescriptionInit`, you can also pass in an
 `RTCSessionDescription`. This lets you simplify code such as the following:

```js
myPeerConnection
  .setRemoteDescription(new RTCSessionDescription(description))
  .then(() => createMyStream());
```

to be:

```js
myPeerConnection.setRemoteDescription(description).then(() => createMyStream());
```

 Using
 `async`/`await`
 syntax, you can further simplify this to:

```js
await myPeerConnection.setRemoteDescription(description);
createMyStream();
```

Since it's unnecessary, the `RTCSessionDescription()` constructor is deprecated.

### Return value

 A `Promise` which is fulfilled once the value of the connection's
 `remoteDescription` is
 successfully changed or rejected if the change cannot be applied (for example, if the
 specified description is incompatible with one or both of the peers on the
 connection). The promise fulfillment handler receives no input parameters.

**Note:** The process of changing descriptions actually involves
 intermediary steps handled by the WebRTC layer to ensure that an active connection
 can be changed without losing the connection if the change does not succeed. See
 Pending and current descriptions in the WebRTC Connectivity page for more details on this process.

### Exceptions

 The following exceptions are reported to the rejection handler for the promise returned
 by `setRemoteDescription()`:

`InvalidAccessError` `DOMException`

Returned if the content of the description is invalid.

`InvalidStateError` `DOMException`

 Returned if the `RTCPeerConnection` is closed, or it's in a state that is not
 compatible with the specified description's
 `type`. For example, this exception is thrown if the
 `type` is `rollback` and the signaling state is one of
 `stable`, `have-local-pranswer`, or
 `have-remote-pranswer` because you cannot
 roll back a connection that's either fully established or is in the final stage of
 becoming connected.

`OperationError` `DOMException`

Returned if an error does not match the ones specified here. This includes identity validation errors.

`RTCError` `DOMException`

 Returned with the `errorDetail` set to `sdp-syntax-error` if the
 SDP specified by `RTCSessionDescription.sdp` is not valid. The
 error object's `sdpLineNumber` property
 indicates the line number within the SDP on which the syntax error was detected.

`TypeError`

 Returned if the specified `RTCSessionDescriptionInit` or
 `RTCSessionDescription` object is missing the
 `type` property, or no description
 parameter was provided at all.

Usage notes
-----------

 When you call `setRemoteDescription()`, the ICE agent checks to make sure
 the `RTCPeerConnection` is in either the `stable` or
 `have-remote-offer` `signalingState`. These states indicate that either an existing connection is being
 renegotiated or that an offer previously specified by an earlier call to
 `setRemoteDescription()` is to be replaced with the new offer. In either of
 those two cases, we're at the beginning of the negotiation process, and the offer is
 set as the remote description.

 On the other hand, if we're in the middle of an ongoing negotiation and an offer is
 passed into `setRemoteDescription()`, the ICE agent automatically begins an
 ICE rollback in order to return the connection to a stable signaling state, then, once
 the rollback is completed, sets the remote description to the specified offer. This
 begins a new negotiation session, with the newly-established offer as the starting
 point.

 Upon starting the new negotiation with the newly-established offer, the local peer is
 now the callee, even if it was previously the caller. This happens instead of throwing
 an exception, thereby reducing the number of potential errors which might occur, and
 simplifies the processing you need to do when you receive an offer, by eliminating the
 need to handle the offer/answer process differently depending on whether the local
 peer is the caller or callee.

**Note:** Earlier implementations of WebRTC would throw an exception
 if an offer was set outside a `stable` or
 `have-remote-offer` state.

Deprecated syntax
-----------------

 In older code and documentation, you may see a callback-based version of this function
 used. This has been deprecated and its use is *strongly* discouraged. You
 should update any existing code to use the `Promise`-based version of
 `setRemoteDescription()` instead. The parameters for the older form of
 `setRemoteDescription()` are described below, to aid in updating existing
 code.

```js
pc.setRemoteDescription(sessionDescription, successCallback, errorCallback);
```

### Parameters

`successCallback`
Deprecated

 A JavaScript `Function` which accepts no input parameters to be called
 once the description has been successfully set. At that time, the offer can be
 sent to a remote peer via the signaling server.

`errorCallback`
Deprecated

 A function matching the signature `RTCPeerConnectionErrorCallback`
 which gets called if the description can't be set. It is passed a single
 `DOMException` object explaining why the request failed.

 This deprecated form of the method returns instantaneously without waiting for the
 actual setting to be done: in case of success, the `successCallback` will
 be called; in case of failure, the `errorCallback` will be called.

### Exceptions

 When using the deprecated callback-based version of
 `setRemoteDescription()`, the following exceptions may occur:

`InvalidStateError`
Deprecated

 The connection's `signalingState`
 is `"closed"`, indicating that the connection is not currently open, so
 negotiation cannot take place.

`InvalidSessionDescriptionError`
Deprecated

 The `RTCSessionDescription` specified by the
 `sessionDescription` parameter is invalid.

Examples
--------

 Here we see a function which handles an offer received from the remote peer. This code
 is derived from the example and tutorial in the article Signaling and video calling; take a look at that for more details and a more in-depth
 explanation of what's going on.

```js
function handleOffer(msg) {
  createMyPeerConnection();

  myPeerConnection
    .setRemoteDescription(msg.description)
    .then(() => navigator.mediaDevices.getUserMedia(mediaConstraints))
    .then((stream) => {
      document.getElementById("local\_video").srcObject = stream;
      return myPeerConnection.addStream(stream);
    })
    .then(() => myPeerConnection.createAnswer())
    .then((answer) => myPeerConnection.setLocalDescription(answer))
    .then(() => {
      // Send the answer to the remote peer using the signaling server
    })
    .catch(handleGetUserMediaError);
}
```

 After creating our `RTCPeerConnection` and saving it as
 `myPeerConnection`, we pass the description included in the received offer
 message, `msg`, directly into `setRemoteDescription()` to tell
 the user agent's WebRTC layer what configuration the caller has proposed using. When
 our promise fulfillment handler is called, indicating that this has been done, we
 create a stream, add it to the connection, then create an SDP answer and call
 `setLocalDescription()` to set
 that as the configuration at our end of the call before forwarding that answer to the
 caller.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-setremotedescription |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* `RTCPeerConnection.remoteDescription`,
 `RTCPeerConnection.pendingRemoteDescription`,
 `RTCPeerConnection.currentRemoteDescription`


RTCPeerConnection: createOffer() method - Web APIs

RTCPeerConnection: createOffer() method
=======================================

 The **`createOffer()`** method
 of the `RTCPeerConnection` interface
 initiates the creation of an SDP offer
 for the purpose of starting a new WebRTC connection to a remote peer.
 The SDP offer includes information
 about any `MediaStreamTrack` objects
 already attached to the WebRTC session, codec, and options supported by the browser,
 and any candidates already gathered by the ICE agent,
 for the purpose of being sent over the signaling channel
 to a potential peer
 to request a connection
 or to update the configuration of an existing connection.

 The return value is a `Promise` which, when the offer has been created, is
 resolved with a `RTCSessionDescription` object containing the newly-created
 offer.

Syntax
------

```js
createOffer()
createOffer(options)

createOffer(successCallback, failureCallback) // deprecated
createOffer(successCallback, failureCallback, options) // deprecated
```

### Parameters

`options` Optional

An object providing the following options requested for the offer:

`iceRestart` Optional

 To restart ICE on an active connection, set this to `true`. This will
 cause the returned offer to have different credentials than those already in place. If
 you then apply the returned offer, ICE will restart. Specify `false` to
 keep the same credentials and therefore not restart ICE. **The default is
`false`**.

`offerToReceiveAudio` Optional
Deprecated

Provides additional control over the directionality of audio. For example, it can be used to ensure that audio can be received, regardless if audio is sent or not.

`offerToReceiveVideo` Optional
Deprecated

Provides additional control over the directionality of video. For example, it can be used to ensure that video can be received, regardless if video is sent or not.

### Deprecated parameters

 In older code and documentation, you may see a callback-based version of this function.
 This has been deprecated and its use is **strongly** discouraged. You
 should update any existing code to use the `Promise`-based version of
 `createOffer()` instead. The parameters for the older form of
 `createOffer()` are described below, to aid in updating existing code.

`successCallback`
Deprecated

 A callback function which will be passed a single
 `RTCSessionDescription` object describing the newly-created offer.

`errorCallback`
Deprecated

 A callback function which will be passed a single
 `DOMException` object explaining why the request to create an offer
 failed.

`options` Optional

An optional object providing options requested for the offer.

### Return value

 A `Promise` whose fulfillment handler will receive an object conforming to
 the RTCSessionDescriptionInit dictionary which contains the SDP
 describing the generated offer. That received offer should be delivered through the
 signaling server to a remote peer.

### Exceptions

 These exceptions are returned by rejecting the returned promise. Your rejection handler
 should examine the received exception to determine which occurred.

`InvalidStateError` `DOMException`

Returned if the `RTCPeerConnection` is closed.

`NotReadableError` `DOMException`

 Returned if no certificate or set of certificates was provided for securing the connection, and
 `createOffer()` was unable to create a new one. Since all WebRTC
 connections are required to be secured, that results in an error.

`OperationError` `DOMException`

 Returned if examining the state of the system to determine resource availability in order to
 generate the offer failed for some reason.

Examples
--------

 Here we see a handler for the `negotiationneeded` event which creates the
 offer and sends it to the remote system over a signaling channel.

**Note:** Keep in mind that this is part of the signaling process, the
 transport layer for which is an implementation detail that's entirely up to you. In
 this case, a WebSocket connection is
 used to send a JSON message with a `type` field with the
 value "video-offer" to the other peer. The contents of the object being passed to the
 `sendToServer()` function, along with everything else in the promise
 fulfillment handler, depend entirely on your design.

```js
myPeerConnection
  .createOffer()
  .then((offer) => myPeerConnection.setLocalDescription(offer))
  .then(() => {
    sendToServer({
      name: myUsername,
      target: targetUsername,
      type: "video-offer",
      sdp: myPeerConnection.localDescription,
    });
  })
  .catch((reason) => {
    // An error occurred, so handle the failure to connect
  });
```

 In this code, the offer is created, and once successful, the local end of the
 `RTCPeerConnection` is configured to match by passing the offer (which is
 represented using an object conforming to RTCSessionDescriptionInit) into
 `setLocalDescription()`. Once
 that's done, the offer is sent to the remote system over the signaling channel; in this
 case, by using a custom function called `sendToServer()`. The implementation
 of the signaling server is independent from the WebRTC specification, so it doesn't
 matter how the offer is sent as long as both the caller and potential receiver are using
 the same one.

Use `Promise.catch()` to trap and handle errors.

 See Signaling and video calling for the complete example from which this snippet is derived; this
 will help you to understand how the signaling code here works.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-createoffer |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCPeerConnection: removeTrack() method - Web APIs

RTCPeerConnection: removeTrack() method
=======================================

 The
 **`RTCPeerConnection.removeTrack()`** method tells the local
 end of the connection to stop sending media from the specified track, without actually
 removing the corresponding `RTCRtpSender` from the list of senders as
 reported by `RTCPeerConnection.getSenders()`. If the track is
 already stopped, or is not in the connection's senders list, this method has no effect.

 If the connection has already been negotiated
 (`signalingState` is set to
 `"stable"`), it is marked as needing to be negotiated again; the remote peer
 won't experience the change until this negotiation occurs. A
 `negotiationneeded` event is sent to the `RTCPeerConnection` to
 let the local end know this negotiation must occur.

Syntax
------

```js
removeTrack(sender)
```

### Parameters

`sender`

A `RTCRtpSender` specifying the sender to remove from the connection.

### Return value

`undefined`.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the connection is not open.

Example
-------

 This example adds a video track to a connection and sets up a listener on a close
 button which removes the track when the user clicks the button.

```js
let pc;
let sender;
navigator.getUserMedia({ video: true }, (stream) => {
  pc = new RTCPeerConnection();
  const [track] = stream.getVideoTracks();
  sender = pc.addTrack(track, stream);
});

document.getElementById("closeButton").addEventListener(
  "click",
  (event) => {
    pc.removeTrack(sender);
    pc.close();
  },
  false,
);
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-removetrack |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API


RTCPeerConnection: getSenders() method - Web APIs

RTCPeerConnection: getSenders() method
======================================

 The `RTCPeerConnection` method **`getSenders()`** returns an array of `RTCRtpSender` objects, each of which represents the RTP sender responsible for transmitting one track's data.
 A sender object provides methods and properties for examining and controlling the encoding and transmission of the track's data.

Syntax
------

```js
getSenders()
```

### Return value

 An array of `RTCRtpSender` objects, one for each track on the connection.
 The array is empty if there are no RTP senders on the connection.

The order of the returned `RTCRtpSender` instances is not defined by the specification, and may change from one call to `getSenders()` to the next.

The array does not include senders associated with transceivers that have been stopped (following offer/answer).

Example
-------

In this example, a `setMuting()` function is shown. This function takes as input an `RTCPeerConnection`, `pc`, and a Boolean, `muting`. The function gets the list of the peer connection's senders and iterates over every sender, setting the corresponding media track's `enabled` to the inverse of the specified `muting`.

```js
function setMuting(pc, muting) {
  let senderList = pc.getSenders();

  senderList.forEach((sender) => {
    sender.track.enabled = !muting;
  });
}
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-getsenders |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* `RTCRtpSender`


RTCPeerConnection: addStream() method - Web APIs

RTCPeerConnection: addStream() method
=====================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The *obsolete* `RTCPeerConnection` method
 **`addStream()`** adds a `MediaStream` as a local
 source of audio or video. Instead of using this obsolete method, you should instead use
 `addTrack()` once for each track you wish to
 send to the remote peer.

 If the `signalingState` is set to
 `closed`, an `InvalidStateError` is raised. If the
 `signalingState` is set to
 `stable`, the event `negotiationneeded` is sent on the
 `RTCPeerConnection` to indicate that ICE negotiation must
 be repeated to consider the new stream.

Syntax
------

```js
addStream(mediaStream)
```

### Parameters

`mediaStream`

 A `MediaStream` object indicating the stream to add to the WebRTC peer
 connection.

### Return value

None.

Example
-------

 This simple example adds the audio and video stream coming from the user's camera to
 the connection.

```js
navigator.mediaDevices.getUserMedia({ video: true, audio: true }, (stream) => {
  const pc = new RTCPeerConnection();
  pc.addStream(stream);
});
```

Migrating to addTrack()
-----------------------

Compatibility allowing, you should update your
 code to instead use the `addTrack()` method:

```js
navigator.getUserMedia({ video: true, audio: true }, (stream) => {
  const pc = new RTCPeerConnection();
  stream.getTracks().forEach((track) => {
    pc.addTrack(track, stream);
  });
});
```

 The newer `addTrack()` API avoids confusion
 over whether later changes to the track-makeup of a stream affects a peer connection
 (they do not).

 The exception is in Chrome, where `addStream()` *does* make the peer
 connection sensitive to later stream changes (though such changes do not fire the
 `negotiationneeded` event). If you are relying on the Chrome behavior, note
 that other browsers do not have it. You can write web compatible code using feature
 detection instead:

```js
// Add a track to a stream and the peer connection said stream was added to:

stream.addTrack(track);
if (pc.addTrack) {
  pc.addTrack(track, stream);
} else {
  // If you have code listening for negotiationneeded events:
  setTimeout(() => pc.dispatchEvent(new Event("negotiationneeded")));
}

// Remove a track from a stream and the peer connection said stream was added to:

stream.removeTrack(track);
if (pc.removeTrack) {
  pc.removeTrack(pc.getSenders().find((sender) => sender.track === track));
} else {
  // If you have code listening for negotiationneeded events:
  setTimeout(() => pc.dispatchEvent(new Event("negotiationneeded")));
}
```

Specifications
--------------

#### No specification found

No specification data found for `api.RTCPeerConnection.addStream`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC


RTCPeerConnection: RTCPeerConnection() constructor - Web APIs

RTCPeerConnection: RTCPeerConnection() constructor
==================================================

The **`RTCPeerConnection()`** constructor returns a newly-created `RTCPeerConnection`, which represents a connection between the local device and a remote peer.

Syntax
------

```js
new RTCPeerConnection()
new RTCPeerConnection(configuration)
```

### Parameters

`configuration` Optional

An object providing options to configure the new connection:

`bundlePolicy` Optional

Specifies how to handle negotiation of candidates when the remote peer is not compatible with the SDP BUNDLE standard. If the remote endpoint is BUNDLE-aware, all media tracks and data channels are bundled onto a single transport at the completion of negotiation, regardless of policy used, and any superfluous transports that were created initially are closed at that point.

In technical terms, a BUNDLE lets all media flow between two peers flow across a single **5-tuple**; that is, from a single IP and port on one peer to a single IP and port on the other peer, using the same transport protocol.

This must be one of the following string values, if not `balanced` is assumed:

`"balanced"`

The ICE agent initially creates one `RTCDtlsTransport` for each type of content added: audio, video, and data channels. If the remote endpoint is not BUNDLE-aware, then each of these DTLS transports handles all the communication for one type of data.

`"max-compat"`

The ICE agent initially creates one `RTCDtlsTransport` per media track and a separate one for data channels. If the remote endpoint is not BUNDLE-aware, everything is negotiated on these separate DTLS transports.

`"max-bundle"`

The ICE agent initially creates only a single `RTCDtlsTransport` to carry all of the `RTCPeerConnection`'s data. If the remote endpoint is not BUNDLE-aware, then only a single track will be negotiated and the rest ignored.

`certificates` Optional

An `Array` of objects of type `RTCCertificate` which are used by the connection for authentication. If this property isn't specified, a set of certificates is generated automatically for each `RTCPeerConnection` instance. Although only one certificate is used by a given connection, providing certificates for multiple algorithms may improve the odds of successfully connecting in some circumstances. See Using certificates for further information.

**Note:** This configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future calls to `RTCPeerConnection.setConfiguration()`.

`iceCandidatePoolSize` Optional

An unsigned 16-bit integer value which specifies the size of the prefetched ICE candidate pool. The default value is 0 (meaning no candidate prefetching will occur). You may find in some cases that connections can be established more quickly by allowing the ICE agent to start fetching ICE candidates before you start trying to connect, so that they're already available for inspection when `RTCPeerConnection.setLocalDescription()` is called.

**Note:** Changing the size of the ICE candidate pool may trigger the beginning of ICE gathering.

`iceServers` Optional

An array of objects, each describing one server which may be used by the ICE agent; these are typically STUN and/or TURN servers. If this isn't specified, the connection attempt will be made with no STUN or TURN server available, which limits the connection to local peers. Each object may have the following properties:

`credential` Optional

The credential to use when logging into the server. This is only used if the object represents a TURN server.

`credentialType` Optional
Deprecated

Non-standard

If the object represents a TURN server, this attribute specifies what kind of `credential` is to be used when connecting. The default is `"password"`.

`urls`

This **required** property is either a single string or an array of strings, each specifying a URL which can be used to connect to the server.

`username` Optional

If the object represents a TURN server, then this is the username to use during the authentication.

`iceTransportPolicy` Optional

A string representing the current ICE transport policy. Possible values are:

`"all"`

All ICE candidates will be considered. This is the default value.

`"public"`
Deprecated

Only ICE candidates with public IP addresses will be considered.

`"relay"`

Only ICE candidates whose IP addresses are being relayed, such as those being passed through a TURN server, will be considered.

`peerIdentity` Optional

A string which specifies the target peer identity for the `RTCPeerConnection`. If this value is set (it defaults to `null`), the `RTCPeerConnection` will not connect to a remote peer unless it can successfully authenticate with the given name.

`rtcpMuxPolicy` Optional

A string which specifies the RTCP mux policy to use when gathering ICE candidates, in order to support non-multiplexed RTCP. Possible values are:

`"negotiate"`

Instructs the ICE agent to gather both RTP and RTCP candidates. If the remote peer can multiplex RTCP, then RTCP candidates are multiplexed atop the corresponding RTP candidates. Otherwise, both the RTP and RTCP candidates are returned, separately.

`"require"`

Tells the ICE agent to gather ICE candidates for only RTP, and to multiplex RTCP atop them. If the remote peer doesn't support RTCP multiplexing, then session negotiation fails. This is the default value.

### Return value

A newly-created `RTCPeerConnection` object, configured as described by `configuration`, if specified; otherwise, configured to appropriate basic defaults.

Using certificates
------------------

When you wish to provide your own certificates for use by an `RTCPeerConnection` instead of having the `RTCPeerConnection` generate them automatically, you do so by calling the static `RTCPeerConnection.generateCertificate()` function.

The `certificates` property's value cannot be changed once it's first specified. If it's included in the configuration passed into a call to a connection's `setConfiguration()`, it is ignored.

This attribute supports providing multiple certificates because even though a given DTLS connection uses only one certificate, providing multiple certificates allows support for multiple encryption algorithms. The implementation of `RTCPeerConnection` will choose which certificate to use based on the algorithms it and the remote peer support, as determined during DTLS handshake.

If you don't provide certificates, new ones are generated automatically. One obvious benefit to providing your own is identity key continuity—if you use the same certificate for subsequent calls, the remote peer can tell you're the same caller. This also avoids the cost of generating new keys.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Signaling and video calling
* WebRTC architecture overview
* Lifetime of a WebRTC session
* `RTCPeerConnection`


RTCPeerConnection: setLocalDescription() method - Web APIs

RTCPeerConnection: setLocalDescription() method
===============================================

 The `RTCPeerConnection` method
 `setLocalDescription()` changes
 the local description associated with the connection. This description specifies the
 properties of the local end of the connection, including the media format.
 The method takes a single parameter—the session description—and it returns a
 `Promise` which is fulfilled once the description has been changed,
 asynchronously.

 If `setLocalDescription()` is called while a connection is already in place,
 it means renegotiation is underway (possibly to adapt to changing network conditions).
 Because descriptions will be exchanged until the two peers agree on a configuration, the
 description submitted by calling `setLocalDescription()` does not immediately
 take effect. Instead, the current connection configuration remains in place until
 negotiation is complete. Only then does the agreed-upon configuration take effect.

Syntax
------

```js
setLocalDescription()
setLocalDescription(sessionDescription)

setLocalDescription(sessionDescription, successCallback, errorCallback) // deprecated
```

### Parameters

`sessionDescription` Optional

 An `RTCSessionDescriptionInit` or `RTCSessionDescription`
 which specifies the configuration to be applied to the local end of the connection. If
 the description is omitted, the WebRTC runtime tries to automatically do the right
 thing.

### Return value

 A `Promise` which is fulfilled once the value of
 `RTCPeerConnection.localDescription` is successfully changed or rejected if
 the change cannot be applied (for example, if the specified description is incompatible
 with one or both of the peers on the connection). The promise's fulfillment handler
 receives no input parameters.

**Note:** The process of changing descriptions actually involves intermediary steps handled by
 the WebRTC layer to ensure that an active connection can be changed without losing the
 connection if the change does not succeed. See
 Pending and current descriptions in the WebRTC Connectivity page for more details on this process.

#### Implicit description

 If you don't explicitly provide a session description, the WebRTC runtime will try to
 handle it correctly. If the signaling state is one of `stable`,
 `have-local-offer`, or `have-remote-pranswer`, the WebRTC runtime
 automatically creates a new offer and sets that as the new local description. Otherwise,
 `setLocalDescription()` creates an answer, which becomes the new local
 description.

#### Type of the description parameter

 The description is of type `RTCSessionDescriptionInit`, which is a
 serialized version of a `RTCSessionDescription` browser object. They're
 interchangeable:

```js
myPeerConnection
  .createOffer()
  .then((offer) => myPeerConnection.setLocalDescription(offer));
```

This is equivalent to:

```js
myPeerConnection
  .createOffer()
  .then((offer) =>
    myPeerConnection.setLocalDescription(new RTCSessionDescription(offer)),
  );
```

For this reason, the `RTCSessionDescription()` constructor is deprecated.

### Deprecated parameters

 In older code and documentation, you may see a callback-based version of this function
 used. This has been deprecated and its use is **strongly** discouraged, as
 it will be removed in the future. You should update any existing code to use the
 `Promise`-based version of `setLocalDescription()` instead. The
 parameters for the older form of `setLocalDescription()` are described below,
 to aid in updating existing code.

`successCallback`
Deprecated

 A JavaScript `Function` which accepts no input parameters to be called
 once the description has been successfully set. At that time, the offer can be sent to
 a remote peer via the signaling server.

`errorCallback`
Deprecated

 A function matching the signature `RTCPeerConnectionErrorCallback` which
 gets called if the description can't be set. It is passed a single
 `DOMException` object explaining why the request failed.

 This deprecated form of the method returns instantaneously without waiting for the
 actual setting to be done: in case of success, the `successCallback` will be
 called; in case of failure, the `errorCallback` will be called.

### Deprecated exceptions

 When using the deprecated callback-based version of `setLocalDescription()`,
 the following exceptions may occur:

`InvalidStateError` `DOMException`
Deprecated

 Thrown if the connection's `signalingState`
 is `"closed"`, indicating that the connection is not currently open, so
 negotiation cannot take place.

`InvalidSessionDescriptionError` `DOMException`
Deprecated

 Thrown if the `RTCSessionDescription` specified by the
 `sessionDescription` parameter is invalid.

Examples
--------

### Implicit descriptions

 One of the advantages of the parameter-free form
 of `setLocalDescription()` is that it lets you simplify your negotiation code
 substantially. This is all your `negotiationneeded` event handler needs to look like, for the most part. Just add the
 signaling server code, which here is represented by the call to
 `signalRemotePeer()`.

```js
pc.addEventListener("negotiationneeded", async (event) => {
  await pc.setLocalDescription();
  signalRemotePeer({ description: pc.localDescription });
});
```

Other than error handling, that's about it!

### Providing your own offer or answer

 The example below shows the implementation of a handler for the
 `negotiationneeded` event that explicitly creates an offer, rather than
 letting `setLocalDescription()` do it.

```js
async function handleNegotiationNeededEvent() {
  try {
    const offer = await pc.createOffer();
    pc.setLocalDescription(offer);
    signalRemotePeer({ description: pc.localDescription });
  } catch (err) {
    reportError(err);
  }
}
```

 This begins by creating an offer by calling
 `createOffer()`; when that succeeds, we
 call `setLocalDescription()`. We can then send the newly-created offer along
 to the other peer using the signaling server, which here is done by calling a function
 called `signalRemotePeer()`.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-setlocaldescription |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC API


RTCPeerConnection: signalingState property - Web APIs

RTCPeerConnection: signalingState property
==========================================

 The read-only **`signalingState`** property on the
 `RTCPeerConnection` interface returns a string value
 describing the state of the signaling process
 on the local end of the connection
 while connecting or reconnecting to another peer.
 See Signaling in our WebRTC session lifetime page.

 Because the signaling process is a state machine, being able to verify that your code
 is in the expected state when messages arrive can help avoid unexpected and avoidable
 failures. For example, if you receive an answer while the `signalingState`
 isn't `"have-local-offer"`, you know that something is wrong, since you
 should only receive answers after creating an offer but before an answer has been
 received and passed into `RTCPeerConnection.setLocalDescription()`. Your
 code will be more reliable if you watch for mismatched states like this and handle them
 gracefully.

This value may also be useful during debugging, for example.

 In addition, when the value of this property changes, a
 `signalingstatechange` event is sent to the `RTCPeerConnection`
 instance.

Value
-----

The allowed string values are:

`stable`

 There is no ongoing exchange of offer and answer underway.
 This may mean that the `RTCPeerConnection` object is new,
 in which case
 both the `localDescription`
 and `remoteDescription`
 are `null`;
 it may also mean that negotiation is complete
 and a connection has been established.

`have-local-offer`

 The local peer has called `RTCPeerConnection.setLocalDescription()`,
 passing in SDP representing an offer
 (usually created by calling `RTCPeerConnection.createOffer()`),
 and the offer has been applied successfully.

`have-remote-offer`

 The remote peer has created an offer
 and used the signaling server
 to deliver it to the local peer,
 which has set the offer
 as the remote description
 by calling `RTCPeerConnection.setRemoteDescription()`.

`have-local-pranswer`

 The offer sent by the remote peer has been applied
 and an answer has been created
 (usually by calling `RTCPeerConnection.createAnswer()`)
 and applied by calling `RTCPeerConnection.setLocalDescription()`.
 This provisional answer describes the supported media formats and so forth,
 but may not have a complete set of ICE candidates included.
 Further candidates will be delivered separately later.

`have-remote-pranswer`

 A provisional answer has been received
 and successfully applied
 in response to an offer previously sent
 and established by calling `setLocalDescription()`.

`closed`

The `RTCPeerConnection` has been closed.

Examples
--------

```js
const pc = new RTCPeerConnection(configuration);
const state = pc.signalingState;
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-signaling-state |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Lifetime of a WebRTC session
* `RTCPeerConnection`
* `signalingstatechange`
* WebRTC


RTCPeerConnection: icecandidateerror event - Web APIs

RTCPeerConnection: icecandidateerror event
==========================================

The WebRTC API event **`icecandidateerror`** is sent to an `RTCPeerConnection` if an error occurs while performing ICE negotiations through a STUN or TURN server. The event object is of type `RTCPeerConnectionIceErrorEvent`, and contains information describing the error in some amount of detail.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("icecandidateerror", (event) => {});

onicecandidateerror = (event) => {};
```

Event type
----------

An `RTCPeerConnectionIceErrorEvent`. Inherits from `Event`.

Event

RTCPeerConnectionIceErrorEventEvent properties
----------------

*The `RTCPeerConnectionIceErrorEvent` interface includes the properties found on the `Event` interface, as well as the following properties:*

`address` Read only

A string providing the local IP address used to communicate with the STUN or TURN server being used to negotiate the connection, or `null` if the local IP address has not yet been exposed as part of a local ICE candidate.

`errorCode` Read only

An unsigned integer value stating the numeric STUN error code returned by the STUN or TURN server. If no host candidate can reach the server, this property is set to the number 701, which is outside the range of valid STUN error codes. The 701 error is fired only once per server URL, and only while the `icegatheringstate` is `gathering`.

`errorText` Read only

A string containing the STUN reason text returned by the STUN or TURN server. If communication with the STUN or TURN server couldn't be established at all, this string will be a browser-specific string explaining the error.

`port` Read only

An unsigned integer value giving the port number over which communication with the STUN or TURN server is taking place, using the IP address given in `address`. `null` if the connection hasn't been established (that is, if `address` is `null`).

`url` Read only

A string indicating the URL of the STUN or TURN server with which the error occurred.

Description
-----------

The error object's `errorCode` property is one of the numeric STUN error codes. There is one additional, WebRTC-specific, error which lies outside the valid STUN error code range: 701. Error 701 indicates that none of the ICE candidates were able to successfully make contact with the STUN or TURN server.

The 701 error is fired only once per server URL from the list of available STUN or TURN servers provided when creating the `RTCPeerConnection`. These errors occur only when the connection's ICE gathering state is `gathering`.

Example
-------

The following example establishes a handler for `icecandidateerror`s that occur on the `RTCPeerConnection` `pc`. This handler looks specifically for 701 errors that indicate that candidates couldn't reach the STUN or TURN server.

When this happens, the server URL and the error message are passed to a function called `reportConnectFail()` to log or output the connection failure.

```js
pc.addEventListener("icecandidateerror", (event) => {
  if (event.errorCode === 701) {
    reportConnectFail(event.url, event.errorText);
  }
});
```

Note that if multiple STUN and/or TURN servers are provided when creating the connection, this error may happen more than once, if more than one of those servers fails. Each provided server is tried until a connection is established.

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-onicecandidateerror |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCPeerConnection: currentLocalDescription property - Web APIs

RTCPeerConnection: currentLocalDescription property
===================================================

 The read-only property
 **`RTCPeerConnection.currentLocalDescription`** returns an
 `RTCSessionDescription` object describing the local end of the connection
 as it was most recently successfully negotiated since the last time the
 `RTCPeerConnection` finished negotiating and connecting to a remote peer.
 Also included is a list of any ICE candidates that may already have been generated by
 the ICE agent since the offer or answer represented by the description was first
 instantiated.

 To change the `currentLocalDescription`, call
 `RTCPeerConnection.setLocalDescription()`, which triggers a series of
 events which leads to this value being set. For details on what exactly happens and why
 the change isn't necessarily instantaneous, see
 Pending and current descriptions in the WebRTC Connectivity page.

**Note:** Unlike `RTCPeerConnection.localDescription`, this value represents the
 actual current state of the local end of the connection; `localDescription`
 may specify a description which the connection is currently in the process of
 switching over to.

Value
-----

 The current description of the local end of the connection, if one has been set. If
 none has been successfully set, this value is `null`.

Examples
--------

 This example looks at the `currentLocalDescription` and displays an alert
 containing the `RTCSessionDescription` object's `type` and
 `sdp` fields.

```js
const pc = new RTCPeerConnection();
// ...
const sd = pc.currentLocalDescription;
if (sd) {
  alert(`Local session: type='${sd.type}'; sdp description='${sd.sdp}'`);
} else {
  alert("No local session yet.");
}
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-currentlocaldesc |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

**Note:** The addition of `currentLocalDescription` and
 `pendingLocalDescription` to
 the WebRTC spec is relatively recent. In browsers which don't support them, just use
 `localDescription`.

See also
--------

* `RTCPeerConnection.setLocalDescription()`,
 `RTCPeerConnection.pendingLocalDescription`,
 `RTCPeerConnection.localDescription`
* `RTCPeerConnection.setRemoteDescription()`,
 `RTCPeerConnection.remoteDescription`,
 `RTCPeerConnection.pendingRemoteDescription`,
 `RTCPeerConnection.currentRemoteDescription`
* WebRTC


RTCPeerConnection: close() method - Web APIs

RTCPeerConnection: close() method
=================================

 The **`RTCPeerConnection.close()`** method closes the current
 peer connection.

Syntax
------

```js
close()
```

*This method has no parameters, and returns nothing.*

 Calling this method terminates the RTCPeerConnection's ICE agent, ending any ongoing
 ICE processing and any active streams. This also releases any resources in use by the
 ICE agent, including TURN permissions. All `RTCRtpSender` objects are
 considered to be stopped once this returns (they may still be in the process of
 stopping, but for all intents and purposes, they're stopped).

 Once this method returns, the signaling state as returned by
 `RTCPeerConnection.signalingState` is `closed`.

 Make sure that you `delete` all references to the previous
 `RTCPeerConnection` before attempting to create a new one that connects
 to the same remote peer, as not doing so might result in some errors depending on the
 browser.

Example
-------

```js
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("my channel");

dc.onmessage = (event) => {
  console.log(`received: ${event.data}`);
  pc.close(); // We decided to close after the first received message
};

dc.onopen = () => {
  console.log("datachannel open");
};

dc.onclose = () => {
  console.log("datachannel close");
};
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnection-close |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC
* `RTCPeerConnection`
* `RTCPeerConnection.signalingState`


RTCPeerConnection: localDescription property - Web APIs

RTCPeerConnection: localDescription property
============================================

 The read-only property **`RTCPeerConnection.localDescription`** returns an `RTCSessionDescription` describing the session for the local end of the connection.
 If it has not yet been set, this is `null`.

Syntax
------

```js
const sessionDescription = peerConnection.localDescription
```

 On a more fundamental level, the returned value is the value of `RTCPeerConnection.pendingLocalDescription` if that property isn't `null`;
 otherwise, the value of `RTCPeerConnection.currentLocalDescription` is returned.
 See Pending and current descriptions in the WebRTC Connectivity page for details on this algorithm and why it's used.

Example
-------

This example looks at the `localDescription` and displays an alert containing the `RTCSessionDescription` object's `type` and `sdp` fields.

```js
const pc = new RTCPeerConnection();
// ...
const sd = pc.localDescription;
if (sd) {
  alert(`Local session: type='${sd.type}'; sdp description='${sd.sdp}'`);
} else {
  alert("No local session yet.");
}
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-peerconnection-localdescription |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `RTCPeerConnection.setLocalDescription()`,
 `RTCPeerConnection.pendingLocalDescription`,
 `RTCPeerConnection.currentLocalDescription`
* `RTCPeerConnection.setRemoteDescription()`,
 `RTCPeerConnection.remoteDescription`,
 `RTCPeerConnection.pendingRemoteDescription`,
 `RTCPeerConnection.currentRemoteDescription`
* WebRTC


DOMMatrixReadOnly: scale() method - Web APIs

DOMMatrixReadOnly: scale() method
=================================

 The **`scale()`** method of the
 `DOMMatrixReadOnly` interface creates a new matrix being the result of the
 original matrix with a scale transform applied.

Syntax
------

The `scale()` method is specified with either one or six values.

```js
DOMMatrixReadOnly.scale(scaleX);
DOMMatrixReadOnly.scale(scaleX, scaleY);
DOMMatrixReadOnly.scale(scaleX, scaleY, scaleZ);
DOMMatrixReadOnly.scale(scaleX, scaleY, scaleZ, originX);
DOMMatrixReadOnly.scale(scaleX, scaleY, scaleZ, originX, originY);
DOMMatrixReadOnly.scale(scaleX, scaleY, scaleZ, originX, originY, originZ);
```

### Parameters

`scaleX`

A multiplier for the scale value on the x-axis.

`scaleY` Optional

 A multiplier for the scale value on the y-axis. If not supplied, this defaults to
 the value of `scaleX`.

`scaleZ` Optional

 A multiplier for the scale value on the z-axis. If this value is anything other
 than 1, the resulting matrix will be 3D.

`originX` Optional

 An x-coordinate for the origin of the transformation. If no origin is supplied,
 this defaults to 0.

`originY` Optional

 A y-coordinate for the origin of the transformation. If no origin is supplied, this
 defaults to 0.

`originZ` Optional

 A z-coordinate for the origin of the transformation. If no origin is supplied, this
 defaults to 0. If this value is anything other than 0, the resulting matrix will be
 3D.

### Return value

 Returns a `DOMMatrix`
 containing a new matrix being the result of the matrix x and y dimensions being scaled
 by the given factor, centered on the origin given. The original matrix is not modified.

If a scale is applied about the z-axis, the resulting matrix will be a 4✕4 3D matrix.

Examples
--------

 This SVG contains three squares, one red, one blue, and one green, each positioned at
 the document origin:

```html
<svg width="250" height="250" viewBox="0 0 25 25">
  <rect width="25" height="25" fill="red" />
  <rect id="transformed" width="25" height="25" fill="blue" />
  <rect id="transformedOrigin" width="25" height="25" fill="green" />
</svg>
```

 This JavaScript first creates an identity matrix, then uses the `scale()`
 method to create a new matrix with a single parameter.

 We test if the browser supports a six parameter `scale()` method by creating
 a new matrix using three parameters and observing its `is2D` property. If
 this is `false` then the third parameter has been accepted by the browser as
 a `scaleZ` parameter, making this a 3D matrix.

 We then create a new matrix scaled about a given origin, using either three or six
 parameters depending on the browser support.

 These new matrices are then applied to the blue and green squares as a
 `transform`, changing their dimensions and position. The red square is left
 in place.

```js
const matrix = new DOMMatrixReadOnly();
const scaledMatrix = matrix.scale(0.5);

let scaledMatrixWithOrigin = matrix.scale(0.5, 25, 25);

// if the browser has interpreted these parameters as scaleX, scaleY, scaleZ, the resulting matrix is 3D
const browserExpectsSixParamScale = !scaledMatrixWithOrigin.is2D;
if (browserExpectsSixParamScale) {
  scaledMatrixWithOrigin = matrix.scale(0.5, 0.5, 1, 25, 25, 0);
}

document
  .querySelector("#transformed")
  .setAttribute("transform", scaledMatrix.toString());
document
  .querySelector("#transformedOrigin")
  .setAttribute("transform", scaledMatrixWithOrigin.toString());
```

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dommatrixreadonly-scale |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


DOMMatrixReadOnly: DOMMatrixReadOnly() constructor - Web APIs

DOMMatrixReadOnly: DOMMatrixReadOnly() constructor
==================================================

 The **`DOMMatrixReadOnly`** constructor creates a new
 `DOMMatrixReadOnly` object which represents 4x4 matrices, suitable for 2D
 and 3D operations.

Syntax
------

```js
DOMMatrixReadOnly()
DOMMatrixReadOnly(init)
```

### Parameters

`init` Optional

 Either a string containing a sequence of numbers or an array of numbers
 specifying the matrix you want to create.

In case an array of numbers is passed, the behavior depends on the length of the array:

* for a 6-element array of components in the form `[a, b, c, d, e, f]`, a 2D read-only matrix is created, initialized with the provided components.
* for a 16-element array of components (in the column-major order) in the form `[m11, m12, m13, …, m42, m43, m44]`, a 3D read-only matrix is created, initialized with the provided components.

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dommatrixreadonly-dommatrixreadonly |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


DOMMatrixReadOnly: translate() method - Web APIs

DOMMatrixReadOnly: translate() method
=====================================

 The `translate()` method of the `DOMMatrixReadOnly` interface
 creates a new matrix being the result of the original matrix with a translation applied.

Syntax
------

```js
DOMMatrix.translate(translateX, translateY)
DOMMatrix.translate(translateX, translateY, translateZ)
```

### Parameters

`translateX`

A number representing the abscissa (x-coordinate) of the translating vector.

`translateY`

A number representing the ordinate (y-coordinate) of the translating vector.

`translateZ` Optional

 A number representing the z component of the translating vector. If not supplied,
 this defaults to 0. If this is anything other than 0, the resulting matrix will be
 3D.

### Return value

 Returns a `DOMMatrix`
 containing a new matrix being the result of the matrix being translated by the given
 vector. The original matrix is not modified.

 If a translation is applied about the z-axis, the resulting matrix will be a 4x4 3D
 matrix.

Examples
--------

 This SVG contains two squares, one red and one blue, each positioned at the document
 origin:

```html
<svg width="250" height="250" viewBox="0 0 50 50">
  <rect width="25" height="25" fill="red" />
  <rect id="transformed" width="25" height="25" fill="blue" />
</svg>
```

 The following JavaScript first creates an identity matrix, then uses the
 `translate()` method to create a new, translated matrix — which is then
 applied to the blue square as a `transform`. The red square is left in place.

```js
const matrix = new DOMMatrixReadOnly().translate(25, 25);

document
  .querySelector("#transformed")
  .setAttribute("transform", matrix.toString());
```

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dommatrixreadonly-translate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


DOMMatrixReadOnly: flipX() method - Web APIs

DOMMatrixReadOnly: flipX() method
=================================

The `flipX()` method of the `DOMMatrixReadOnly` interface creates a new matrix being the result of the original matrix flipped about the x-axis.

Syntax
------

```js
  DOMMatrixReadOnly.flipX()
```

### Return value

Returns a `DOMMatrix` containing a new matrix being the result of the original matrix flipped about the x-axis, which is equivalent to multiplying the matrix by `DOMMatrix(-1, 0, 0, 1, 0, 0)`. The original matrix is not modified.

Examples
--------

### Inverting a triangle

In this example, the SVG contains two paths in the shape of a triangle, both drawn to the same position. Note that the x co-ordinate of the viewBox attribute is negative, showing us content from both sides of the x-axis.

The JavaScript first creates an identity matrix, then uses the `flipX()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis. The red triangle is left in place.

#### HTML

```html
<svg width="100" height="100" viewBox="-50 0 100 100">
  <path fill="red" d="M 0 50 L 50 0 L 50 100 Z" />
  <path id="flipped" fill="blue" d="M 0 50 L 50 0 L 50 100 Z" />
</svg>
```

#### JavaScript

```js
const flipped = document.getElementById("flipped");
const matrix = new DOMMatrixReadOnly();
const flippedMatrix = matrix.flipX();
flipped.setAttribute("transform", flippedMatrix.toString());
```

#### Result

Specifications
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dommatrixreadonly-flipx |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


FileSystemFileEntry: createWriter() method - Web APIs

FileSystemFileEntry: createWriter() method
==========================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `FileSystemFileEntry` interface's method
 **`createWriter()`** returns a `FileWriter` object
 which can be used to write data into the file represented by the directory entry.

Syntax
------

```js
createWriter(successCallback)
createWriter(successCallback, errorCallback)
```

### Parameters

`successCallback`

 A callback function which is called when the `FileWriter` has been
 created successfully; the `FileWriter` is passed into the callback as the
 only parameter.

`errorCallback` Optional

 If provided, this must be a method which is called when an error occurs while trying
 to create the `FileWriter`. This callback receives as input a
 `FileError` object describing the error.

### Return value

None (`undefined`).

Examples
--------

 This example establishes a method, `writeToFileEntry()`, which outputs a
 text string to the file corresponding to the passed-in directory entry.

```js
function writeToFileEntry(entry, text) {
  entry.createWriter(
    (fileWriter) => {
      let data = Blob([text], { type: "text/plain" });

      fileWriter.write(data);
    },
    (fileError) => {
      /\* do whatever to handle the error \*/
    },
  );
}
```

 The success callback for the `createWriter()` call takes the text which was
 passed in and creates a new `Blob` object of type `text/plain`
 that contains the passed text. This blob is then output to the `FileWriter`
 object to be written to the file.

Specifications
--------------

This feature is not part of any specification anymore. It is no longer on track to become a standard.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API


FileSystemFileEntry: file() method - Web APIs

FileSystemFileEntry: file() method
==================================

 The `FileSystemFileEntry` interface's method
 **`file()`** returns a
 `File` object which can be used to read data from the file represented by
 the directory entry.

Syntax
------

```js
file(successCallback)
file(successCallback, errorCallback)
```

### Parameters

`successCallback`

 A callback function which is called when the `File` has been created
 successfully; the `File` is passed into the callback as the only parameter.

`errorCallback` Optional

 If provided, this must be a method which is called when an error occurs while trying
 to create the `File`. This callback receives as input a
 `DOMException` object describing the error.

### Return value

None (`undefined`).

Examples
--------

 This example establishes a method, `readFile()`, reads a text file and calls
 a specified callback function with the received text (in a string)
 once the read is completed. If an error occurs, a specified (optional) error callback is
 called.

```js
function readFile(entry, successCallback, errorCallback) {
  entry.file((file) => {
    let reader = new FileReader();

    reader.onload = () => {
      successCallback(reader.result);
    };

    reader.onerror = () => {
      errorCallback(reader.error);
    };

    reader.readAsText(file);
  }, errorCallback);
}
```

 This function calls `file()`, specifying as its success callback a method
 which proceeds to use a `FileReader` to read the file as text. The
 FileReader's `load` event handler is set up to deliver the loaded string to
 the `successCallback` specified when the `readFile()` method was
 called; similarly, its `error` handler is set up to call the
 `errorCallback` specified.

Specifications
--------------

| Specification |
| --- |
| File and Directory Entries API # dom-filesystemfileentry-file |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API


MerchantValidationEvent: complete() method - Web APIs

MerchantValidationEvent: complete() method
==========================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The `MerchantValidationEvent` method **`complete()`** takes merchant-specific information previously received from the `validationURL` and uses it to validate the merchant.

All you have to do is call `complete()` from your handler for the `merchantvalidation` event, passing in the data fetched from the `validationURL`.

Syntax
------

```js
complete(validationData)
complete(merchantSessionPromise)
```

### Parameters

`validationData` or `merchantSessionPromise`

An object containing the data needed to complete the merchant validation process, or a `Promise` which resolves to the validation data.

### Return value

None (`undefined`).

### Exceptions

This exception may be passed into the rejection handler for the promise:

`InvalidStateError` `DOMException`

Returned if the event did not come directly from the user agent, but was instead dispatched by other code. Another payment request is currently being processed, the current payment request is not currently being displayed to the user, or payment information is currently being updated.

Examples
--------

In this example, we see the client-side code needed to support merchant validation for a payment request called `payRequest`:

```js
payRequest.onmerchantvalidation = (event) => {
  const validationDataPromise = getValidationData(event.validationURL);
  event.complete(validationDataPromise);
};

function getValidationData(url) {
  // Retrieve the validation data from the URL
  // …
}
```

This code sets up a handler for the `merchantvalidation` event. The event handler calls a function, `getValidationData()`, which retrieves the data from the validation URL, then passes that data (or a promise to deliver the data) into `complete()`.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Payment Request API
* Using the Payment Request API
* Payment processing concepts


MerchantValidationEvent: methodName property - Web APIs

MerchantValidationEvent: methodName property
============================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The `MerchantValidationEvent` property
 **`methodName`** is a read-only value which returns a string
 indicating the payment method identifier which represents the payment handler that
 requires merchant validation.

Value
-----

 A read-only string which uniquely identifies the payment handler
 which is requesting merchant validation. See
 Merchant validation for more information on the process.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Payment Request API
* Using the Payment Request API
* Payment processing concepts


MerchantValidationEvent: validationURL property - Web APIs

MerchantValidationEvent: validationURL property
===============================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The `MerchantValidationEvent` property
 **`validationURL`** is a read-only string value providing the
 URL from which to fetch the payment handler-specific data needed to validate the
 merchant.

This data should be passed into the `complete()` method to let the user agent complete the transaction.

Value
-----

 A read-only string giving the URL from which to load payment handler
 specific data needed to complete the merchant verification process. Once this has been
 loaded, it should be passed into `complete()`, either directly or using a promise.

See Merchant validation to learn more about the process.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Payment Request API
* Using the Payment Request API
* Payment processing concepts


MerchantValidationEvent: MerchantValidationEvent() constructor - Web APIs

MerchantValidationEvent: MerchantValidationEvent() constructor
==============================================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`MerchantValidationEvent()`** constructor creates a new `MerchantValidationEvent` object. You should not have to create these events yourself; instead, just handle the `merchantvalidation` event.

Syntax
------

```js
new MerchantValidationEvent(type)
new MerchantValidationEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `merchantvalidation`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`methodName` Optional

A string containing the payment method identifier for the payment handler being used. This is an empty string by default.

`validationURL` Optional

The URL from which to retrieve payment handler specific verification information used to validate the merchant. This is an empty string by default.

### Return value

 A new `MerchantValidationEvent` object providing the information
 that needs to be delivered to the client-side code to present to the user agent by calling `complete()`.

### Exceptions

`TypeError`

Thrown if the string specified as `validationURL` could not be parsed as a URL.

`RangeError`

Thrown if the specified `methodName` does not correspond to a known and supported merchant or is not a well-formed standard payment method identifier.

Specifications
--------------

*This feature is deprecated and is not part of any specification.*

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Payment Request API
* Using the Payment Request API
* Payment processing concepts


NavigationHistoryEntry: key property - Web APIs

NavigationHistoryEntry: key property
====================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`key`** read-only property of the `NavigationHistoryEntry` interface returns the `key` of the history entry, or an empty string if current document is not fully active. This is a unique, UA-generated value that represents the history entry's slot in the entries list. It is used to navigate that particular slot via `Navigation.traverseTo()`. The `key` will be reused by other entries that replace the entry in the list (that is, if the `NavigateEvent.navigationType` is `replace`).

This differs from the `id` of a history entry. The `id` is a unique, UA-generated value that always represents a specific history entry rather than its slot in the entries list. This is useful to correlate it with an external resource such as a storage cache.

Value
-----

A string representing the `key` of the `NavigationHistoryEntry`.

Examples
--------

### Basic usage

```js
const current = navigation.currentEntry;
console.log(current.key);
```

### Set up a home button

```js
function initHomeBtn() {
  // Get the key of the first loaded entry
  // so the user can always go back to this view.
  const { key } = navigation.currentEntry;
  backToHomeButton.onclick = () => {
    navigation.traverseTo(key);
  };
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
  event.intercept({
    async handler() {
      // Navigate to a different view,
      // but the "home" button will always work.
    },
  });
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigationhistoryentry-key-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigationHistoryEntry: url property - Web APIs

NavigationHistoryEntry: url property
====================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`url`** read-only property of the `NavigationHistoryEntry` interface returns the absolute URL of this history entry. If the entry corresponds to a different Document than the current one (like `sameDocument` property is `false`), and that Document was fetched with a `referrer policy` header set to `no-referrer` or `origin`, the property returns `null`. If current document is not fully active, it returns an empty string.

Value
-----

A string representing the URL or `null`.

Examples
--------

```js
const current = navigation.currentEntry;
console.log(current.url);
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigationhistoryentry-url-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigationHistoryEntry: id property - Web APIs

NavigationHistoryEntry: id property
===================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`id`** read-only property of the `NavigationHistoryEntry` interface returns the `id` of the history entry, or an empty string if current document is not fully active. This is a unique, UA-generated value that always represents a specific history entry, useful to correlate it with an external resource such as a storage cache.

This differs from the `key` of a history entry. The `key` is a unique, UA-generated value that represents the history entry's slot in the entries list rather than the entry itself. It is used to navigate that particular slot via `Navigation.traverseTo()`. The `key` will be reused by other entries that replace the entry in the list (that is, if the `NavigateEvent.navigationType` is `replace`).

Value
-----

A string representing the `id` of the `NavigationHistoryEntry`.

Examples
--------

```js
const current = navigation.currentEntry;
console.log(current.id);
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigationhistoryentry-id-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigationHistoryEntry: dispose event - Web APIs

NavigationHistoryEntry: dispose event
=====================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`dispose`** event of the `NavigationHistoryEntry` interface is fired when the entry is no longer part of the history entry list.

Disposal occurs when:

* Forward history entries are cleared. See the example at Notifications on entry disposal for more information.
* The user clears their browser history using settings or provided UI controls.
* The history limit is exceeded. This is not specified anywhere, but browsers tend to have a history limit of 50 pages.
Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("dispose", (event) => {});

ondispose = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

```js
navigation.addEventListener("currententrychange", () => {
  navigation.currentEntry.addEventListener("dispose", disposeHandler);
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # handler-navigationhistoryentry-ondispose |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigationHistoryEntry: sameDocument property - Web APIs

NavigationHistoryEntry: sameDocument property
=============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`sameDocument`** read-only property of the `NavigationHistoryEntry` interface returns `true` if this history entry is for the same `document` as the current `Document` value and current document is fully active, or `false` otherwise.

Value
-----

A boolean.

Examples
--------

```js
const current = navigation.currentEntry;
console.log(current.sameDocument);
// Will always return true
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigationhistoryentry-samedocument-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigationHistoryEntry: getState() method - Web APIs

NavigationHistoryEntry: getState() method
=========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`getState()`** method of the `NavigationHistoryEntry` interface returns a clone of the developer-supplied state associated with this history entry.

Syntax
------

```js
getState()
```

### Parameters

None.

### Return value

A value representing the state. This can be any structured-cloneable data type.

If no state is defined or if current document is not fully active, it returns `undefined`.

### Exceptions

None.

Examples
--------

```js
async function handleReload() {
  // Update existing state via reload()
  await navigation.reload({
    state: { ...navigation.currentEntry.getState(), newState: 3 },
  });

  // Print current state to the console
  const current = navigation.currentEntry;
  console.log(current.getState());
}
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigationhistoryentry-getstate-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo
* Methods that allow state to be updated — `Navigation.navigate()`, `Navigation.reload()`, and `Navigation.updateCurrentEntry()`


NavigationHistoryEntry: index property - Web APIs

NavigationHistoryEntry: index property
======================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`index`** read-only property of the `NavigationHistoryEntry` interface returns the index of the history entry in the history entries list (that is, the list returned by `Navigation.entries()`), or `-1` if the entry does not appear in the list or if current document is not fully active.

Value
-----

A number representing the `index` of the entry in the history entries list, or `-1` if this item does not appear in the list.

Examples
--------

```js
const current = navigation.currentEntry;
console.log(current.index);
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigationhistoryentry-index-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


PageTransitionEvent: persisted property - Web APIs

PageTransitionEvent: persisted property
=======================================

The **`persisted`** read-only property indicates if a webpage is loading from a cache.

Value
-----

A boolean value.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-pagetransitionevent-persisted-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PageTransitionEvent: PageTransitionEvent() constructor - Web APIs

PageTransitionEvent: PageTransitionEvent() constructor
======================================================

The **`PageTransitionEvent()`** constructor creates a new `PageTransitionEvent` object, that is used by the `pageshow` or `pagehide` events, fired at the `window` object when a page is loaded or unloaded.

**Note:** A web developer doesn't typically need to call this constructor, as the browser creates these objects itself when firing `pageshow` or `pagehide` events.

Syntax
------

```js
new PageTransitionEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `pageshow` or `pagehide`.

`options` Optional

An object that, *in addition to the properties defined in `Event()`*, has the following property:

`persisted` Optional

A boolean indicating if the document is loading from a cache.

### Return value

A new `PageTransitionEvent` object.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-pagetransitionevent-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `pageshow` event
* `pagehide` event


DeviceMotionEvent: rotationRate property - Web APIs

DeviceMotionEvent: rotationRate property
========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`rotationRate`** read-only property of the `DeviceMotionEvent` interface returns the rate at which the device is rotating around each of its axes in degrees per
 second.

**Note:** If the hardware isn't capable of providing this
 information, this property returns `null`.

Value
-----

 The `rotationRate` property is a read only object describing the rotation
 rates of the device around each of its axes:

`alpha`

 The rate at which the device is rotating about its Z axis; that is, being twisted
 about a line perpendicular to the screen.

`beta`

The rate at which the device is rotating about its X axis; that is, front to back.

`gamma`

The rate at which the device is rotating about its Y axis; that is, side to side.

Specifications
--------------

| Specification |
| --- |
| DeviceOrientation Event Specification # ref-for-dom-devicemotionevent-rotationrate② |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Detecting device orientation
* Orientation and motion data explained
* `devicemotion` event


DeviceMotionEvent: DeviceMotionEvent() constructor - Web APIs

DeviceMotionEvent: DeviceMotionEvent() constructor
==================================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`DeviceMotionEvent()`** constructor creates a new `DeviceMotionEvent` object.

Syntax
------

```js
new DeviceMotionEvent(type)
new DeviceMotionEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `devicemotion`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`acceleration` Optional

A `DeviceMotionEventAcceleration` object giving the acceleration of the device on the three axis X, Y and Z. Acceleration is expressed in m/s². If not specified, every properties in the object will be `null`.

`accelerationIncludingGravity` Optional

A `DeviceMotionEventAcceleration` object giving the acceleration of the device on the three axis X, Y and Z with the effect of gravity. Acceleration is expressed in m/s². If not specified, every properties in the object will be `null`.

`rotationRate` Optional

A `DeviceMotionEventRotationRate` object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is express in degrees per seconds. If not specified, every properties in the object will be `null`.

`interval` Optional

A number representing the interval of time, in milliseconds, at which data is obtained from the device. It defaults to `0`.

### Return value

A new `DeviceMotionEvent` object.

Specifications
--------------

| Specification |
| --- |
| DeviceOrientation Event Specification # dom-devicemotionevent-devicemotionevent |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


DeviceMotionEvent: acceleration property - Web APIs

DeviceMotionEvent: acceleration property
========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`acceleration`** read-only property of the `DeviceMotionEvent` interface returns the amount of acceleration recorded by
 the device, in meters per second squared (m/s²).
 The acceleration value does not include the effect of
 the gravity force, in contrast to `DeviceMotionEvent.accelerationIncludingGravity`.

**Note:** If the hardware doesn't know how to remove gravity from the
 acceleration data, this value may not be present in the
 `DeviceMotionEvent`. In this situation, you'll need to use
 `DeviceMotionEvent.accelerationIncludingGravity` instead.

Value
-----

 The `acceleration` property is an object providing information about
 acceleration on three axis. Each axis is represented with its own property:

`x`

Represents the acceleration upon the x axis which is the west to east axis

`y`

Represents the acceleration upon the y axis which is the south to north axis

`z`

Represents the acceleration upon the z axis which is the down to up axis

Specifications
--------------

| Specification |
| --- |
| DeviceOrientation Event Specification # ref-for-dom-devicemotionevent-acceleration③ |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Detecting device orientation
* Orientation and motion data explained
* `devicemotion` event


DeviceMotionEvent: interval property - Web APIs

DeviceMotionEvent: interval property
====================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`interval`** read-only property of the `DeviceMotionEvent` interface returns the interval, in milliseconds, at which data is obtained from the underlying
 hardware. You can use this to determine the granularity of motion events.

Value
-----

A number representing the interval of time, in milliseconds.

Specifications
--------------

| Specification |
| --- |
| DeviceOrientation Event Specification # ref-for-dom-devicemotionevent-interval① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Detecting device orientation
* Orientation and motion data explained
* `devicemotion` event


DeviceMotionEvent: accelerationIncludingGravity property - Web APIs

DeviceMotionEvent: accelerationIncludingGravity property
========================================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`accelerationIncludingGravity`** read-only property of the `DeviceMotionEvent` interface returns the
 amount of acceleration recorded by the device, in meters per second squared (m/s²). Unlike `DeviceMotionEvent.acceleration`
 which compensates for the influence of gravity, its value is the sum of the acceleration
 of the device as induced by the user and an acceleration equal and opposite to that
 caused by gravity. In other words, it measures the
 g-force. In practice, this value represents
 the raw data measured by an accelerometer.

 This value is not typically as useful as `DeviceMotionEvent.acceleration`,
 but may be the only value available on devices that aren't able to remove gravity from
 the acceleration data, such as on devices that don't have a gyroscope.

**Note:** `accelerationIncludingGravity`'s name can be misleading. This property represents acceleration including *the effects of* gravity. For example, if a device is lying flat on a horizontal surface with the screen pointing up, gravity would be -9.8 along the Z axis, while `acceleration.z` would be 0 and `accelerationIncludingGravity.z` would be 9.8. Similarly, if a device is in free fall with its screen horizontal and pointing up, gravity would be -9.8 along the Z axis, while `acceleration.z` would be -9.8 and `accelerationIncludingGravity.z` would be 0.

Value
-----

 The `accelerationIncludingGravity` property is an object providing
 information about acceleration on three axis. Each axis is represented with its own
 property:

`x`

Represents the acceleration upon the x axis which is the west to east axis

`y`

Represents the acceleration upon the y axis which is the south to north axis

`z`

Represents the acceleration upon the z axis which is the down to up axis

Specifications
--------------

| Specification |
| --- |
| DeviceOrientation Event Specification # ref-for-dom-devicemotionevent-accelerationincludinggravity④ |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Detecting device orientation
* Orientation and motion data explained
* `devicemotion` event


PushSubscriptionOptions: applicationServerKey property - Web APIs

PushSubscriptionOptions: applicationServerKey property
======================================================

The **`applicationServerKey`** read-only property of the `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
--------------

| Specification |
| --- |
| Push API # dom-pushsubscriptionoptions-applicationserverkey |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.