repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/usbintransferresult/index.md
--- title: USBInTransferResult slug: Web/API/USBInTransferResult page-type: web-api-interface status: - experimental browser-compat: api.USBInTransferResult --- {{securecontext_header}}{{APIRef("WebUSB API")}}{{SeeCompatTable}} The `USBInTransferResult` interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides the result from a call to the `transferIn()` and `controlTransferIn()` methods of the `USBDevice` interface. It represents the result from requesting a transfer of data from the USB device to the USB host. ## Constructor - {{domxref("USBInTransferResult.USBInTransferResult", "USBInTransferResult()")}} {{Experimental_Inline}} - : Creates a new `USBInTransferResult` object with the provided `status` and `data` fields. ## Instance properties - {{domxref("USBInTransferResult.data")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a `DataView` object containing the data received from the USB device, if any. - {{domxref("USBInTransferResult.status")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the status of the transfer request, one of: - `"ok"` - The transfer was successful. - `"stall"` - The device indicated an error by generating a stall condition on the endpoint. A stall on the control endpoint does not need to be cleared. A stall on a bulk or interrupt endpoint must be cleared by calling `clearHalt()` before `transferIn()` can be called again. - `"babble"` - The device responded with more data than was expected. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgtrefelement/index.md
--- title: SVGTRefElement slug: Web/API/SVGTRefElement page-type: web-api-interface status: - deprecated browser-compat: api.SVGTRefElement --- {{APIRef("SVG")}}{{deprecated_header}} The **`SVGTRefElement`** interface corresponds to the {{SVGElement("tref")}} elements. Object-oriented access to the attributes of the {{SVGElement("tref")}} element via the SVG DOM is not possible. {{InheritanceDiagram}} ## Instance properties _This interface has no properties but inherits properties from its parent, {{domxref("</em>SVGTextPositioningElement<em>")}}._ ## Instance methods _This interface has no methods but inherits methods from its parent, {{domxref("</em>SVGTextPositioningElement<em>")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("tref")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/backgroundfetchupdateuievent/index.md
--- title: BackgroundFetchUpdateUIEvent slug: Web/API/BackgroundFetchUpdateUIEvent page-type: web-api-interface status: - experimental browser-compat: api.BackgroundFetchUpdateUIEvent --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`BackgroundFetchUpdateUIEvent`** interface of the {{domxref('Background Fetch API','','',' ')}} is an event type for the {{domxref("ServiceWorkerGlobalScope.backgroundfetchsuccess_event", "backgroundfetchsuccess")}} and {{domxref("ServiceWorkerGlobalScope.backgroundfetchfail_event", "backgroundfetchfail")}} events, and provides a method for updating the title and icon of the app to inform a user of the success or failure of a background fetch. {{InheritanceDiagram}} ## Constructor - {{domxref("BackgroundFetchUpdateUIEvent.BackgroundFetchUpdateUIEvent()", "BackgroundFetchUpdateUIEvent()")}} {{Experimental_Inline}} - : Creates a new `BackgroundFetchUIEvent` object. This constructor is not typically used, as the browser creates these objects itself for the {{domxref("ServiceWorkerGlobalScope.backgroundfetchsuccess_event", "backgroundfetchsuccess")}} and {{domxref("ServiceWorkerGlobalScope.backgroundfetchfail_event", "backgroundfetchfail")}} events. ## Instance properties _This interface doesn't implement any specific properties, but inherits properties from {{domxref("Event")}}, and {{domxref("BackgroundFetchEvent")}}._ ## Instance methods - {{domxref("BackgroundFetchUpdateUIEvent.updateUI()")}} {{Experimental_Inline}} - : Updates the title and icon in the user interface to show the status of a background fetch. Resolves with a {{jsxref("Promise")}}. ## Examples In this example, the `backgroundfetchsuccess` event is listened for, indicating that a fetch has completed successfully. The {{domxref("BackgroundFetchUpdateUIEvent.updateUI()", "updateUI()")}} method is then called, with a message to let the user know the episode they downloaded is ready. ```js addEventListener("backgroundfetchsuccess", (event) => { const bgFetch = event.registration; event.waitUntil( (async () => { // Create/open a cache. const cache = await caches.open("downloads"); // Get all the records. const records = await bgFetch.matchAll(); // Copy each request/response across. const promises = records.map(async (record) => { const response = await record.responseReady; await cache.put(record.request, response); }); // Wait for the copying to complete. await Promise.all(promises); // Update the progress notification. event.updateUI({ title: "Episode 5 ready to listen!" }); })(), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/backgroundfetchupdateuievent
data/mdn-content/files/en-us/web/api/backgroundfetchupdateuievent/updateui/index.md
--- title: "BackgroundFetchUpdateUIEvent: updateUI() method" short-title: updateUI() slug: Web/API/BackgroundFetchUpdateUIEvent/updateUI page-type: web-api-instance-method status: - experimental browser-compat: api.BackgroundFetchUpdateUIEvent.updateUI --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`updateUI()`** method of the {{domxref("BackgroundFetchUpdateUIEvent")}} interface updates the title and icon in the user interface to show the status of a background fetch. This method may only be run once, to notify the user on a failed or a successful fetch. ## Syntax ```js-nolint updateUI(options) ``` ### Parameters - `options` {{optional_inline}} - : An object containing any of the following: - `icons` {{optional_inline}} - : A list of one or more image resources, containing icons for use in the user interface. An image resource is an object containing: - `src` - : A string which is a URL of an image. - `sizes` {{optional_inline}} - : A string which is equivalent to a {{htmlelement("link")}} `sizes` attribute. - `type` {{optional_inline}} - : A string containing an image MIME type. - `label` {{optional_inline}} - : A string providing a name for the associated image. - `title` {{optional_inline}} - : A string containing the new title of the user interface. ### Return value A {{jsxref("Promise")}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Returned if any of the following are true: - The {{domxref("Event.isTrusted","isTrusted")}} property is `false`. - The {{domxref("BackgroundFetchUpdateUIEvent")}} UI updated flag is already set, indicating that the `updateUI()` method has already been called. - The {{domxref("BackgroundFetchUpdateUIEvent")}} is not active. ## Examples The following example demonstrates updating the UI with a title and image icon on a successful fetch. ```js addEventListener("backgroundfetchsuccess", (event) => { event.updateUI({ title: "Episode 5 ready to listen!", icon: { src: "path/to/success.ico", sizes: "16x16 32x32 64x64", }, }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/backgroundfetchupdateuievent
data/mdn-content/files/en-us/web/api/backgroundfetchupdateuievent/backgroundfetchupdateuievent/index.md
--- title: "BackgroundFetchUpdateUIEvent: BackgroundFetchUpdateUIEvent() constructor" short-title: BackgroundFetchUpdateUIEvent() slug: Web/API/BackgroundFetchUpdateUIEvent/BackgroundFetchUpdateUIEvent page-type: web-api-constructor status: - experimental browser-compat: api.BackgroundFetchUpdateUIEvent.BackgroundFetchUpdateUIEvent --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}} The **`BackgroundFetchUpdateUIEvent()`** constructor creates a new {{domxref("BackgroundFetchUpdateUIEvent")}} object. This constructor is not typically used as the browser creates these objects itself and provides them to background fetch event callbacks. ## Syntax ```js-nolint new BackgroundFetchEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers set it to `backgroundfetchsuccess` or `backgroundfetchfail`. - `options` - : An object that, _in addition of the properties defined in {{domxref("ExtendableEvent/ExtendableEvent", "ExtendableEvent()")}}_, has the following properties: - `registration` - : A {{domxref("BackgroundFetchRegistration")}} object. ### Return value A new {{domxref("BackgroundFetchUpdateUIEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/mediastreamtrackevent/index.md
--- title: MediaStreamTrackEvent slug: Web/API/MediaStreamTrackEvent page-type: web-api-interface browser-compat: api.MediaStreamTrackEvent --- {{APIRef("Media Capture and Streams")}} The **`MediaStreamTrackEvent`** interface of the {{domxref("Media Capture and Streams API", "", "", "nocode")}} represents events which indicate that a {{domxref("MediaStream")}} has had tracks added to or removed from the stream through calls to [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API) methods. These events are sent to the stream when these changes occur. {{InheritanceDiagram}} The events based on this interface are {{domxref("MediaStream/addtrack_event", "addtrack")}} and {{domxref("MediaStream/removetrack_event", "removetrack")}}. ## Constructor - {{domxref("MediaStreamTrackEvent.MediaStreamTrackEvent", "MediaStreamTrackEvent()")}} - : Constructs a new `MediaStreamTrackEvent` with the specified configuration. ## Instance properties _Also inherits properties from its parent interface, {{domxref("Event")}}._ - {{domxref("MediaStreamTrackEvent.track")}} {{ReadOnlyInline}} - : Returns a {{domxref("MediaStreamTrack")}} object representing the track associated with the event. ## Instance methods _Also inherits methods from its parent interface, {{domxref("Event")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaStream")}}: {{domxref("MediaStream/addtrack_event", "addtrack")}} and {{domxref("MediaStream/removetrack_event", "removetrack")}} events - {{domxref("MediaStreamTrack")}} - [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
0
data/mdn-content/files/en-us/web/api/mediastreamtrackevent
data/mdn-content/files/en-us/web/api/mediastreamtrackevent/mediastreamtrackevent/index.md
--- title: "MediaStreamTrackEvent: MediaStreamTrackEvent() constructor" short-title: MediaStreamTrackEvent() slug: Web/API/MediaStreamTrackEvent/MediaStreamTrackEvent page-type: web-api-constructor browser-compat: api.MediaStreamTrackEvent.MediaStreamTrackEvent --- {{APIRef("Media Capture and Streams")}} The **`MediaStreamTrackEvent()`** constructor returns a new {{domxref("MediaStreamTrackEvent")}} object, which represents an event signaling that a {{domxref("MediaStreamTrack")}} has been added to or removed from a {{domxref("MediaStream")}}. ## Syntax ```js-nolint new MediaStreamTrackEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers set it to `addtrack` or `removetrack`. - `options` - : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties: - `track` - : A {{domxref("MediaStreamTrack")}} object representing the track which was added to or removed from the stream. ### Return value A new {{domxref("MediaStreamTrackEvent")}} object, initialized based on the provided options. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaStream/addtrack_event", "addtrack")}} and {{domxref("MediaStream/removetrack_event", "removetrack")}} events - {{domxref("MediaStreamTrack")}} - {{domxref("MediaStream")}} - [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
0
data/mdn-content/files/en-us/web/api/mediastreamtrackevent
data/mdn-content/files/en-us/web/api/mediastreamtrackevent/track/index.md
--- title: "MediaStreamTrackEvent: track property" short-title: track slug: Web/API/MediaStreamTrackEvent/track page-type: web-api-instance-property browser-compat: api.MediaStreamTrackEvent.track --- {{APIRef("Media Capture and Streams")}} The **`track`** read-only property of the {{domxref("MediaStreamTrackEvent")}} interface returns the {{domxref("MediaStreamTrack")}} associated with this event. ## Value A {{domxref("MediaStreamTrack")}} object. ## Examples ```js const stream = new MediaStream(); stream.addEventListener("removetrack", (event) => { console.log(`${event.track.kind} track removed`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaStream/addtrack_event", "addtrack")}} and {{domxref("MediaStream/removetrack_event", "removetrack")}} events - {{domxref("MediaStreamTrack")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/speculation_rules_api/index.md
--- title: Speculation Rules API slug: Web/API/Speculation_Rules_API page-type: web-api-overview status: - experimental browser-compat: - api.Document.prerendering - api.Document.prerenderingchange_event - html.elements.script.type.speculationrules spec-urls: - https://wicg.github.io/nav-speculation/speculation-rules.html - https://wicg.github.io/nav-speculation/prerendering.html --- {{SeeCompatTable}}{{DefaultAPISidebar("Speculation Rules API")}} The **Speculation Rules API** is designed to improve performance for future navigations. It targets document URLs rather than specific resource files, and so makes sense for multi-page applications (MPAs) rather than single-page applications (SPAs). The Speculation Rules API provides an alternative to the widely-available [`<link rel="prefetch">`](/en-US/docs/Web/HTML/Attributes/rel/prefetch) feature and is designed to supersede the Chrome-only deprecated [`<link rel="prerender">`](/en-US/docs/Web/HTML/Attributes/rel/prerender) feature. It provides many improvements over these technologies, along with a more expressive, configurable syntax for specifying which documents should be prefetched or prerendered. > **Note:** The Speculation Rules API doesn't handle subresource prefetches; for that you'll need to use `<link rel="prefetch">`. ## Concepts and usage Speculation rules are specified inside [`<script type="speculationrules"> ... </script>`](/en-US/docs/Web/HTML/Element/script/type/speculationrules). The rules are specified as a JSON structure. For example: ```html <script type="speculationrules"> { "prerender": [ { "source": "list", "urls": ["extra.html", "extra2.html"] } ], "prefetch": [ { "source": "list", "urls": ["next.html", "next2.html"], "requires": ["anonymous-client-ip-when-cross-origin"], "referrer_policy": "no-referrer" } ] } </script> ``` You specify a different array to contain the rules for each speculative loading type (for example `"prerender"` or `"prefetch"`). Each rule is contained in an object that specifies for example a list of resources to be fetched, plus options such as an explicit {{httpheader("Referrer-Policy")}} setting for each rule. Note that prerendered URLs are also prefetched. See [`<script type="speculationrules">`](/en-US/docs/Web/HTML/Element/script/type/speculationrules) for a full explanation of the available syntax. > **Note:** As speculation rules use a `<script>` element, they need to be explicitly allowed in the {{httpheader("Content-Security-Policy")}} [`script-src`](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) directive if the site includes it. This is done by adding the `'inline-speculation-rules'` source along with a hash- or nonce-source. ### Using prefetching Including `prefetch` rules inside `<script type=speculationrules> ... </script>` will cause supporting browsers to download the response body of the referenced pages, but none of the subresources referenced by the page. When a prefetched page is navigated to, it will render much more quickly than if it were not prefetched. The results are kept in a per-document in-memory cache. Any cached prefetches are discarded when you navigate away from the current page, except of course a prefetched document that you then navigate to. This means that if you prefetch something the user doesn't navigate to, it is generally a waste of resources, although the result may populate the HTTP cache if headers allow. That said, the upfront cost of a prefetch is much smaller than the upfront cost of a prerender, so you are encouraged to adopt prefetching broadly, for example prefetching all of the significant pages on your site, provided they are safe to prefetch (see [Unsafe speculative loading conditions](#unsafe_speculative_loading_conditions) for more details). Same-site and cross-site prefetches will work, but cross-site prefetches are limited (see ["same-site" and "cross-site"](https://web.dev/articles/same-site-same-origin#same-site-cross-site) for an explanation of the difference between the two). For privacy reasons cross-site prefetches will currently only work if the user has no cookies set for the destination site β€” we don't want sites to be able to track user activity via prefetched pages (which they may never even actually visit) based on previously-set cookies. > **Note:** In the future an opt-in will be provided via the {{httpheader("Supports-Loading-Mode")}} header, but this was not implemented at the time of writing. For browsers that support it, speculation rules prefetch should be preferred over older prefetch mechanisms, namely [`<link rel="prefetch">`](/en-US/docs/Web/HTML/Attributes/rel/prefetch) and {{domxref("fetch()")}} with a `priority: "low"` option set on it. Because we know that speculation rules prefetch is for navigations, not general resource prefetching: - It can be used for cross-site navigations, whereas `<link rel="prefetch">` cannot. - It doesn't get blocked by {{httpheader("Cache-Control")}} headers, whereas `<link rel="prefetch">` often does. In addition, speculation rules prefetch: - Automatically lowers the priority when needed (`fetch()` doesn't). - Is respectful of the user's configuration. For example, prefetching doesn't happen when the user's device is in Battery Saver or Data Saver mode. - Stores the prefetched resources in a per-document in-memory cache as opposed to the HTTP cache, which may result in slightly faster prefetching. ### Using prerendering Including `prerender` rules inside `<script type=speculationrules> ... </script>` will cause supporting browsers to fetch, render, and load the content into an invisible tab, stored in a per-document in-memory cache. This includes loading all subresources, running all JavaScript, and even loading subresources and performing data fetches started by JavaScript. Any cached prerenders and their subresources are discarded when you navigate away from the current page, except of course a prerendered document that you then navigate to. Future navigations to a prerendered page will be near-instant. The browser activates the invisible tab instead of carrying out the usual navigation process, replacing the old foreground page with the prerendered page. If a page is activated before it has fully prerendered, it is activated in its current state and then continues to load, which means you will still see a significant performance improvement. Prerendering uses memory and network bandwidth. If you prerender something the user doesn't navigate to, these are wasted (although the result may populate the HTTP cache if headers allow, allowing later use). The upfront cost of a prerender is much larger than the upfront cost of a prefetch, and there are more conditions that could make content unsafe to prerender (see [Unsafe speculative loading conditions](#unsafe_speculative_loading_conditions) for more details). As a result, you are encouraged to adopt prerendering more sparingly, carefully considering cases where there is a high likelihood of the page being navigated to, and you think the user experience benefit is worth the extra cost. > **Note:** To put the amount of potential resource wastage in perspective, a prerender uses about the same amount of resources as rendering an {{htmlelement("iframe")}}. > **Note:** Many APIs will be automatically deferred when prerendering/until activation. See [Platform features deferred or restricted during prerender](#platform_features_deferred_or_restricted_during_prerender) for more details. Prerendering is restricted to same-origin documents by default. Cross-origin, same-site prerendering is possible β€” it requires the navigation target to opt-in using the {{httpheader("Supports-Loading-Mode")}} header with a value of `credentialed-prerender`. Cross-site prerendering is not possible at this time. For browsers that support it, speculation rules prerender should be preferred over older prerender mechanisms, namely [`<link rel="prerender">`](/en-US/docs/Web/HTML/Attributes/rel/prerender): - `<link rel="prerender">` is Chrome-specific and was never standardized, and the Chrome engineering team are in the process of sunsetting it. {{experimental_inline}} - It loads subresources loaded via JavaScript, whereas `<link rel="prerender">` doesn't. - It doesn't get blocked by {{httpheader("Cache-Control")}} settings, whereas `<link rel="prerender">` often does. - Speculation rules prerender should be treated as a hint and a progressive enhancement. Unlike `<link rel="prerender">`, it is a speculative hint and the browser may choose not to act upon the hint based on user settings, current memory usage, or other heuristics. ### Speculation rules API feature detection You can check if the Speculation Rules API is supported using the following code: ```js if ( HTMLScriptElement.supports && HTMLScriptElement.supports("speculationrules") ) { console.log("Your browser supports the Speculation Rules API."); } ``` For example, you might want to insert speculation rules for prefetching in supporting browsers, but use an older technology such as `<link rel="prefetch">` in others: ```js if ( HTMLScriptElement.supports && HTMLScriptElement.supports("speculationrules") ) { const specScript = document.createElement("script"); specScript.type = "speculationrules"; const specRules = { prefetch: [ { source: "list", urls: ["/next.html"], }, ], }; specScript.textContent = JSON.stringify(specRules); document.body.append(specScript); } else { const linkElem = document.createElement("link"); linkElem.rel = "prefetch"; linkElem.href = "/next.html"; document.head.append(linkElem); } ``` ## Detecting prefetched and prerendered pages This section looks at different ways to detect whether a requested page has been prefetched or prerendered. ### Server-side detection Prefetched and prerendered page requests are sent with the {{httpheader("Sec-Purpose")}} request header: For prefetch: ```http Sec-Purpose: prefetch ``` For prerender: ```http Sec-Purpose: prefetch;prerender ``` Servers can respond based on this header, for example to log speculative load requests, return different content, or even prevent the speculative loading from happening. If a non-success response code is returned (not 200 or 304), then the page will not be prefetched/prerendered. This is the easiest way to prevent speculative loading, although it is usually a better approach to allow the prefetch/prerender, but delay any actions that should only happen then the page is actually viewed, using JavaScript. ### JavaScript prefetch detection When a page is prefetched, its {{domxref("PerformanceResourceTiming.deliveryType")}} entry will return a value of `"navigational-prefetch"`. You could use the following to run a function when a performance entry of type `"navigational-prefetch"` is received: ```js if ( performance.getEntriesByType("navigation")[0].deliveryType === "navigational-prefetch" ) { respondToPrefetch(); // Author-defined function } ``` This technique is useful when measuring performance, or when you want to defer actions that might cause problems if they occur during prefetching (see [Unsafe prefetching](#unsafe_prefetching)). ### JavaScript prerender detection To run an activity while the page is prerendering, you can check for the {{domxref("Document.prerendering")}} property. You could for example run some analytics: ```js if (document.prerendering) { analytics.sendInfo("got this far during prerendering!"); } ``` When a prerendered document is activated, {{domxref("PerformanceNavigationTiming.activationStart")}} is set to a {{domxref("DOMHighResTimeStamp")}} representing the time between when the prerender was started and the document was actually activated. The following function can check for prerendering _and_ prerendered pages: ```js function pagePrerendered() { return ( document.prerendering || self.performance?.getEntriesByType?.("navigation")[0]?.activationStart > 0 ); } ``` When the prerendered page is activated by the user viewing the page, the {{domxref("Document.prerenderingchange_event", "prerenderingchange")}} event will fire. This can be used to enable activities that previously would be started by default on page load but which you wish to delay until the page is actually viewed by the user. The following code sets up an event listener to run a function once prerendering has finished, on a prerendered page, or runs it immediately on a non-prerendered page: ```js if (document.prerendering) { document.addEventListener("prerenderingchange", initAnalytics, { once: true, }); } else { initAnalytics(); } ``` ## Unsafe speculative loading conditions This section covers conditions to look out for, under which prefetching and/or prerendering are **unsafe**. This means that prefetching/prerendering pages that exhibit these conditions may require mitigations in your code, or need to be avoided altogether. ### Unsafe prefetching As mentioned earlier, we recommend adopting prefetching broadly, as the risk to reward ratio is fairly low β€” the potential for resource wastage is minimal, and the performance improvements can be significant. However, you need to make sure prefetched pages do not cause problems with the flow of your application. When a prefetch is done, the browser downloads the response body of the referenced page via a single GET request, which the user may navigate to at a future time. Problems can arise specifically when the URL of the request performs a server-initiated side effect that you don't want to happen until the URL is actually navigated to. For example: - Sign-out URLs. - Language switching URLs. - "Add to cart" URLs. - Sign-in flow URLs where the server causes an SMS to be sent, for example as a one-time password (OTP). - URLs that increment a user's usage allowance numbers, such as consuming their monthly free article allowance or starting the timer on their monthly minutes. - URLs that initiate server-side ad conversion tracking. Such issues can be mitigated on the server by watching for the {{httpheader("Sec-Purpose", "Sec-Purpose: prefetch")}} header as the requests come in, and then running specific code to defer problematic functionality. Later on, when the page is actually navigated to, you can initiate the deferred functionality via JavaScript if needed. > **Note:** You can find more details about the detection code in the [Detecting prefetched and prerendered pages](#detecting_prefetched_and_prerendered_pages) section. If the functionality only occurs under normal circumstances when JavaScript runs, then prefetching is safe, since the JavaScript will not run until activation. It is also potentially risky to prefetch a document whose server-rendered contents will change due to actions the user can take on the current page. This could include, for example, flash sale pages or movie theater seat maps. Test such cases carefully, and mitigate such issues by updating content once the page is loaded. See [Server-rendered varying state](#server-rendered_varying_state) for more details about these cases. > **Note:** Browsers will cache prefetched pages for a short time (Chrome for example caches them for 5 minutes) before discarding them, so in any case, your users might see content that is up to 5 minutes out of date. One final tip is to audit the URLs listed as disallowed in your {{glossary("robots.txt")}} file β€” normally these URLs point to pages that can only be accessed by authenticated users, and therefore should not be included in search engine results. Many of these will be fine, but it can be a good place to find URLs unsafe for prefetching (i.e. they exhibit the conditions described above). ### Unsafe prerendering Prerendering is more risky to adopt than prefetching and should therefore be done more sparingly, in cases where it is worth it. There are more unsafe conditions to watch out for with prerendering so, while the reward is higher, the risk is too. When a prerender is done, the browser GETs the URL and renders and loads the content into an invisible tab. This includes running the content's JavaScript and loading all subresources, including those fetched by JavaScript. Content can be potentially unsafe to prerender if any of the following conditions are observed: - The URL is [unsafe to prefetch](#unsafe_prefetching). Read the previous section first if you haven't already, and understand that these conditions also equally apply to unsafe prerendering. - The page's JavaScript modifies client-side storage (for example [Web Storage](/en-US/docs/Web/API/Web_Storage_API) or [IndexedDB](/en-US/docs/Web/API/IndexedDB_API)) on load in a way that may cause confusing effects in other, non-prerendered pages that the user is currently looking at. - The page runs JavaScript or loads images that cause side effects such as sending analytics, recording ad impressions, or otherwise modifying the state of the application as if the user had already interacted with it. Again, this can affect the flow of the application, or cause incorrect performance or usage reporting. See [Server-rendered varying state](#server-rendered_varying_state) for more details about such use cases. To mitigate such problems, you can use the following techniques: - Watch for the {{httpheader("Sec-Purpose", "Sec-Purpose: prefetch")}} header on the server as the requests come in, and then run specific code to defer problematic functionality. - Use the {{domxref("Document.prerenderingchange_event", "prerenderingchange")}} event to detect when the prerendered page is actually activated and run code as a result. This is useful in two cases: - Deferring code that may cause problems if it is run before the page is viewed. For example, you may want to wait until after activation to update client-side storage or modify server-side state using JavaScript. This can avoid situations when the UI and the application state become out of sync with one another, for example a shopping cart showing no items even though the user has added some. - If the above is not possible, then you could still rerun code after the page is activated to bring the app up-to-date again. For example, a highly-dynamic flash sale page might rely on content updates coming in from a third-party library. If you can't delay the updates, you can always get fresh updates once the user views the page. Prerendered pages can be updated in real time using the [Broadcast Channel API](/en-US/docs/Web/API/Broadcast_Channel_API), or another mechanism such as {{domxref("fetch()")}} or a {{domxref("WebSocket")}}. This guarantees that the user will see up-to-date content after prerendering activation. - Manage your third-party analytics scripts carefully β€” if possible, use scripts that are prerendering-aware (for example use the {{domxref("Document.prerendering")}} property to defer running on prerendering pages) such as Google Analytics or NewRelic. - Note that cross-origin {{htmlelement("iframe")}} loads are delayed while prerendering, therefore most other third-party widgets such as adtech are actually safe to use while prerendering. - For third-party scripts that are not prerendering-aware, avoid loading them until after activation using the {{domxref("Document.prerenderingchange_event", "prerenderingchange")}} event, as mentioned earlier. ### Server-rendered varying state There are two main types of server-rendered state to be concerned with: **outdated state**, and **user-specific state**. This can cause both unsafe prefetching and prerendering. - Outdated state: Consider the example of a server-rendered list of blog comments, which may become out of date between the blog post being prerendered, and it being viewed. This might be particularly problematic if the current page is an admin panel where the user is deleting spam comments. If the user then navigates to the blog post, they might be confused as to why they can see the spam comments they just deleted. - User-specific state: Consider the example of tracking sign-in state via a cookie. Problems can arise like the following: - The user visits `https://site.example/a` in tab 1 and `https://site.example/b` in tab 2, while logged out. - `https://site.example/b` prerenders `https://site.example/c`. It will be prerendered in a logged-out state. - The user signs in to `https://site.example` in tab 1. - The user switches to tab 2 and clicks the link to `https://site.example/c`, which activates the prerendered page. - Tab 2 displays a signed-out view of `https://site.example/c`, which confuses the user since they thought they were logged in. User-specific state problems can occur for other user settings, for example language settings, dark-mode preferences, or adding items to a cart. They can also occur when only a single tab is involved: - Let's say the user visits `https://site.example/product`. - `https://site.example.com/product` prerenders `https://site.example.com/cart`. It prerenders with 0 items in the cart. - The user clicks on the "Add to cart" buttons, which initiates a fetch request to add the item to the user's cart (with no page reload). - The user clicks on the link to `https://site.example.com/cart`, which activates the prerendered page. - The user sees an empty cart, even though they just added something to it. The best mitigation for these cases, and indeed any time when content can get out of sync with the server, is for pages to refresh themselves as needed. For example, a server might use the [Broadcast Channel API](/en-US/docs/Web/API/Broadcast_Channel_API), or another mechanism such as {{domxref("fetch()")}} or a {{domxref("WebSocket")}}. Pages can then update themselves appropriately, including speculatively loaded pages that have not yet activated. ## Session history behavior for prerendered documents Activating a prerendering/prerendered document behaves like any conventional navigation, from the end-user perspective. The activated document is displayed in the tab and appended to session history, and any existing forward history entries are pruned. Any navigations taking place within the prerendering browsing context _before_ activation do not affect the session history. From the developer's perspective, a prerendering document can be thought of as having a **trivial session history** where only one entry β€” the current entry β€” exists. All navigations within the prerendering context are effectively replaced. While API features that operate on session history (for example {{domxref("History")}} and {{domxref("Navigation")}}) can be called within prerendering documents, they only operate on the context's trivial session history. Consequently, prerendering documents do not take part in their referring page's joint session history. For example, they cannot navigate their referrer via {{domxref("History.back()")}}. This design ensures that users get the expected experience when using the back button β€” i.e. that they are taken back to the last thing they saw. Once a prerendering document is activated, only a single session history entry gets appended to the joint session history, ignoring any previous navigations that happened within the prerendering browsing context. Going back one step in the joint session history β€” for example by pressing the back button β€” takes the user back to the referrer page. ## Platform features deferred or restricted during prerender Because a prerendered page is opened in a hidden state, a number of APIs and other web platform features that cause potentially intrusive behaviors are not activated in this state, and are instead deferred until the page is activated or restricted altogether. In the small number of cases where this is not yet possible, the prerender is canceled. ### Asynchronous API deferral The following asynchronous features' results are deferred in prerendered documents until they are activated: - [Audio Output Devices API](/en-US/docs/Web/API/Audio_Output_Devices_API): {{domxref("MediaDevices.selectAudioOutput()")}} - [Background Fetch API](/en-US/docs/Web/API/Background_Fetch_API): {{domxref("BackgroundFetchManager.fetch()")}} - [Broadcast Channel API](/en-US/docs/Web/API/Broadcast_Channel_API): {{domxref("BroadcastChannel.postMessage()")}} - [Credential Management API](/en-US/docs/Web/API/Credential_Management_API): {{domxref("CredentialsContainer.create()")}}, {{domxref("CredentialsContainer.get()")}}, {{domxref("CredentialsContainer.store()")}} - [Encrypted Media Extensions API](/en-US/docs/Web/API/Encrypted_Media_Extensions_API): {{domxref("Navigator.requestMediaKeySystemAccess()")}} - [Gamepad API](/en-US/docs/Web/API/Gamepad_API): {{domxref("Navigator.getGamepads()")}}, {{domxref("Window.gamepadconnected_event", "gamepadconnected")}} event, {{domxref("Window.gamepaddisconnected_event", "gamepaddisconnected")}} event - [Geolocation API](/en-US/docs/Web/API/Geolocation_API): {{domxref("Geolocation.getCurrentPosition()")}}, {{domxref("Geolocation.watchPosition()")}}, {{domxref("Geolocation.clearWatch()")}} - {{domxref("HTMLMediaElement")}} API: The playback position will not advance while the containing document is prerendering - [Idle Detection API](/en-US/docs/Web/API/Idle_Detection_API): {{domxref("IdleDetector.start()")}} - [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API): {{domxref("MediaDevices.getUserMedia()")}} (and the legacy {{domxref("Navigator.getUserMedia()")}} version), {{domxref("MediaDevices.enumerateDevices()")}} - [Notifications API](/en-US/docs/Web/API/Notifications_API): {{domxref("Notification.Notification", "Notification()")}} constructor, {{domxref("Notification/requestPermission_static", "Notification.requestPermission()")}} - [Push API](/en-US/docs/Web/API/Push_API): {{domxref("PushManager.subscribe()")}} - [Screen Orientation API](/en-US/docs/Web/API/Screen_Orientation_API): {{domxref("ScreenOrientation.lock()")}}, {{domxref("ScreenOrientation.unlock()")}} - [Sensor APIs](/en-US/docs/Web/API/Sensor_APIs): {{domxref("Sensor.start()")}} - [Service Worker API](/en-US/docs/Web/API/Service_Worker_API): {{domxref("ServiceWorker.postMessage()")}}, {{domxref("ServiceWorkerContainer.register()")}}, {{domxref("ServiceWorkerRegistration.update()")}}, {{domxref("ServiceWorkerRegistration.unregister()")}} - [Storage API](/en-US/docs/Web/API/Storage_API): {{domxref("StorageManager.persist()")}} - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API): {{domxref("AudioContext")}}s are not allowed to start while the containing document is prerendering - [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API): {{domxref("Bluetooth.getDevices()")}}, {{domxref("Bluetooth.requestDevice()")}} - [WebHID API](/en-US/docs/Web/API/WebHID_API): {{domxref("HID.getDevices()")}}, {{domxref("HID.requestDevice()")}} - [Web Locks API](/en-US/docs/Web/API/Web_Locks_API): {{domxref("LockManager.query()")}}, {{domxref("LockManager.request()")}} - [Web MIDI API](/en-US/docs/Web/API/Web_MIDI_API): {{domxref("Navigator.requestMIDIAccess()")}} - [Web NFC API](/en-US/docs/Web/API/Web_NFC_API): {{domxref("NDefReader.write()")}}, {{domxref("NDefReader.scan()")}} - [Web Serial API](/en-US/docs/Web/API/Web_Serial_API): {{domxref("Serial.getPorts()")}}, {{domxref("Serial.requestPort()")}} - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API): {{domxref("SpeechRecognition.abort()")}}, {{domxref("SpeechRecognition.start()")}}, {{domxref("SpeechRecognition.stop()")}}, {{domxref("SpeechSynthesis.cancel()")}}, {{domxref("SpeechSynthesis.pause()")}}, {{domxref("SpeechSynthesis.resume()")}}, {{domxref("SpeechSynthesis.speak()")}} - [WebUSB API](/en-US/docs/Web/API/WebUSB_API): {{domxref("USB.getDevices()")}}, {{domxref("USB.requestDevice()")}} - [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API): {{domxref("XRSystem.requestSession()")}} ### Implicitly restricted APIs The following features will automatically fail or no-op in documents that are not activated. APIs that require {{glossary("transient activation")}} or {{glossary("sticky activation")}}: - Confirmation dialogs generated by the {{domxref("Window.beforeunload_event", "beforeunload")}} event - The firing of any events in the [Clipboard API](/en-US/docs/Web/API/Clipboard_API). - [File System API](/en-US/docs/Web/API/File_System_API): {{domxref("Window.showDirectoryPicker()")}}, {{domxref("Window.showOpenFilePicker()")}}, {{domxref("Window.showSaveFilePicker()")}} - [Fullscreen API](/en-US/docs/Web/API/Fullscreen_API): {{domxref("Element.requestFullscreen()")}} - [Idle Detection API](/en-US/docs/Web/API/Idle_Detection_API): {{domxref("IdleDetector/requestPermission_static", "IdleDetector.requestPermission()")}} - [Keyboard API](/en-US/docs/Web/API/Keyboard_API): {{domxref("Keyboard.lock()")}} (which requires fullscreen) - [Payment Request API](/en-US/docs/Web/API/Payment_Request_API): {{domxref("PaymentRequest.show()")}} - [Presentation API](/en-US/docs/Web/API/Presentation_API): {{domxref("PresentationRequest.start()")}} - [Pointer Lock API](/en-US/docs/Web/API/Pointer_Lock_API): {{domxref("Element.requestPointerLock()")}} - [Screen Capture API](/en-US/docs/Web/API/Screen_Capture_API): {{domxref("MediaDevices.getDisplayMedia()")}} - [Web Share API](/en-US/docs/Web/API/Web_Share_API): {{domxref("Navigator.share()")}} - {{domxref("Window.open()")}} APIs that require the containing document to be focused: - [Clipboard API](/en-US/docs/Web/API/Clipboard_API): {{domxref("Clipboard.read()")}}, {{domxref("Clipboard.readText()")}}, {{domxref("Clipboard.write()")}}, {{domxref("Clipboard.writeText()")}} APIs that require the containing document's {{domxref("Document.visibilityState")}} to be `"visible"`: - [Picture-in-Picture API](/en-US/docs/Web/API/Picture-in-Picture_API): {{domxref("HTMLVideoElement.requestPictureInPicture()")}} (requires the containing document's visibility state to be `"visible", _or_ {{glossary("transient activation")}}) - [Screen Wake Lock API](/en-US/docs/Web/API/Screen_Wake_Lock_API): {{domxref("WakeLock.request()")}} ### Other restricted features - Download links, i.e. {{htmlelement("a")}} and {{htmlelement("area")}} elements with the `download` attribute, will have their downloads delayed until prerendering has finished. - No cross-site navigations: Any prerendering document that navigates to a different site will be immediately discarded before a request to that other site is sent. - Restricted URLs: Prerendering documents cannot host non-HTTP(S) top-level URLs. Including the following URL types will cause the prerender to be immediately discarded: - `javascript:` URLs - `data:` URLs - `blob:` URLs - `about:` URLs, including `about:blank` and `about:srcdoc` - Session storage: {{domxref("Window.sessionStorage")}} can be used, but the behavior is very specific, to avoid breaking sites that expect only one page to access the tab's session storage at a time. A prerendered page therefore starts out with a clone of the tab's session storage state from when it was created. Upon activation, the prerendered page's storage clone is discarded, and the tab's main storage state is used instead. Pages that use session storage can use the {{domxref("Document.prerenderingchange_event", "prerenderingchange")}} event to detect when this storage swap occurs. - {{domxref("Window.print()")}}: Any calls to this method are ignored. - "Simple dialog methods" are restricted as follows: - {{domxref("Window.alert()")}} immediately returns without showing a dialog. - {{domxref("Window.confirm()")}} immediately returns `false` without showing a dialog. - {{domxref("Window.prompt()")}} immediately returns an empty string (`""`) without showing a dialog. - Dedicated/shared worker scripts are loaded, but their execution is deferred until the prerendered document is activated. - Cross-origin {{htmlelement("iframe")}} loads are delayed while prerendering until after the page is activated. ## Interfaces The Speculation Rules API does not define any interfaces of its own. ### Extensions to other interfaces - {{domxref("Document.prerendering")}} {{experimental_inline}} - : A boolean property that returns `true` if the document is currently in the process of prerendering. - {{domxref("Document.prerenderingchange_event", "prerenderingchange")}} event {{experimental_inline}} - : Fired on a prerendered document when it is activated (i.e. the user views the page). - {{domxref("PerformanceNavigationTiming.activationStart")}} {{experimental_inline}} - : A number representing the time between when a document starts prerendering and when it is activated. - {{domxref("PerformanceResourceTiming.deliveryType")}} `"navigational-prefetch"` value {{experimental_inline}} - : Signals that the type of a performance entry is a prefetch. ## HTTP headers - {{httpheader("Content-Security-Policy")}} `'inline-speculation-rules'` value {{experimental_inline}} - : Used to opt-in to allowing usage of `<script type="speculationrules">` to define speculation rules on the document being fetched. - {{httpheader("Supports-Loading-Mode")}} {{experimental_inline}} - : Set by a navigation target to opt-in to using various higher-risk loading modes. For example, cross-origin, same-site prerendering requires a `Supports-Loading-Mode` value of `credentialed-prerender`. ## HTML features - [`<script type="speculationrules"> ... </script>`](/en-US/docs/Web/HTML/Element/script/type/speculationrules) {{experimental_inline}} - : Used to define a set of prefetch and/or prerender speculation rules on the current document. ## Examples You can find a [complete prerender demo here](https://prerender-demos.glitch.me/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Prerender pages in Chrome for instant page navigations](https://developer.chrome.com/blog/prerender-pages/) on developer.chrome.com (2023) - [Speculative loading](/en-US/docs/Web/Performance/Speculative_loading) for a comparison of speculation rules and other similar performance improvement features.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfeoffsetelement/index.md
--- title: SVGFEOffsetElement slug: Web/API/SVGFEOffsetElement page-type: web-api-interface browser-compat: api.SVGFEOffsetElement --- {{APIRef("SVG")}} The **`SVGFEOffsetElement`** interface corresponds to the {{SVGElement("feOffset")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGFEOffsetElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element. - {{domxref("SVGFEOffsetElement.in1")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element. - {{domxref("SVGFEOffsetElement.dx")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("dx")}} attribute of the given element. - {{domxref("SVGFEOffsetElement.dy")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("dy")}} attribute of the given element. - {{domxref("SVGFEOffsetElement.result")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element. - {{domxref("SVGFEOffsetElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element. - {{domxref("SVGFEOffsetElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGFEOffsetElement.y")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element. ## Instance methods _This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("feOffset")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svganimatedpreserveaspectratio/index.md
--- title: SVGAnimatedPreserveAspectRatio slug: Web/API/SVGAnimatedPreserveAspectRatio page-type: web-api-interface browser-compat: api.SVGAnimatedPreserveAspectRatio --- {{APIRef("SVG")}} ## SVG animated preserveAspectRatio interface The `SVGAnimatedPreserveAspectRatio` interface is used for attributes of type {{ domxref("SVGPreserveAspectRatio") }} which can be animated. ### Interface overview <table class="standard-table"> <tbody> <tr> <th scope="row">Also implement</th> <td><em>None</em></td> </tr> <tr> <th scope="row">Methods</th> <td><em>None</em></td> </tr> <tr> <th scope="row">Properties</th> <td> <ul> <li>readonly float <code>baseVal</code></li> <li>readonly float <code>animVal</code></li> </ul> </td> </tr> <tr> <th scope="row">Normative document</th> <td> <a href="https://www.w3.org/TR/SVG11/coords.html#InterfaceSVGAnimatedPreserveAspectRatio" >SVG 1.1 (2nd Edition)</a > </td> </tr> </tbody> </table> ## Instance properties - {{domxref("SVGAnimatedPreserveAspectRatio.baseVal")}} {{ReadOnlyInline}} - : A {{domxref("SVGPreserveAspectRatio")}} that represents the base value of the given attribute before applying any animations. - {{domxref("SVGAnimatedPreserveAspectRatio.animVal")}} {{ReadOnlyInline}} - : A {{domxref("SVGPreserveAspectRatio")}} that represents the current animated value of the given attribute. If the given attribute is not currently being animated, then the {{ domxref("SVGPreserveAspectRatio") }} will have the same contents as `baseVal`. The object referenced by `animVal` is always distinct from the one referenced by `baseVal`, even when the attribute is not animated. ## Instance methods The `SVGAnimatedPreserveAspectRatio` interface do not provide any specific methods. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtcpeerconnection/index.md
--- title: RTCPeerConnection slug: Web/API/RTCPeerConnection page-type: web-api-interface browser-compat: api.RTCPeerConnection --- {{APIRef('WebRTC')}} The **`RTCPeerConnection`** interface represents a WebRTC connection between the local computer and a remote peer. It provides methods to connect to a remote peer, maintain and monitor the connection, and close the connection once it's no longer needed. {{InheritanceDiagram}} ## Constructor - {{DOMxRef("RTCPeerConnection.RTCPeerConnection", "RTCPeerConnection()")}} - : Returns a new `RTCPeerConnection`, representing a connection between the local device and a remote peer. ## Instance properties _Also inherits properties from {{DOMxRef("EventTarget")}}._ - {{DOMxRef("RTCPeerConnection.canTrickleIceCandidates", "canTrickleIceCandidates")}} {{ReadOnlyInline}} - : Returns a boolean value which indicates whether or not the remote peer can accept [trickled ICE candidates](https://datatracker.ietf.org/doc/html/draft-ietf-mmusic-trickle-ice). - {{DOMxRef("RTCPeerConnection.connectionState", "connectionState")}} {{ReadOnlyInline}} - : Indicates the current state of the peer connection by returning one of the strings: `new`, `connecting`, `connected`, `disconnected`, `failed`, or `closed`. - {{DOMxRef("RTCPeerConnection.currentLocalDescription", "currentLocalDescription")}} {{ReadOnlyInline}} - : Returns an {{DOMxRef("RTCSessionDescription")}} object describing the local end of the connection as it was most recently successfully negotiated since the last time this `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. - {{DOMxRef("RTCPeerConnection.currentRemoteDescription", "currentRemoteDescription")}} {{ReadOnlyInline}} - : Returns an {{DOMxRef("RTCSessionDescription")}} object describing the remote end of the connection as it was most recently successfully negotiated since the last time this `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. - {{DOMxRef("RTCPeerConnection.iceConnectionState", "iceConnectionState")}} {{ReadOnlyInline}} - : Returns a string which state of the ICE agent associated with this RTCPeerConnection. It can be one of the following values: `new`, `checking`, `connected`, `completed`, `failed`, `disconnected`, or `closed`. - {{DOMxRef("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} {{ReadOnlyInline}} - : Returns a string that describes connection's ICE gathering state. This lets you detect, for example, when collection of ICE candidates has finished. Possible values are: `new`, `gathering`, or `complete`. - {{DOMxRef("RTCPeerConnection.localDescription", "localDescription")}} {{ReadOnlyInline}} - : Returns an {{DOMxRef("RTCSessionDescription")}} describing the session for the local end of the connection. If it has not yet been set, returns `null`. - {{DOMxRef("RTCPeerConnection.peerIdentity", "peerIdentity")}} {{ReadOnlyInline}} - : Returns a {{jsxref("Promise")}} that resolves to an {{DOMxRef("RTCIdentityAssertion")}} which contains a string identifying the remote peer. Once this promise resolves successfully, the resulting identity is the target peer identity and will not change for the duration of the connection. - {{DOMxRef("RTCPeerConnection.pendingLocalDescription", "pendingLocalDescription")}} {{ReadOnlyInline}} - : Returns an {{DOMxRef("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. - {{DOMxRef("RTCPeerConnection.pendingRemoteDescription", "pendingRemoteDescription")}} {{ReadOnlyInline}} - : Returns an {{DOMxRef("RTCSessionDescription")}} object describing a pending configuration change for the remote end of the connection. This does not describe the connection as it currently stands, but as it may exist in the near future. - {{DOMxRef("RTCPeerConnection.remoteDescription", "remoteDescription")}} {{ReadOnlyInline}} - : Returns an {{DOMxRef("RTCSessionDescription")}} object describing the session, including configuration and media information, for the remote end of the connection. If this hasn't been set yet, this returns `null`. - {{DOMxRef("RTCPeerConnection.sctp", "sctp")}} {{ReadOnlyInline}} - : Returns an {{DOMxRef("RTCSctpTransport")}} object describing the {{Glossary("SCTP")}} transport layer over which SCTP data is being sent and received. If SCTP hasn't been negotiated, this value is `null`. - {{DOMxRef("RTCPeerConnection.signalingState", "signalingState")}} {{ReadOnlyInline}} - : Returns a string describing the state of the signaling process on the local end of the connection while connecting or reconnecting to another peer. It is one of the following values: `stable`, `have-local-offer`, `have-remote-offer`, `have-local-pranswer`, `have-remote-pranswer`, or `closed`. ## Static methods - {{DOMxRef("RTCPeerConnection.generateCertificate_static", "RTCPeerConnection.generateCertificate()")}} - : Creates an X.509 certificate and its corresponding private key, returning a {{jsxref("Promise")}} that resolves with the new {{DOMxRef("RTCCertificate")}} once it is generated. ## Instance methods _Also inherits methods from {{DOMxRef("EventTarget")}}._ - {{DOMxRef("RTCPeerConnection.addIceCandidate", "addIceCandidate()")}} - : Adds a new remote candidate to the `RTCPeerConnection`'s remote description, which describes the state of the remote end of the connection. - {{DOMxRef("RTCPeerConnection.addTrack", "addTrack()")}} - : Adds a new {{DOMxRef("MediaStreamTrack")}} to the set of tracks which will be transmitted to the other peer. - {{DOMxRef("RTCPeerConnection.addTransceiver", "addTransceiver()")}} - : Creates a new {{DOMxRef("RTCRtpTransceiver")}} and adds it to the set of transceivers associated with the connection. Each transceiver represents a bidirectional stream, with both an {{DOMxRef("RTCRtpSender")}} and an {{DOMxRef("RTCRtpReceiver")}} associated with it. - {{DOMxRef("RTCPeerConnection.close", "close()")}} - : Closes the current peer connection. - {{DOMxRef("RTCPeerConnection.createAnswer", "createAnswer()")}} - : Initiates the creation of an {{Glossary("SDP")}} answer to an offer received from a remote peer during the offer/answer negotiation of a WebRTC connection. The answer contains information about any media already attached to the session, codecs and options supported by the browser, and any {{Glossary("ICE")}} candidates already gathered. - {{DOMxRef("RTCPeerConnection.createDataChannel", "createDataChannel()")}} - : Initiates the creation a new channel linked with the remote peer, over which any kind of data may be transmitted. This can be useful for back-channel content, such as images, file transfer, text chat, game update packets, and so forth. - {{DOMxRef("RTCPeerConnection.createOffer", "createOffer()")}} - : Initiates the creation of an {{Glossary("SDP")}} offer for the purpose of starting a new WebRTC connection to a remote peer. The SDP offer includes information about any {{DOMxRef("MediaStreamTrack")}} objects already attached to the WebRTC session, codec, and options supported by the browser, as well as any candidates already gathered by the {{Glossary("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. - {{DOMxRef("RTCPeerConnection.getConfiguration", "getConfiguration()")}} - : Returns an object which indicates the current configuration of the connection. - {{DOMxRef("RTCPeerConnection.getIdentityAssertion", "getIdentityAssertion()")}} - : Initiates the gathering of an identity assertion and returns a {{jsxref("Promise")}} which resolves to an identity assertion encoded as a string. This has an effect only if {{DOMxRef("RTCPeerConnection.signalingState", "signalingState")}} is not `closed`. - {{DOMxRef("RTCPeerConnection.getReceivers", "getReceivers()")}} - : Returns an array of {{DOMxRef("RTCRtpReceiver")}} objects, each of which represents one {{Glossary("RTP")}} receiver. - {{DOMxRef("RTCPeerConnection.getSenders", "getSenders()")}} - : Returns an array of {{DOMxRef("RTCRtpSender")}} objects, each of which represents the {{Glossary("RTP")}} sender responsible for transmitting one track's data. - {{DOMxRef("RTCPeerConnection.getStats", "getStats()")}} - : Returns a {{jsxref("Promise")}} which resolves with data providing statistics about either the overall connection or about the specified {{DOMxRef("MediaStreamTrack")}}. - {{DOMxRef("RTCPeerConnection.getTransceivers", "getTransceivers()")}} - : Returns a list of all the {{DOMxRef("RTCRtpTransceiver")}} objects being used to send and receive data on the connection. - {{DOMxRef("RTCPeerConnection.removeTrack", "removeTrack()")}} - : Tells the local end of the connection to stop sending media from the specified track, without actually removing the corresponding {{DOMxRef("RTCRtpSender")}} from the list of senders as reported by {{DOMxRef("RTCPeerConnection.getSenders", "getSenders()")}}. If the track is already stopped, or is not in the connection's senders list, this method has no effect. - {{DOMxRef("RTCPeerConnection.restartIce", "restartIce()")}} - : Allows to easily request that ICE candidate gathering be redone on both ends of the connection. This simplifies the process by allowing the same method to be used by either the caller or the receiver to trigger an {{Glossary("ICE")}} restart. - {{DOMxRef("RTCPeerConnection.setConfiguration", "setConfiguration()")}} - : Sets the current configuration of the connection based on the values included in the specified object. This lets you change the {{Glossary("ICE")}} servers used by the connection and which transport policies to use. - {{DOMxRef("RTCPeerConnection.setIdentityProvider", "setIdentityProvider()")}} - : Sets the Identity Provider (IdP) to the triplet given in parameter: its name, the protocol used to communicate with it and an username. The protocol and the username are optional. - {{DOMxRef("RTCPeerConnection.setLocalDescription", "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. It returns a {{jsxref("Promise")}} which is fulfilled once the description has been changed, asynchronously. - {{DOMxRef("RTCPeerConnection.setRemoteDescription", "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. It returns a {{jsxref("Promise")}} which is fulfilled once the description has been changed, asynchronously. ### Obsolete methods - {{DOMxRef("RTCPeerConnection.addStream", "addStream()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Adds a {{DOMxRef("MediaStream")}} as a local source of audio or video. Instead of using this obsolete method, you should instead use {{DOMxRef("RTCPeerConnection.addTrack", "addTrack()")}} once for each track you wish to send to the remote peer. - {{DOMxRef("RTCPeerConnection.createDTMFSender", "createDTMFSender()")}} {{Deprecated_Inline}} - : Creates a new {{DOMxRef("RTCDTMFSender")}}, associated to a specific {{DOMxRef("MediaStreamTrack")}}, that will be able to send {{Glossary("DTMF")}} phone signaling over the connection. - {{DOMxRef("RTCPeerConnection.removeStream", "removeStream()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Removes a {{DOMxRef("MediaStream")}} as a local source of audio or video. Because this method is obsolete, you should instead use {{DOMxRef("RTCPeerConnection.removeTrack", "removeTrack()")}}. ## Events Listen to these events using {{domxref("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface. - {{domxref("RTCPeerConnection.connectionstatechange_event", "connectionstatechange")}} - : Sent when the overall connectivity status of the `RTCPeerConnection` changes. - {{domxref("RTCPeerConnection.datachannel_event", "datachannel")}} - : Sent when the remote peer adds an {{domxref("RTCDataChannel")}} to the connection. - {{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}} - : Sent to request that the specified candidate be transmitted to the remote peer. - {{domxref("RTCPeerConnection.icecandidateerror_event", "icecandidateerror")}} - : Sent to the connection if an error occurred during {{Glossary("ICE")}} candidate gathering. The event describes the error. - {{domxref("RTCPeerConnection.iceconnectionstatechange_event", "iceconnectionstatechange")}} - : Sent when the state of the {{Glossary("ICE")}} connection changes, such as when it disconnects. - {{domxref("RTCPeerConnection.icegatheringstatechange_event", "icegatheringstatechange")}} - : Sent when the {{Glossary("ICE")}} layer's gathering state, reflected by {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}}, changes. This indicates whether ICE negotiation has not yet begun (`new`), has begun gathering candidates (`gathering`), or has completed (`complete`). - {{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}} - : Sent when negotiation or renegotiation of the {{Glossary("ICE")}} connection needs to be performed; this can happen both when first opening a connection as well as when it is necessary to adapt to changing network conditions. The receiver should respond by creating an offer and sending it to the other peer. - {{domxref("RTCPeerConnection.signalingstatechange_event", "signalingstatechange")}} - : Sent when the connection's {{Glossary("ICE")}} signaling state changes. - {{domxref("RTCPeerConnection.track_event", "track")}} - : Sent after a new track has been added to one of the {{domxref("RTCRtpReceiver")}} instances which comprise the connection. ### Obsolete events - {{domxref("RTCPeerConnection.addstream_event", "addstream")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Sent when a new {{domxref("MediaStream")}} has been added to the connection. Instead of listening for this obsolete event, you should listen for {{domxref("RTCPeerConnection.track_event", "track")}} events; one is sent for each {{domxref("MediaStreamTrack")}} added to the connection. - {{domxref("RTCPeerConnection.removestream_event", "removestream")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Sent when a {{domxref("MediaStream")}} is removed from the connection. Instead of listening for this obsolete event, you should listen for {{domxref("MediaStream.removetrack_event", "removetrack")}} events on each stream. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - <https://github.com/jesup/nightly-gupshup/blob/master/static/js/chat.js> - [Get started with WebRTC](https://web.dev/articles/webrtc-basics) - [TutorRoom](https://github.com/chrisjohndigital/TutorRoom): Node.js HTML video capture, peer-to-peer video and filesharing application ([source on GitHub](https://github.com/chrisjohndigital/TutorRoom))
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/signalingstate/index.md
--- title: "RTCPeerConnection: signalingState property" short-title: signalingState slug: Web/API/RTCPeerConnection/signalingState page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.signalingState --- {{APIRef("WebRTC")}} The read-only **`signalingState`** property on the {{domxref("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](/en-US/docs/Web/API/WebRTC_API/Session_lifetime#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 {{domxref("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 {{DOMxRef("RTCPeerConnection/signalingstatechange_event", "signalingstatechange")}} event is sent to the {{domxref("RTCPeerConnection")}} instance. ## Value The allowed string values are: - `stable` - : There is no ongoing exchange of offer and answer underway. This may mean that the {{domxref("RTCPeerConnection")}} object is new, in which case both the {{domxref("RTCPeerConnection.localDescription", "localDescription")}} and {{domxref("RTCPeerConnection.remoteDescription", "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 {{domxref("RTCPeerConnection.setLocalDescription()")}}, passing in SDP representing an offer (usually created by calling {{domxref("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 {{domxref("RTCPeerConnection.setRemoteDescription()")}}. - `have-local-pranswer` - : The offer sent by the remote peer has been applied and an answer has been created (usually by calling {{domxref("RTCPeerConnection.createAnswer()")}}) and applied by calling {{domxref("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 {{domxref("RTCPeerConnection")}} has been closed. ## Examples ```js const pc = new RTCPeerConnection(configuration); const state = pc.signalingState; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime) - {{domxref("RTCPeerConnection")}} - {{DOMxRef("RTCPeerConnection/signalingstatechange_event", "signalingstatechange")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/addicecandidate/index.md
--- title: "RTCPeerConnection: addIceCandidate() method" short-title: addIceCandidate() slug: Web/API/RTCPeerConnection/addIceCandidate page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.addIceCandidate --- {{APIRef("WebRTC")}} When a website or app using {{domxref("RTCPeerConnection")}} receives a new ICE candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser's {{Glossary("ICE")}} agent by calling **`RTCPeerConnection.addIceCandidate()`**. This adds this new remote candidate to the `RTCPeerConnection`'s remote description, which describes the state of the remote end of the connection. If the `candidate` parameter is missing or a value of `null` is given when calling `addIceCandidate()`, the added ICE candidate is an "end-of-candidates" indicator. The same is the case if the value of the specified object's {{domxref("RTCIceCandidate.candidate", "candidate")}} is either missing or an empty string (`""`), it signals that all remote candidates have been delivered. The end-of-candidates notification is transmitted to the remote peer using a candidate with an a-line value of `end-of-candidates`. During negotiation, your app will likely receive many candidates which you'll deliver to the ICE agent in this way, allowing it to build up a list of potential connection methods. This is covered in more detail in the articles [WebRTC connectivity](/en-US/docs/Web/API/WebRTC_API/Connectivity) and [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling). ## Syntax ```js-nolint addIceCandidate(candidate) addIceCandidate(candidate, successCallback) // deprecated addIceCandidate(candidate, successCallback, failureCallback) // deprecated ``` ### Parameters - `candidate` {{optional_inline}} - : An {{domxref("RTCIceCandidate")}} object, or an object that has the following properties: <!-- RTCIceCandidateInit in spec --> - `candidate` {{optional_inline}} - : A string describing the properties of the candidate, taken directly from the [SDP](/en-US/docs/Web/API/WebRTC_API/Protocols#sdp) attribute `"candidate"`. The candidate string specifies the network connectivity information for the candidate. If the `candidate` is an empty string (`""`), the end of the candidate list has been reached; this candidate is known as the "end-of-candidates" marker. The syntax of the candidate string is described in {{RFC(5245, "", 15.1)}}. For an a-line (attribute line) that looks like this: ```plain a=candidate:4234997325 1 udp 2043278322 192.0.2.172 44323 typ host ``` the corresponding `candidate` string's value will be `"candidate:4234997325 1 udp 2043278322 192.0.2.172 44323 typ host"`. The {{Glossary("user agent")}} always prefers candidates with the highest {{domxref("RTCIceCandidate.priority", "priority")}}, all else being equal. In the example above, the priority is `2043278322`. The attributes are all separated by a single space character, and are in a specific order. The complete list of attributes for this example candidate is: - {{domxref("RTCIceCandidate.foundation", "foundation")}} = 4234997325 - {{domxref("RTCIceCandidate.component", "component")}} = `"rtp"` (the number 1 is encoded to this string; 2 becomes `"rtcp"`) - {{domxref("RTCIceCandidate.protocol", "protocol")}} = `"udp"` - {{domxref("RTCIceCandidate.priority", "priority")}} = 2043278322 - {{domxref("RTCIceCandidate/address", "ip")}} = `"192.0.2.172"` - {{domxref("RTCIceCandidate.port", "port")}} = 44323 - {{domxref("RTCIceCandidate.type", "type")}} = `"host"` Additional information can be found in {{domxref("RTCIceCandidate.candidate")}}. > **Note:** For backward compatibility with older versions of the WebRTC specification, the constructor also accepts this string directly as an argument. - `sdpMid` {{optional_inline}} - : A string containing the identification tag of the media stream with which the candidate is associated, or `null` if there is no associated media stream. The default is `null`. Additional information can be found in {{domxref("RTCIceCandidate.sdpMid")}}. - `sdpMLineIndex` {{optional_inline}} - : A number property containing the zero-based index of the m-line with which the candidate is associated, within the [SDP](/en-US/docs/Web/API/WebRTC_API/Protocols#sdp) of the media description, or `null` if no such associated exists. The default is `null`. Additional information can be found in {{domxref("RTCIceCandidate.sdpMLineIndex")}}. - `usernameFragment` {{optional_inline}} - : A string containing the username fragment (usually referred to in shorthand as "ufrag" or "ice-ufrag"). This fragment, along with the ICE password ("ice-pwd"), uniquely identifies a single ongoing ICE interaction (including for any communication with the {{Glossary("STUN")}} server). The string is generated by WebRTC at the beginning of the session. It may be up to 256 characters long, and at least 24 bits must contain random data. It has no default value and is not present unless set explicitly. Additional information can be found in {{domxref("RTCIceCandidate.usernameFragment")}}. The method will throw a {{jsxref("TypeError")}} exception if both `sdpMid` and `sdpMLineIndex` are `null`. The contents of the object should be constructed from a message received over the signaling channel, describing a newly received ICE candidate that's ready to be delivered to the local ICE agent. If no `candidate` object is specified, or its value is `null`, an end-of-candidates signal is sent to the remote peer using the `end-of-candidates` a-line, formatted like this: ```plain a=end-of-candidates ``` ### 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 {{jsxref("Promise")}}-based version of `addIceCandidate()` instead. The parameters for the older form of `addIceCandidate()` are described below, to aid in updating existing code. - `successCallback` {{deprecated_inline}} - : A function to be called when the ICE candidate has been successfully added. This function receives no input parameters and doesn't return a value. - `failureCallback` {{deprecated_inline}} - : A function to be called if attempting to add the ICE candidate fails. Receives as input a {{domxref("DOMException")}} object describing why failure occurred. ### Return value A {{jsxref("Promise")}} that is fulfilled when the candidate has been successfully added to the remote peer's description by the ICE agent. The promise does not receive any input parameters. ### Exceptions When an error occurs while attempting to add the ICE candidate, the {{jsxref("Promise")}} returned by this method is rejected, returning one of the errors below as the {{domxref("DOMException.name", "name")}} attribute in the specified {{domxref("DOMException")}} object passed to the rejection handler. - {{jsxref("TypeError")}} - : Returned if the specified candidate's {{domxref("RTCIceCandidate.sdpMid", "sdpMid")}} and {{domxref("RTCIceCandidate.sdpMLineIndex", "sdpMLineIndex")}} are both `null`. - `InvalidStateError` {{domxref("DOMException")}} - : Returned if the `RTCPeerConnection` currently has no remote peer established ({{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}} is `null`). - `OperationError` {{domxref("DOMException")}} - : Returned in one of the following situations: - The value specified for {{domxref("RTCIceCandidate.sdpMid", "sdpMid")}} is non-`null` and doesn't match the media description ID of any media description included within the {{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}}. - The specified value of {{domxref("RTCIceCandidate.sdpMLineIndex", "sdpMLineIndex")}} is greater than or equal to the number of media descriptions included in the remote description. - The specified {{domxref("RTCIceCandidate.usernameFragment", "ufrag")}} doesn't match the `ufrag` field in any of the remote descriptions being considered. - One or more of the values in the {{domxref("RTCIceCandidate", "candidate")}} string are invalid or could not be parsed. - Attempting to add the candidate fails for any reason. ## Examples This code snippet shows how to signal ICE candidates across an arbitrary signaling channel. ```js // This example assumes that the other peer is using a signaling channel as follows: // // pc.onicecandidate = (event) => { // if (event.candidate) { // signalingChannel.send(JSON.stringify({ice: event.candidate})); // "ice" is arbitrary // } else { // // All ICE candidates have been sent // } // } signalingChannel.onmessage = (receivedString) => { const message = JSON.parse(receivedString); if (message.ice) { // A typical value of ice here might look something like this: // // {candidate: "candidate:0 1 UDP 2122154243 192.0.2.43 53421 typ host", sdpMid: "0", …} // // Pass the whole thing to addIceCandidate: pc.addIceCandidate(message.ice).catch((e) => { console.log(`Failure during addIceCandidate(): ${e.name}`); }); } else { // handle other things you might be signaling, like sdp } }; ``` The last candidate to be signaled this way by the remote peer will be a special candidate denoting end-of-candidates. Out of interest, end-of-candidates may be manually indicated as follows: ```js pc.addIceCandidate({ candidate: "" }); ``` However, in most cases you won't need to look for this explicitly, since the events driving the {{domxref("RTCPeerConnection")}} will deal with it for you, sending the appropriate events. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling) - [Introduction to WebRTC protocols](/en-US/docs/Web/API/WebRTC_API/Protocols) - [WebRTC connectivity](/en-US/docs/Web/API/WebRTC_API/Connectivity) - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/pendingremotedescription/index.md
--- title: "RTCPeerConnection: pendingRemoteDescription property" short-title: pendingRemoteDescription slug: Web/API/RTCPeerConnection/pendingRemoteDescription page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.pendingRemoteDescription --- {{APIRef("WebRTC")}} The read-only property **`RTCPeerConnection.pendingRemoteDescription`** returns an {{domxref("RTCSessionDescription")}} object describing a pending configuration change for the remote end of the connection. This does not describe the connection as it currently stands, but as it may exist in the near future. Use {{domxref("RTCPeerConnection.currentRemoteDescription")}} or {{domxref("RTCPeerConnection.remoteDescription")}} to get the current session description for the remote endpoint. For details on the difference, see [Pending and current descriptions](/en-US/docs/Web/API/WebRTC_API/Connectivity#pending_and_current_descriptions) in the WebRTC Connectivity page. ## Value If a remote description change is in progress, this is an {{domxref("RTCSessionDescription")}} describing the proposed configuration. Otherwise, this returns `null`. ## Examples This example looks at the `pendingRemoteDescription` to determine whether or not there's a description change being processed. ```js const pc = new RTCPeerConnection(); // ... const sd = pc.pendingRemoteDescription; if (sd) { // There's a description change underway! } else { // No description change pending } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} > **Note:** The addition of `pendingRemoteDescription` and > {{domxref("RTCPeerConnection.currentRemoteDescription", "currentRemoteDescription")}} > to the WebRTC spec is relatively recent. In browsers which don't support them, only > {{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}} is available. ## See also - {{domxref("RTCPeerConnection.setRemoteDescription()")}}, {{domxref("RTCPeerConnection.currentRemoteDescription")}}, {{domxref("RTCPeerConnection.remoteDescription")}} - {{domxref("RTCPeerConnection.setLocalDescription()")}}, {{domxref("RTCPeerConnection.localDescription")}}, {{domxref("RTCPeerConnection.pendingLocalDescription")}}, {{domxref("RTCPeerConnection.currentLocalDescription")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/icegatheringstatechange_event/index.md
--- title: "RTCPeerConnection: icegatheringstatechange event" short-title: icegatheringstatechange slug: Web/API/RTCPeerConnection/icegatheringstatechange_event page-type: web-api-event browser-compat: api.RTCPeerConnection.icegatheringstatechange_event --- {{APIRef("WebRTC")}} The **`icegatheringstatechange`** event is sent to the `onicegatheringstatechange` event handler on an {{domxref("RTCPeerConnection")}} when the state of the {{Glossary("ICE")}} candidate gathering process changes. This signifies that the value of the connection's {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} property has changed. When ICE first starts to gather connection candidates, the value changes from `new` to `gathering` to indicate that the process of collecting candidate configurations for the connection has begun. When the value changes to `complete`, all of the transports that make up the `RTCPeerConnection` have finished gathering ICE candidates. > **Note:** While you can determine that ICE candidate gathering is complete by watching for `icegatheringstatechange` events and checking for the value of {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} to become `complete`, you can also have your handler for the {{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}} event look to see if its {{domxref("RTCPeerConnectionIceEvent.candidate", "candidate")}} property is `null`. This also indicates that collection of candidates is finished. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("icegatheringstatechange", (event) => {}); onicegatheringstatechange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples This example creates a handler for `icegatheringstatechange` events. ```js pc.onicegatheringstatechange = (ev) => { let connection = ev.target; switch (connection.iceGatheringState) { case "gathering": /* collection of candidates has begun */ break; case "complete": /* collection of candidates is finished */ break; } }; ``` Likewise, you can use {{domxref("EventTarget.addEventListener", "addEventListener()")}} to add a listener for `icegatheringstatechange` events: ```js pc.addEventListener( "icegatheringstatechange", (ev) => { let connection = ev.target; switch (connection.iceGatheringState) { case "gathering": // collection of candidates has begun break; case "complete": // collection of candidates is finished break; } }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling) - [WebRTC connectivity](/en-US/docs/Web/API/WebRTC_API/Connectivity) - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/addstream_event/index.md
--- title: "RTCPeerConnection: addstream event" short-title: addstream slug: Web/API/RTCPeerConnection/addstream_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.RTCPeerConnection.addstream_event --- {{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}} The obsolete **`addstream`** event is sent to an {{domxref("RTCPeerConnection")}} when new media, in the form of a {{domxref("MediaStream")}} object, has been added to it. > **Warning:** This event has been removed from the WebRTC specification. You should instead watch for the {{domxref("RTCPeerConnection.track_event", "track")}} event, which is sent for each media track added to the `RTCPeerConnection`. You can, similarly, watch for streams to be removed from the connection by monitoring the {{domxref("RTCPeerConnection.removestream_event", "removestream")}} event. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("addstream", (event) => {}); onaddstream = (event) => {}; ``` ## Event type A {{domxref("MediaStreamEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MediaStreamEvent")}} ## Event properties _A {{domxref("MediaStreamEvent")}} being an {{domxref("Event")}}, this event also implements these properties_. - {{domxref("MediaStreamEvent.stream")}} {{ReadOnlyInline}} - : Contains the {{domxref("MediaStream")}} containing the stream associated with the event. ## Examples This example looks to determine if the user's browser supports the {{domxref("RTCPeerConnection.track_event", "track")}} event. If it does, a `track` event listener is set up; otherwise, an `addstream` event listener is set up. `pc` is an `RTCPeerConnection`. ```js if (pc.addTrack !== undefined) { pc.ontrack = (ev) => { ev.streams.forEach((stream) => doAddStream(stream)); }; } else { pc.onaddstream = (ev) => { doAddStream(ev.stream); }; } ``` This calls a function `doAddStream()` once for each stream being added to the {{domxref("RTCPeerConnection")}}, regardless of whether the browser sends `addstream` or `track`. You can also use the {{domxref("EventTarget.addEventListener", "addEventListener()")}} method to set an event listener: ```js pc.addEventListener("addstream", (ev) => doAddStream(ev.stream), false); ``` ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection.addStream()")}} - {{domxref("MediaStreamEvent")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/sctp/index.md
--- title: "RTCPeerConnection: sctp property" short-title: sctp slug: Web/API/RTCPeerConnection/sctp page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.sctp --- {{APIRef("WebRTC")}} The read-only **`sctp`** property on the {{domxref("RTCPeerConnection")}} interface returns an {{domxref("RTCSctpTransport")}} describing the {{Glossary("SCTP")}} transport over which SCTP data is being sent and received. If SCTP hasn't been negotiated, this value is `null`. The SCTP transport is used for transmitting and receiving data for any and all {{domxref("RTCDataChannel")}}s on the peer connection. ## Value A {{domxref("RTCSctpTransport")}} object describing the SCTP transport being used by the {{domxref("RTCPeerConnection")}} for transmitting and receiving on its data channels, or `null` if SCTP negotiation hasn't happened. ## Example ```js const peerConnection = new RTCPeerConnection(); const channel = peerConnection.createDataChannel("Mydata"); channel.onopen = (event) => { channel.send("sending a message"); }; channel.onmessage = (event) => { console.log(event.data); }; // Determine the largest message size that can be sent const sctp = peerConnection.sctp; const maxMessageSize = sctp.maxMessageSize; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection")}} - {{domxref("RTCDataChannel")}} - {{Glossary("SCTP")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/iceconnectionstatechange_event/index.md
--- title: "RTCPeerConnection: iceconnectionstatechange event" short-title: iceconnectionstatechange slug: Web/API/RTCPeerConnection/iceconnectionstatechange_event page-type: web-api-event browser-compat: api.RTCPeerConnection.iceconnectionstatechange_event --- {{APIRef("WebRTC")}} An **`iceconnectionstatechange`** event is sent to an {{domxref("RTCPeerConnection")}} object each time the {{Glossary("ICE")}} connection state changes during the negotiation process. The new ICE connection state is available in the object's {{domxref("RTCPeerConnection.iceConnectionState", "iceConnectionState")}} property. One common task performed by the `iceconnectionstatechange` event listener is to trigger [ICE restart](/en-US/docs/Web/API/WebRTC_API/Session_lifetime#ice_restart) when the state changes to `failed`. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("iceconnectionstatechange", (event) => {}); oniceconnectionstatechange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Usage notes A successful connection attempt will typically involve the state starting at `new`, then transitioning through `checking`, then `connected`, and finally `completed`. However, under certain circumstances, the `connected` state can be skipped, causing a connection to transition directly from the `checking` state to `completed`. This can happen when only the last checked candidate is successful, and the gathering and end-of-candidates signals both occur before the successful negotiation is completed. ### ICE connection state during ICE restarts When an ICE restart is processed, the gathering and connectivity checking process is started over from the beginning, which will cause the `iceConnectionState` to transition to `connected` if the ICE restart was triggered while in the `completed` state. If ICE restart is initiated while in the transient `disconnected` state, the state transitions instead to `checking`, essentially indicating that the negotiation is ignoring the fact that the connection had been temporarily lost. ### State transitions as negotiation ends When the negotiation process runs out of candidates to check, the ICE connection transitions to one of two states. If no suitable candidates were found, the state transitions to `failed`. If at least one suitable candidate was successfully identified, the state transitions to `completed`. The ICE layer makes this determination upon receiving the end-of-candidates signal, which is provided by calling {{domxref("RTCPeerConnection.addIceCandidate", "addIceCandidate()")}} with a candidate whose {{domxref("RTCIceCandidate.candidate", "candidate")}} property is an empty string (""), or by setting the {{domxref("RTCPeerConnection")}} property {{domxref("RTCPeerConnection.canTrickleIceCandidates", "canTrickleIceCandidates")}} to `false`. ## Examples An event handler for this event can be added using the `oniceconnectionstatechange` property or by using {{domxref("EventTarget.addEventListener", "addEventListener()")}} on the `RTCPeerConnection`. In this example, a handler for `iceconnectionstatechange` is set up to update a call state indicator by using the value of {{domxref("RTCPeerConnection.iceConnectionState", "iceConnectionState")}} to create a string which corresponds to the name of a CSS class that we can assign to the status indicator to cause it to reflect the current state of the connection. ```js pc.addEventListener( "iceconnectionstatechange", (ev) => { let stateElem = document.querySelector("#call-state"); stateElem.className = `${pc.iceConnectionState}-state`; }, false, ); ``` This can also be written as: ```js pc.oniceconnectionstatechange = (ev) => { let stateElem = document.querySelector("#call-state"); stateElem.className = `${pc.iceConnectionState}-state`; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection")}} - {{domxref("RTCPeerConnection.iceConnectionState")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/setlocaldescription/index.md
--- title: "RTCPeerConnection: setLocalDescription() method" short-title: setLocalDescription() slug: Web/API/RTCPeerConnection/setLocalDescription page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.setLocalDescription --- {{APIRef("WebRTC")}} The {{domxref("RTCPeerConnection")}} method {{domxref("RTCPeerConnection.setLocalDescription", "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 {{jsxref("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-nolint setLocalDescription() setLocalDescription(sessionDescription) setLocalDescription(sessionDescription, successCallback, errorCallback) // deprecated ``` ### Parameters - `sessionDescription` {{optional_inline}} - : An {{domxref("RTCSessionDescriptionInit")}} or {{domxref("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 {{jsxref("Promise")}} which is fulfilled once the value of {{domxref("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](/en-US/docs/Web/API/WebRTC_API/Connectivity#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 {{domxref("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 {{domxref("RTCSessionDescription.RTCSessionDescription", "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 {{jsxref("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_inline}} - : A JavaScript {{jsxref("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_inline}} - : A function matching the signature `RTCPeerConnectionErrorCallback` which gets called if the description can't be set. It is passed a single {{domxref("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` {{domxref("DOMException")}} {{deprecated_inline}} - : Thrown if the connection's {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is `"closed"`, indicating that the connection is not currently open, so negotiation cannot take place. - `InvalidSessionDescriptionError` {{domxref("DOMException")}} {{deprecated_inline}} - : Thrown if the {{domxref("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 {{domxref("RTCPeerConnection.negotiationneeded_event", "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 {{DOMxRef("RTCPeerConnection/negotiationneeded_event", "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 {{domxref("RTCPeerConnection.createOffer()", "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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/icecandidate_event/index.md
--- title: "RTCPeerConnection: icecandidate event" short-title: icecandidate slug: Web/API/RTCPeerConnection/icecandidate_event page-type: web-api-event browser-compat: api.RTCPeerConnection.icecandidate_event --- {{APIRef("WebRTC")}} An **`icecandidate`** event is sent to an {{domxref("RTCPeerConnection")}} when: - An {{domxref("RTCIceCandidate")}} has been identified and added to the local peer by a call to {{domxref("RTCPeerConnection.setLocalDescription()")}}, - Every {{domxref("RTCIceCandidate")}} correlated with a particular username fragment and password combination (a **generation**) has been so identified and added, and - All ICE gathering on all transports is complete. In the first two cases, the event handler should transmit the candidate to the remote peer over the signaling channel so the remote peer can add it to its set of remote candidates. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("icecandidate", (event) => {}); onicecandidate = (event) => {}; ``` ## Event type An {{domxref("RTCPeerConnectionIceEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("RTCPeerConnectionIceEvent")}} ## Event properties _A {{domxref("RTCPeerConnectionIceEvent")}} being an {{domxref("Event")}}, this event also implements the following property_. - {{domxref("RTCPeerConnectionIceEvent.candidate")}} {{ReadOnlyInline}} - : Indicates the {{domxref("RTCIceCandidate")}} containing the candidate associated with the event. This will be the empty string if the event indicates that there are no further candidates to come in this **generation**, or `null` if all ICE gathering on all transports is complete. ## Description There are three reasons why the `icecandidate` event is fired on an {{domxref("RTCPeerConnection")}}. ### Sharing a new candidate The majority of `icecandidate` events are fired to indicate that a new candidate has been gathered. This candidate needs to be delivered to the remote peer over the signaling channel your code manages. ```js rtcPeerConnection.onicecandidate = (event) => { if (event.candidate !== null) { sendCandidateToRemotePeer(event.candidate); } else { /* there are no more candidates coming during this negotiation */ } }; ``` The remote peer, upon receiving the candidate, will add the candidate to its candidate pool by calling {{domxref("RTCPeerConnection.addIceCandidate", "addIceCandidate()")}}, passing in the {{domxref("RTCPeerConnectionIceEvent.candidate", "candidate")}} string you have passed along using the signaling server. ### Indicating the end of a generation of candidates When an ICE negotiation session runs out of candidates to propose for a given {{domxref("RTCIceTransport")}}, it has completed gathering for a **generation** of candidates. That this has occurred is indicated by an `icecandidate` event whose {{domxref("RTCPeerConnectionIceEvent.candidate", "candidate")}} string is empty (`""`). You should deliver this to the remote peer just like any standard candidate, as described under [Sharing a new candidate](#sharing_a_new_candidate) above. This ensures that the remote peer is given the end-of-candidates notification as well. As you see in the code in the previous section, every candidate is sent to the other peer, including any that might have an empty candidate string. Only candidates for which the event's {{domxref("RTCPeerConnectionIceEvent.candidate", "candidate")}} property is `null` are not forwarded across the signaling connection. The end-of-candidates indication is described in [section 9.3 of the Trickle ICE draft specification](https://datatracker.ietf.org/doc/html/draft-ietf-mmusic-trickle-ice-02#section-9.3) (note that the section number is subject to change as the specification goes through repeated drafts). ### Indicating that ICE gathering is complete Once all ICE transports have finished gathering candidates and the value of the {{domxref("RTCPeerConnection")}} object's {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} has made the transition to `complete`, an `icecandidate` event is sent with the value of `candidate` set to `null`. This signal exists for backward compatibility purposes and does _not_ need to be delivered onward to the remote peer (which is why the code snippet above checks to see if `event.candidate` is `null` prior to sending the candidate along). If you need to perform any special actions when there are no further candidates expected, you're much better off watching the ICE gathering state by watching for {{domxref("RTCPeerConnection.icegatheringstatechange_event", "icegatheringstatechange")}} events: ```js pc.addEventListener("icegatheringstatechange", (ev) => { switch (pc.iceGatheringState) { case "new": /* gathering is either just starting or has been reset */ break; case "gathering": /* gathering has begun or is ongoing */ break; case "complete": /* gathering has ended */ break; } }); ``` As you can see in this example, the `icegatheringstatechange` event lets you know when the value of the {{domxref("RTCPeerConnection")}} property {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} has been updated. If that value is now `complete`, you know that ICE gathering has just ended. This is a more reliable approach than looking at the individual ICE messages for one indicating that the ICE session is finished. ## Examples This example creates a simple handler for the `icecandidate` event that uses a function called `sendMessage()` to create and send a reply to the remote peer through the signaling server. First, an example using {{domxref("EventTarget.addEventListener", "addEventListener()")}}: ```js pc.addEventListener( "icecandidate", (ev) => { if (ev.candidate !== null) { sendMessage({ type: "new-ice-candidate", candidate: ev.candidate, }); } }, false, ); ``` You can also set the `onicecandidate` event handler property directly: ```js pc.onicecandidate = (ev) => { if (ev.candidate !== null) { sendMessage({ type: "new-ice-candidate", candidate: ev.candidate, }); } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/icecandidateerror_event/index.md
--- title: "RTCPeerConnection: icecandidateerror event" short-title: icecandidateerror slug: Web/API/RTCPeerConnection/icecandidateerror_event page-type: web-api-event browser-compat: api.RTCPeerConnection.icecandidateerror_event --- {{APIRef("WebRTC")}} The [WebRTC API](/en-US/docs/Web/API/WebRTC_API) event **`icecandidateerror`** is sent to an {{domxref("RTCPeerConnection")}} if an error occurs while performing ICE negotiations through a {{Glossary("STUN")}} or {{Glossary("TURN")}} server. The event object is of type {{domxref("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 {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("icecandidateerror", (event) => {}); onicecandidateerror = (event) => {}; ``` ## Event type An {{domxref("RTCPeerConnectionIceErrorEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("RTCPeerConnectionIceErrorEvent")}} ## Event properties _The `RTCPeerConnectionIceErrorEvent` interface includes the properties found on the {{domxref("Event")}} interface, as well as the following properties:_ - {{domxref("RTCPeerConnectionIceErrorEvent.address", "address")}} {{ReadOnlyInline}} - : A string providing the local IP address used to communicate with the {{Glossary("STUN")}} or {{Glossary("TURN")}} server being used to negotiate the connection, or `null` if the local IP address has not yet been exposed as part of a local ICE candidate. - {{domxref("RTCPeerConnectionIceErrorEvent.errorCode", "errorCode")}} {{ReadOnlyInline}} - : An unsigned integer value stating the numeric [STUN error code](https://www.iana.org/assignments/stun-parameters/stun-parameters.xhtml#stun-parameters-6) returned by the STUN or TURN server. If no host candidate can reach the server, this property is set to the number 701, which is outside the range of valid STUN error codes. The 701 error is fired only once per server URL, and only while the {{domxref("RTCPeerConnection.icegatheringstate", "icegatheringstate")}} is `gathering`. - {{domxref("RTCPeerConnectionIceErrorEvent.errorText", "errorText")}} {{ReadOnlyInline}} - : A string containing the STUN reason text returned by the STUN or TURN server. If communication with the STUN or TURN server couldn't be established at all, this string will be a browser-specific string explaining the error. - {{domxref("RTCPeerConnectionIceErrorEvent.port", "port")}} {{ReadOnlyInline}} - : An unsigned integer value giving the port number over which communication with the STUN or TURN server is taking place, using the IP address given in `address`. `null` if the connection hasn't been established (that is, if `address` is `null`). - {{domxref("RTCPeerConnectionIceErrorEvent.url", "url")}} {{ReadOnlyInline}} - : A string indicating the URL of the STUN or TURN server with which the error occurred. ## Description The error object's {{domxref("RTCPeerConnectionIceErrorEvent.errorCode", "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 {{domxref("RTCPeerConnection")}}. These errors occur only when the connection's [ICE gathering state](/en-US/docs/Web/API/RTCPeerConnection/iceGatheringState) is `gathering`. ## Example The following example establishes a handler for `icecandidateerror`s that occur on the {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/getsenders/index.md
--- title: "RTCPeerConnection: getSenders() method" short-title: getSenders() slug: Web/API/RTCPeerConnection/getSenders page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.getSenders --- {{APIRef("WebRTC")}} The {{domxref("RTCPeerConnection")}} method **`getSenders()`** returns an array of {{domxref("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-nolint getSenders() ``` ### Return value An array of {{domxref("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](/en-US/docs/Web/API/RTCRtpTransceiver/currentDirection) (following offer/answer). ## Example In this example, a `setMuting()` function is shown. This function takes as input an {{domxref("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 {{domxref("MediaStreamTrack.enabled", "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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCRtpSender")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/getstats/index.md
--- title: "RTCPeerConnection: getStats() method" short-title: getStats() slug: Web/API/RTCPeerConnection/getStats page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.getStats --- {{APIRef("WebRTC")}} The {{domxref("RTCPeerConnection")}} method **`getStats()`** returns a promise which resolves with data providing statistics about either the overall connection or about the specified {{domxref("MediaStreamTrack")}}. ## Syntax ```js-nolint getStats() getStats(selector) getStats(selector, successCallback, failureCallback) // deprecated ``` ### Parameters - `selector` {{optional_inline}} - : A {{domxref("MediaStreamTrack")}} for which to gather statistics. If this is `null` (the default value), statistics will be gathered for the entire {{domxref("RTCPeerConnection")}}. ### 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 {{jsxref("Promise")}}-based version of `getStats()` instead. The parameters for the older form of `getStats()` are described below, to aid in updating existing code. - `successCallback` {{deprecated_inline}} - : A [callback function](/en-US/docs/Glossary/Callback_function) called once the report has been successfully generated. - `failureCallback` {{deprecated_inline}} - : A [callback function](/en-US/docs/Glossary/Callback_function) called once the report has failed to be generated. ### Return value A {{jsxref("Promise")}} which resolves with an {{domxref("RTCStatsReport")}} object providing connection statistics. The report's contents depend on the `selector` and other details of the connection. ### Exceptions This method does not throw exceptions; instead, it rejects the returned promise with one of the following errors: - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown when there is no {{domxref("RTCRtpSender")}} or {{domxref("RTCRtpReceiver")}} whose `track` matches the specified `selector`, or `selector` matches more than one sender or receiver. ## Examples This example creates a periodic function using {{domxref("setInterval()")}} that collects statistics for an {{domxref("RTCPeerConnection")}} every second, generating an HTML-formatted report and inserting it into a specific element in the DOM. ```js setInterval(() => { myPeerConnection.getStats(null).then((stats) => { let statsOutput = ""; stats.forEach((report) => { statsOutput += `<h2>Report: ${report.type}</h2>\n<strong>ID:</strong> ${report.id}<br>\n` + `<strong>Timestamp:</strong> ${report.timestamp}<br>\n`; // Now the statistics for this report; we intentionally drop the ones we // sorted to the top above Object.keys(report).forEach((statName) => { if ( statName !== "id" && statName !== "timestamp" && statName !== "type" ) { statsOutput += `<strong>${statName}:</strong> ${report[statName]}<br>\n`; } }); }); document.querySelector(".stats-box").innerHTML = statsOutput; }); }, 1000); ``` This works by calling `getStats()`, then, when the promise is resolved, iterates over the {{domxref("RTCStatsReport")}} objects on the returned {{domxref("RTCStatsReport")}}. A section is created for each report with a header and all of the statistics below, with the type, ID, and timestamp handled specially to place them at the top of the list. Once the [HTML](/en-US/docs/Web/HTML) for the report is generated, it is injected into the element whose class is `"stats-box"` by setting its {{domxref("Element.innerHTML", "innerHTML")}} property. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/currentlocaldescription/index.md
--- title: "RTCPeerConnection: currentLocalDescription property" short-title: currentLocalDescription slug: Web/API/RTCPeerConnection/currentLocalDescription page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.currentLocalDescription --- {{APIRef("WebRTC")}} The read-only property **`RTCPeerConnection.currentLocalDescription`** returns an {{domxref("RTCSessionDescription")}} object describing the local end of the connection as it was most recently successfully negotiated since the last time the {{domxref("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 {{domxref("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](/en-US/docs/Web/API/WebRTC_API/Connectivity#pending_and_current_descriptions) in the WebRTC Connectivity page. > **Note:** Unlike {{domxref("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 {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}} > **Note:** The addition of `currentLocalDescription` and > {{domxref("RTCPeerConnection.pendingLocalDescription", "pendingLocalDescription")}} to > the WebRTC spec is relatively recent. In browsers which don't support them, just use > {{domxref("RTCPeerConnection.localDescription", "localDescription")}}. ## See also - {{domxref("RTCPeerConnection.setLocalDescription()")}}, {{domxref("RTCPeerConnection.pendingLocalDescription")}}, {{domxref("RTCPeerConnection.localDescription")}} - {{domxref("RTCPeerConnection.setRemoteDescription()")}}, {{domxref("RTCPeerConnection.remoteDescription")}}, {{domxref("RTCPeerConnection.pendingRemoteDescription")}}, {{domxref("RTCPeerConnection.currentRemoteDescription")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/peeridentity/index.md
--- title: "RTCPeerConnection: peerIdentity property" short-title: peerIdentity slug: Web/API/RTCPeerConnection/peerIdentity page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.peerIdentity --- {{APIRef("WebRTC")}} The read-only {{domxref("RTCPeerConnection")}} property **`peerIdentity`** returns a JavaScript {{jsxref("Promise")}} that resolves to an {{domxref("RTCIdentityAssertion")}} which contains a string identifying the remote peer. Once this promise resolves successfully, the resulting identity is the **target peer identity** and cannot change for the duration of the connection. ## Value A JavaScript {{jsxref("Promise")}} which resolves to an {{domxref("RTCIdentityAssertion")}} that describes the remote peer's identity. If an error occurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. If there isn't already a target peer identity, `peerIdentity` is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur. > **Note:** The promise returned by > {{domxref("RTCPeerConnection.setRemoteDescription", "setRemoteDescription()")}} cannot > resolve until any target peer identity that's been set is validated. If the identity > hasn't been validated yet, the promise returned by `setRemoteDescription()` > will be rejected. If there's no target peer identity, > `setRemoteDescription()` doesn't need to wait for validation to occur > before it resolves. ## Examples In this example, a function, `getIdentityAssertion()`, is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller. If an error occurs and the promise is rejected, this logs the error to the console and returns `null` to the caller. ```js let pc = new RTCPeerConnection(); // … async function getIdentityAssertion(pc) { try { const identity = await pc.peerIdentity; return identity; } catch (err) { console.log("Error identifying remote peer: ", err); return null; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/pendinglocaldescription/index.md
--- title: "RTCPeerConnection: pendingLocalDescription property" short-title: pendingLocalDescription slug: Web/API/RTCPeerConnection/pendingLocalDescription page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.pendingLocalDescription --- {{APIRef("WebRTC")}} The read-only property **`RTCPeerConnection.pendingLocalDescription`** returns an {{domxref("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 {{domxref("RTCPeerConnection.currentLocalDescription")}} or {{domxref("RTCPeerConnection.localDescription")}} to get the current state of the endpoint. For details on the difference, see [Pending and current descriptions](/en-US/docs/Web/API/WebRTC_API/Connectivity#pending_and_current_descriptions) in the WebRTC Connectivity page. ## Value If a local description change is in progress, this is an {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}} > **Note:** The addition of `pendingLocalDescription` and > {{domxref("RTCPeerConnection.currentLocalDescription", "currentLocalDescription")}} to > the WebRTC spec is relatively recent. In browsers which don't support them, only > {{domxref("RTCPeerConnection.localDescription", "localDescription")}} is available. ## See also - {{domxref("RTCPeerConnection.setLocalDescription()")}}, {{domxref("RTCPeerConnection.currentLocalDescription")}}, {{domxref("RTCPeerConnection.localDescription")}} - {{domxref("RTCPeerConnection.setRemoteDescription()")}}, {{domxref("RTCPeerConnection.remoteDescription")}}, {{domxref("RTCPeerConnection.pendingRemoteDescription")}}, {{domxref("RTCPeerConnection.currentRemoteDescription")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/restartice/index.md
--- title: "RTCPeerConnection: restartIce() method" short-title: restartIce() slug: Web/API/RTCPeerConnection/restartIce page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.restartIce --- {{APIRef("WebRTC")}} The [WebRTC](/en-US/docs/Web/API/WebRTC_API) API's {{domxref("RTCPeerConnection")}} interface offers the **`restartIce()`** method to allow a web application to easily request that {{Glossary("ICE")}} candidate gathering be redone on both ends of the connection. This simplifies the process by allowing the same method to be used by either the caller or the receiver to trigger an ICE restart. After `restartIce()` returns, the offer returned by the next call to {{domxref("RTCPeerConnection.createOffer", "createOffer()")}} is automatically configured to trigger ICE restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well. `restartIce()` causes the {{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}} event to be fired on the `RTCPeerConnection` to inform the application that it should perform negotiation using its signaling channel. If negotiation fails to completeβ€”either due to rollback or because incoming offers are in the process of being negotiatedβ€”the {{domxref("RTCPeerConnection")}} will remember that you requested ICE restart. The next time the connection's {{domxref("RTCPeerConnection.signalingState", "signalingState")}} changes to `stable`, the connection will fire the {{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}} event. This process continues until an ICE restart has been successfully completed. ## Syntax ```js-nolint restartIce() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Usage notes After calling `restartIce()`, the next offer created using {{domxref("RTCPeerConnection.createOffer", "createOffer()")}} will initiate ICE restart once sent to the remote peer over your signaling mechanism. Restarting ICE essentially resets ICE so that it creates all new candidates using new credentials. Existing media transmissions continue uninterrupted during this process. For details about how ICE restart works, see [ICE restart](/en-US/docs/Web/API/WebRTC_API/Session_lifetime#ice_restart) and {{RFC(5245, "ICE specification", "9.1.1.1")}}. ## Examples This example creates a handler for the {{domxref("RTCPeerConnection.iceconnectionstatechange_event", "iceconnectionstatechange")}} event that handles a transition to the `failed` state by restarting ICE in order to try again. ```js pc.addEventListener("iceconnectionstatechange", (event) => { if (pc.iceConnectionState === "failed") { /* possibly reconfigure the connection in some way here */ /* then request ICE restart */ pc.restartIce(); } }); ``` With this code in place, a transition to the `failed` state during ICE negotiation will cause a {{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}} event to be fired, in response to which your code should renegotiate as usual. However, because you have called `restartIce()`, your call to {{domxref("RTCPeerConnection.createOffer", "createOffer()")}} which occurs in the handler for `negotiationneeded` will trigger an ICE restart rather than just a regular renegotiation. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime) - [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/currentremotedescription/index.md
--- title: "RTCPeerConnection: currentRemoteDescription property" short-title: currentRemoteDescription slug: Web/API/RTCPeerConnection/currentRemoteDescription page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.currentRemoteDescription --- {{APIRef("WebRTC")}} The read-only property **`RTCPeerConnection.currentRemoteDescription`** returns an {{domxref("RTCSessionDescription")}} object describing the remote end of the connection as it was most recently successfully negotiated since the last time the {{domxref("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 `currentRemoteDescription`, call {{domxref("RTCPeerConnection.setRemoteDescription()")}}, 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](/en-US/docs/Web/API/WebRTC_API/Connectivity#pending_and_current_descriptions) in the WebRTC Connectivity page. > **Note:** Unlike {{domxref("RTCPeerConnection.remoteDescription")}}, this value represents the > actual current state of the local end of the connection; > `remoteDescription` may specify a description which the connection is > currently in the process of switching over to. ## Value The current description of the remote 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 `currentRemoteDescription` and displays an alert containing the {{domxref("RTCSessionDescription")}} object's `type` and `sdp` fields. ```js const pc = new RTCPeerConnection(); // ... const sd = pc.currentRemoteDescription; if (sd) { alert(`Local session: type='${sd.type}'; sdp description='${sd.sdp}'`); } else { alert("No local session yet."); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("RTCPeerConnection.setRemoteDescription()")}}, {{domxref("RTCPeerConnection.pendingRemoteDescription")}}, {{domxref("RTCPeerConnection.remoteDescription")}} - {{domxref("RTCPeerConnection.setRemoteDescription()")}}, {{domxref("RTCPeerConnection.remoteDescription")}}, {{domxref("RTCPeerConnection.pendingRemoteDescription")}}, {{domxref("RTCPeerConnection.currentRemoteDescription")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/removestream_event/index.md
--- title: "RTCPeerConnection: removestream event" short-title: removestream slug: Web/API/RTCPeerConnection/removestream_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.RTCPeerConnection.removestream_event --- {{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}} The obsolete **`removestream`** event was sent to an {{domxref("RTCPeerConnection")}} to inform it that a {{domxref("MediaStream")}} had been removed from the connection. You can use the `RTCPeerConnection` interface's `onremovestream` property to set a handler for this event. This is the counterpart to the {{domxref("RTCPeerConnection.addstream_event", "addstream")}} event, which is also obsolete. > **Warning:** This event has been removed from the WebRTC specification in favor of the existing {{DOMxRef("MediaStream/removetrack_event", "removetrack")}} event on the remote {{domxref("MediaStream")}} and the corresponding event handler property of the remote {{domxref("MediaStream")}}. The {{domxref("RTCPeerConnection")}} API is now track-based, so having zero tracks in the remote stream is equivalent to the remote stream being removed, which caused a `removestream` event. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("removestream", (event) => {}); onremovestream = (event) => {}; ``` ## Event type A {{domxref("MediaStreamEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MediaStreamEvent")}} ## Event properties _A {{domxref("MediaStreamEvent")}} being an {{domxref("Event")}}, this event also implements these properties_. - {{domxref("MediaStreamEvent.stream")}} {{ReadOnlyInline}} - : Contains the {{domxref("MediaStream")}} containing the stream associated with the event. ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection.removeStream()")}} - {{domxref("MediaStream.removetrack_event", "removetrack")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/rtcpeerconnection/index.md
--- title: "RTCPeerConnection: RTCPeerConnection() constructor" short-title: RTCPeerConnection() slug: Web/API/RTCPeerConnection/RTCPeerConnection page-type: web-api-constructor browser-compat: api.RTCPeerConnection.RTCPeerConnection --- {{APIRef("WebRTC")}} The **`RTCPeerConnection()`** constructor returns a newly-created {{domxref("RTCPeerConnection")}}, which represents a connection between the local device and a remote peer. ## Syntax ```js-nolint new RTCPeerConnection() new RTCPeerConnection(configuration) ``` ### Parameters - `configuration` {{optional_inline}} - : An object providing options to configure the new connection: - `bundlePolicy` {{optional_inline}} - : Specifies how to handle negotiation of candidates when the remote peer is not compatible with the [SDP BUNDLE standard](https://webrtcstandards.info/sdp-bundle/). 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 {{domxref("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 {{domxref("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 {{domxref("RTCDtlsTransport")}} to carry all of the {{DOMxRef("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_inline}} - : An {{jsxref("Array")}} of objects of type {{domxref("RTCCertificate")}} which are used by the connection for authentication. If this property isn't specified, a set of certificates is generated automatically for each {{domxref("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](#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 {{domxref("RTCPeerConnection.setConfiguration()")}}. - `iceCandidatePoolSize` {{optional_inline}} - : 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 {{domxref("RTCPeerConnection.setLocalDescription()")}} is called. > **Note:** Changing the size of the ICE candidate pool may trigger the beginning of ICE gathering. - `iceServers` {{optional_inline}} - : 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_inline}} - : The credential to use when logging into the server. This is only used if the object represents a TURN server. - `credentialType` {{optional_inline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : 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_inline}} - : If the object represents a TURN server, then this is the username to use during the authentication. - `iceTransportPolicy` {{optional_inline}} - : 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_inline}} - : 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_inline}} - : A string which specifies the target peer identity for the {{domxref("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_inline}} - : 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 {{Glossary("RTP")}} and {{Glossary("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 {{domxref("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 {{domxref("RTCPeerConnection")}} instead of having the `RTCPeerConnection` generate them automatically, you do so by calling the static {{domxref("RTCPeerConnection.generateCertificate_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 {{domxref("RTCPeerConnection.setConfiguration", "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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling) - [WebRTC architecture overview](/en-US/docs/Web/API/WebRTC_API/Protocols) - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime) - {{domxref("RTCPeerConnection")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/datachannel_event/index.md
--- title: "RTCPeerConnection: datachannel event" short-title: datachannel slug: Web/API/RTCPeerConnection/datachannel_event page-type: web-api-event browser-compat: api.RTCPeerConnection.datachannel_event --- {{APIRef("WebRTC")}} A **`datachannel`** event is sent to an {{domxref("RTCPeerConnection")}} instance when an {{domxref("RTCDataChannel")}} has been added to the connection, as a result of the remote peer calling {{domxref("RTCPeerConnection.createDataChannel()")}}. > **Note:** This event is _not_ dispatched when the local end of the connection creates the channel. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("datachannel", (event) => {}); ondatachannel = (event) => {}; ``` ## Event type An {{domxref("RTCDataChannelEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("RTCDataChannelEvent")}} ## Event properties _Also inherits properties from {{DOMxRef("Event")}}._ - {{DOMxRef("RTCDataChannelEvent.channel", "channel")}} {{ReadOnlyInline}} - : Returns the {{domxref("RTCDataChannel")}} associated with the event. ## Examples This example sets up a function that handles `datachannel` events by gathering the information needed to communicate with the newly added {{domxref("RTCDataChannel")}} and by adding event handlers for the events that occur on that channel. ```js pc.addEventListener( "datachannel", (ev) => { receiveChannel = ev.channel; receiveChannel.onmessage = myHandleMessage; receiveChannel.onopen = myHandleOpen; receiveChannel.onclose = myHandleClose; }, false, ); ``` `receiveChannel` is set to the value of the event's {{domxref("RTCDataChannelEvent.channel", "channel")}} property, which specifies the `RTCDataChannel` object representing the data channel linking the remote peer to the local one. This same code can also instead use the {{domxref("RTCPeerConnection")}} interface's `ondatachannel` event handler property, like this: ```js pc.ondatachannel = (ev) => { receiveChannel = ev.channel; receiveChannel.onmessage = myHandleMessage; receiveChannel.onopen = myHandleOpen; receiveChannel.onclose = myHandleClose; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Using WebRTC data channels](/en-US/docs/Web/API/WebRTC_API/Using_data_channels) - [A simple RTCDataChannel sample](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample) - {{domxref("RTCDataChannelEvent")}} - {{domxref("RTCPeerConnection.createDataChannel()")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/getconfiguration/index.md
--- title: "RTCPeerConnection: getConfiguration() method" short-title: getConfiguration() slug: Web/API/RTCPeerConnection/getConfiguration page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.getConfiguration --- {{APIRef("WebRTC")}} The **`RTCPeerConnection.getConfiguration()`** method returns an object which indicates the current configuration of the {{domxref("RTCPeerConnection")}} on which the method is called. The returned configuration is the last configuration applied via {{domxref("RTCPeerConnection.setConfiguration","setConfiguration()")}}, or if `setConfiguration()` hasn't been called, the configuration the `RTCPeerConnection` was constructed with. The configuration includes a list of the ICE servers used by the connection, information about transport policies, and identity information. ## Syntax ```js-nolint getConfiguration() ``` ### Parameters This method takes no input parameters. ### Return value An object describing the {{domxref("RTCPeerConnection")}}'s current configuration. See [`RTCPeerConnection()`](/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#parameters) for more information on what options are allowed. ## Examples This example adds a new certificate to an active connection if it doesn't already have one in use. ```js let configuration = myPeerConnection.getConfiguration(); if (configuration.certificates?.length === 0) { RTCPeerConnection.generateCertificate({ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), }).then((cert) => { configuration.certificates = [cert]; myPeerConnection.setConfiguration(configuration); }); } ``` This example fetches the current configuration of the {{domxref("RTCPeerConnection")}}, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for `certificates`, and (b) whether its length is zero. If it's determined that there are no certificates in place, {{domxref("RTCPeerConnection.generateCertificate_static", "RTCPeerConnection.generateCertificate()")}} is called to create a new certificate; we provide a fulfillment handler which adds a new array containing the one newly-created certificate to the current configuration and passes it to {{domxref("RTCPeerConnect.setConfiguration", "setConfiguration()")}} to add the certificate to the connection. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("RTCPeerConnection.setConfiguration()")}} - {{domxref("RTCPeerConnection.RTCPeerConnection", "RTCPeerConnection()")}} - {{domxref("RTCPeerConnection")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/addtransceiver/index.md
--- title: "RTCPeerConnection: addTransceiver() method" short-title: addTransceiver() slug: Web/API/RTCPeerConnection/addTransceiver page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.addTransceiver --- {{APIRef("WebRTC")}} The {{domxref("RTCPeerConnection")}} method **`addTransceiver()`** creates a new {{domxref("RTCRtpTransceiver")}} and adds it to the set of transceivers associated with the `RTCPeerConnection`. Each transceiver represents a bidirectional stream, with both an {{domxref("RTCRtpSender")}} and an {{domxref("RTCRtpReceiver")}} associated with it. ## Syntax ```js-nolint addTransceiver(trackOrKind) addTransceiver(trackOrKind, init) ``` ### Parameters - `trackOrKind` - : A {{domxref("MediaStreamTrack")}} to associate with the transceiver, or a string which is used as the {{domxref("MediaStreamTrack.kind", "kind")}} of the receiver's {{domxref("RTCRtpReceiver.track", "track")}}, and by extension of the {{domxref("RTCRtpReceiver")}} itself. - `init` {{optional_inline}} - : An object for specifying any options when creating the new transceiver. Possible values are: - `direction` {{optional_inline}} - : The new transceiver's preferred directionality. This value is used to initialize the new {{domxref("RTCRtpTransceiver")}} object's {{domxref("RTCRtpTransceiver.direction")}} property. - `sendEncodings` {{optional_inline}} - : An array of encodings to allow when sending RTP media from the {{domxref("RTCRtpSender")}}. This is the same as the [`parameter.encodings`](/en-US/docs/Web/API/RTCRtpSender/setParameters#encodings) array passed to {{domxref("RTCRtpSender.setParameters()")}}. - `streams` {{optional_inline}} - : A list of {{domxref("MediaStream")}} objects to add to the transceiver's {{domxref("RTCRtpReceiver")}}; when the remote peer's {{domxref("RTCPeerConnection")}}'s {{domxref("RTCPeerConnection.track_event", "track")}} event occurs, these are the streams that will be specified by that event. ### Return value The {{domxref("RTCRtpTransceiver")}} object which will be used to exchange the media data. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if `trackOrKind` was not either `"audio"` or `"video"`. If the `sendEncodings` argument is used, this error may also be thrown if there is a badly formatted `rid` member, some but not all encodings contain a `rid` member, or different encodings have the same `rid` value. - {{jsxref("RangeError")}} - : Thrown if any of the `sendEncodings` encodings have a `maxFramerate` value less than 0.0, or a `scaleResolutionDownBy` value of less than 1.0. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the method is called when the associated connection is closed. - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if the `sendEncodings` argument is used, and contains a read-only parameter other than `rid`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Introduction to the Real-time Transport Protocol (RTP)](/en-US/docs/Web/API/WebRTC_API/Intro_to_RTP) - {{domxref("RTCPeerConnection.addTrack()")}} also creates transceivers - {{domxref("RTCRtpReceiver")}} and {{domxref("RTCRtpSender")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/removestream/index.md
--- title: "RTCPeerConnection: removeStream() method" short-title: removeStream() slug: Web/API/RTCPeerConnection/removeStream page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.RTCPeerConnection.removeStream --- {{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`RTCPeerConnection.removeStream()`** method removes a {{domxref("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 {{domxref("RTCPeerConnection.removeTrack", "removeTrack()")}} if your target browser versions have implemented it. If the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is set to `"closed"`, an `InvalidStateError` is raised. If the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is set to `"stable"`, the event {{DOMxRef("RTCPeerConnection/negotiationneeded_event", "negotiationneeded")}} is sent on the {{domxref("RTCPeerConnection")}}. ## Syntax ```js-nolint removeStream(mediaStream) ``` ### Parameters - `mediaStream` - : A {{domxref("MediaStream")}} specifying the stream to remove from the connection. ### Return value {{jsxref("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 {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection.removeTrack()")}} - {{domxref("RTCPeerConnection.addTrack()")}} - {{domxref("RTCPeerConnection.addStream()")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/getreceivers/index.md
--- title: "RTCPeerConnection: getReceivers() method" short-title: getReceivers() slug: Web/API/RTCPeerConnection/getReceivers page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.getReceivers --- {{APIRef("WebRTC")}} The **`RTCPeerConnection.getReceivers()`** method returns an array of {{domxref("RTCRtpReceiver")}} objects, each of which represents one RTP receiver. Each RTP receiver manages the reception and decoding of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}. ## Syntax ```js-nolint getReceivers() ``` ### Return value An array of {{domxref("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](/en-US/docs/Web/API/RTCRtpTransceiver/currentDirection) (following offer/answer). ## Example tbd ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCRtpSender")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/gettransceivers/index.md
--- title: "RTCPeerConnection: getTransceivers() method" short-title: getTransceivers() slug: Web/API/RTCPeerConnection/getTransceivers page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.getTransceivers --- {{APIRef("WebRTC")}} The {{domxref("RTCPeerConnection")}} interface's **`getTransceivers()`** method returns a list of the {{domxref("RTCRtpTransceiver")}} objects being used to send and receive data on the connection. ## Syntax ```js-nolint getTransceivers() ``` ### Parameters None. ### Return value An array of the {{domxref("RTCRtpTransceiver")}} objects representing the transceivers handling sending and receiving all media on the `RTCPeerConnection`. The array is in the order in which the transceivers were added to the connection. The array does not include transceivers that have already been [stopped](/en-US/docs/Web/API/RTCRtpTransceiver/currentDirection) (following offer/answer). ## Examples The following snippet of code stops all transceivers associated with an `RTCPeerConnection`. ```js pc.getTransceivers().forEach((transceiver) => { transceiver.stop(); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling) - {{domxref("RTCPeerConnection.addTransceiver()")}} - {{jsxref("Array.forEach()")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/getidentityassertion/index.md
--- title: "RTCPeerConnection: getIdentityAssertion() method" short-title: getIdentityAssertion() slug: Web/API/RTCPeerConnection/getIdentityAssertion page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.getIdentityAssertion --- {{APIRef("WebRTC")}} The **`RTCPeerConnection.getIdentityAssertion()`** method initiates the gathering of an identity assertion. This has an effect only if the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is not `"closed"`. The method returns a JavaScript {{jsxref("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-nolint 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/localdescription/index.md
--- title: "RTCPeerConnection: localDescription property" short-title: localDescription slug: Web/API/RTCPeerConnection/localDescription page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.localDescription --- {{APIRef("WebRTC")}} The read-only property **`RTCPeerConnection.localDescription`** returns an {{domxref("RTCSessionDescription")}} describing the session for the local end of the connection. If it has not yet been set, this is `null`. ## Syntax ```js-nolint const sessionDescription = peerConnection.localDescription ``` On a more fundamental level, the returned value is the value of {{domxref("RTCPeerConnection.pendingLocalDescription")}} if that property isn't `null`; otherwise, the value of {{domxref("RTCPeerConnection.currentLocalDescription")}} is returned. See [Pending and current descriptions](/en-US/docs/Web/API/WebRTC_API/Connectivity#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 {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("RTCPeerConnection.setLocalDescription()")}}, {{domxref("RTCPeerConnection.pendingLocalDescription")}}, {{domxref("RTCPeerConnection.currentLocalDescription")}} - {{domxref("RTCPeerConnection.setRemoteDescription()")}}, {{domxref("RTCPeerConnection.remoteDescription")}}, {{domxref("RTCPeerConnection.pendingRemoteDescription")}}, {{domxref("RTCPeerConnection.currentRemoteDescription")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/createoffer/index.md
--- title: "RTCPeerConnection: createOffer() method" short-title: createOffer() slug: Web/API/RTCPeerConnection/createOffer page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.createOffer --- {{APIRef("WebRTC")}} The **`createOffer()`** method of the {{domxref("RTCPeerConnection")}} interface initiates the creation of an {{Glossary("SDP")}} offer for the purpose of starting a new WebRTC connection to a remote peer. The SDP offer includes information about any {{domxref("MediaStreamTrack")}} objects already attached to the WebRTC session, codec, and options supported by the browser, and any candidates already gathered by the {{Glossary("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 {{jsxref("Promise")}} which, when the offer has been created, is resolved with a {{domxref("RTCSessionDescription")}} object containing the newly-created offer. ## Syntax ```js-nolint createOffer() createOffer(options) createOffer(successCallback, failureCallback) // deprecated createOffer(successCallback, failureCallback, options) // deprecated ``` ### Parameters - `options` {{optional_inline}} - : An object providing the following options requested for the offer: - `iceRestart` {{optional_inline}} - : 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_inline}} {{deprecated_inline}} - : 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_inline}} {{deprecated_inline}} - : 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 {{jsxref("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_inline}} - : A [callback function](/en-US/docs/Glossary/Callback_function) which will be passed a single {{domxref("RTCSessionDescription")}} object describing the newly-created offer. - `errorCallback` {{deprecated_inline}} - : A [callback function](/en-US/docs/Glossary/Callback_function) which will be passed a single {{domxref("DOMException")}} object explaining why the request to create an offer failed. - `options` {{optional_inline}} - : An optional object providing options requested for the offer. ### Return value A {{jsxref("Promise")}} whose fulfillment handler will receive an object conforming to the [RTCSessionDescriptionInit](/en-US/docs/Web/API/RTCSessionDescription/RTCSessionDescription#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` {{domxref("DOMException")}} - : Returned if the `RTCPeerConnection` is closed. - `NotReadableError` {{domxref("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` {{domxref("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 {{DOMxRef("RTCPeerConnection/negotiationneeded_event", "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](/en-US/docs/Web/API/WebSockets_API) connection is > used to send a {{Glossary("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 {{domxref("RTCPeerConnection")}} is configured to match by passing the offer (which is represented using an object conforming to [RTCSessionDescriptionInit](/en-US/docs/Web/API/RTCSessionDescription/RTCSessionDescription#rtcsessiondescriptioninit)) into {{domxref("RTCPeerConnection.setLocalDescription", "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 {{jsxref("Promise.catch()")}} to trap and handle errors. See [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/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 {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/createanswer/index.md
--- title: "RTCPeerConnection: createAnswer() method" short-title: createAnswer() slug: Web/API/RTCPeerConnection/createAnswer page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.createAnswer --- {{APIRef("WebRTC")}} The **`createAnswer()`** method on the {{domxref("RTCPeerConnection")}} interface creates an {{Glossary("SDP")}} answer to an offer received from a remote peer during the offer/answer negotiation of a WebRTC connection. The answer contains information about any media already attached to the session, codecs and options supported by the browser, and any {{Glossary("ICE")}} candidates already gathered. The answer is delivered to the returned {{jsxref("Promise")}}, and should then be sent to the source of the offer to continue the negotiation process. ## Syntax ```js-nolint createAnswer() createAnswer(options) createAnswer(successCallback, failureCallback) // deprecated createAnswer(successCallback, failureCallback, options) // deprecated ``` ### Parameters - `options` {{optional_inline}} - : An optional object providing options requested for the answer. Currently, there are no available options. ### 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 {{jsxref("Promise")}}-based version of `createAnswer()` instead. The parameters for the older form of `createAnswer()` are described below, to aid in updating existing code. - `successCallback` {{deprecated_inline}} - : A [callback function](/en-US/docs/Glossary/Callback_function) which will be passed a single {{domxref("RTCSessionDescription")}} object describing the newly-created answer. - `failureCallback` {{deprecated_inline}} - : A [callback function](/en-US/docs/Glossary/Callback_function) which will be passed a single {{domxref("DOMException")}} object explaining why the request to create an answer failed. - `options` {{optional_inline}} - : An optional object providing options requested for the answer. ### Exceptions - `NotReadableError` - : The identity provider wasn't able to provide an identity assertion. - `OperationError` - : Generation of the SDP failed for some reason; this is a general failure catch-all exception. ### Return value A {{jsxref("Promise")}} whose fulfillment handler is called with an object conforming to the {{domxref("RTCSessionDescriptionInit")}} dictionary which contains the SDP answer to be delivered to the other peer. ## Examples Here is a segment of code taken from the code that goes with the article [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling). This code comes from the handler for the message sent to carry an offer to another peer across the 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](/en-US/docs/Web/API/WebSockets_API) connection is used to send a > {{Glossary("JSON")}} message with a `type` field with the value > "video-answer" to the other peer, carrying the answer to the device which sent the > offer to connect. 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 pc.createAnswer() .then((answer) => pc.setLocalDescription(answer)) .then(() => { // Send the answer to the remote peer through the signaling server. }) .catch(handleGetUserMediaError); ``` This asks {{domxref("RTCPeerConnection")}} to create and return a new answer. In our promise handler, the returned answer is set as the description of the local end of the connection by calling {{domxref("RTCPeerConnection.setLocalDescription", "setLocalDescription()")}}. Once that succeeds, the answer is sent to the signaling server using whatever protocol you see fit. {{jsxref("Promise.catch()")}} is used to trap and handle errors. See [Handling the invitation](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling#handling_the_invitation) in our WebRTC chat example to view the complete code from which this snippet is derived; that will help you understand the signaling process and how answers work. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/negotiationneeded_event/index.md
--- title: "RTCPeerConnection: negotiationneeded event" short-title: negotiationneeded slug: Web/API/RTCPeerConnection/negotiationneeded_event page-type: web-api-event browser-compat: api.RTCPeerConnection.negotiationneeded_event --- {{APIRef("WebRTC")}} A **`negotiationneeded`** event is sent to the {{domxref("RTCPeerConnection")}} when negotiation of the connection through the signaling channel is required. This occurs both during the initial setup of the connection as well as any time a change to the communication environment requires reconfiguring the connection. The `negotiationneeded` event is first dispatched to the {{domxref("RTCPeerConnection")}} when media is first added to the connection. This starts the process of {{Glossary("ICE")}} negotiation by instructing your code to begin exchanging ICE candidates through the signaling server. See [Signaling transaction flow](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling#signaling_transaction_flow) for a description of the signaling process that begins with a `negotiationneeded` event. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("negotiationneeded", (event) => {}); onnegotiationneeded = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples In this example, we use {{domxref("EventTarget.addEventListener", "addEventListener()")}} to create an event handler for `negotiationneeded`. Its role is to create an {{Glossary("SDP")}} offer and send it through the signaling channel to the remote peer. ```js pc.addEventListener( "negotiationneeded", (ev) => { pc.createOffer() .then((offer) => pc.setLocalDescription(offer)) .then(() => sendSignalingMessage({ type: "video-offer", sdp: pc.localDescription, }), ) .catch((err) => { // handle error }); }, false, ); ``` After creating the offer, the local end is configured by calling {{domxref("RTCPeerConnection.setLocalDescription()")}}; then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer. The other peer should recognize this message and follow up by creating its own {{domxref("RTCPeerConnection")}}, setting the remote description with {{domxref("RTCPeerConnection.setRemoteDescription", "setRemoteDescription()")}}, and then creating an answer to send back to the offering peer. You can also set an event handler for the `negotiationneeded` event by assigning the event handler function to the `onnegotiationneeded` property: ```js pc.onnegotiationneeded = (ev) => { pc.createOffer() .then((offer) => pc.setLocalDescription(offer)) .then(() => sendSignalingMessage({ type: "video-offer", sdp: pc.localDescription, }), ) .catch((err) => { // handle error }); }; ``` For a more detailed example, see [Starting negotiation](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling#starting_negotiation). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling) - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime) - [WebRTC connectivity](/en-US/docs/Web/API/WebRTC_API/Connectivity) - [Introduction to WebRTC protocols](/en-US/docs/Web/API/WebRTC_API/Protocols)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/connectionstate/index.md
--- title: "RTCPeerConnection: connectionState property" short-title: connectionState slug: Web/API/RTCPeerConnection/connectionState page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.connectionState --- {{APIRef("WebRTC")}} The read-only **`connectionState`** property of the {{domxref("RTCPeerConnection")}} interface indicates the current state of the peer connection by returning one of the following string values: `new`, `connecting`, `connected`, `disconnected`, `failed`, or `closed`. This state essentially represents the aggregate state of all ICE transports (which are of type {{domxref("RTCIceTransport")}} or {{domxref("RTCDtlsTransport")}}) being used by the connection. When this property's value changes, a {{domxref("RTCPeerConnection.connectionstatechange_event", "connectionstatechange")}} event is sent to the {{domxref("RTCPeerConnection")}} instance. ## Value A string representing the current state of the connection. This can take on of the following values: - `new` - : At least one of the connection's {{Glossary("ICE")}} transports ({{domxref("RTCIceTransport")}} or {{domxref("RTCDtlsTransport")}} objects) is in the `new` state, and none of them are in one of the following states: `connecting`, `checking`, `failed`, `disconnected`, or all of the connection's transports are in the `closed` state. - `connecting` - : One or more of the {{Glossary("ICE")}} transports are currently in the process of establishing a connection; that is, their {{DOMxRef("RTCPeerConnection.iceConnectionState", "iceConnectionState")}} is either `checking` or `connected`, and no transports are in the `failed` state. - `connected` - : Every {{Glossary("ICE")}} transport used by the connection is either in use (state `connected` or `completed`) or is closed (state `closed`); in addition, at least one transport is either `connected` or `completed`. - `disconnected` - : At least one of the {{Glossary("ICE")}} transports for the connection is in the `disconnected` state and none of the other transports are in the states: `failed`, `connecting`, or `checking`. - `failed` - : One or more of the {{Glossary("ICE")}} transports on the connection is in the `failed` state. - `closed` - : The {{DOMxRef("RTCPeerConnection")}} is closed. ## Example ```js const peerConnection = new RTCPeerConnection(configuration); // … const connectionState = peerConnection.connectionState; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime) - {{domxref("RTCPeerConnection")}} - {{domxref("RTCPeerConnection.connectionstatechange_event", "connectionstatechange")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/setremotedescription/index.md
--- title: "RTCPeerConnection: setRemoteDescription() method" short-title: setRemoteDescription() slug: Web/API/RTCPeerConnection/setRemoteDescription page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.setRemoteDescription --- {{APIRef("WebRTC")}} The {{domxref("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 {{jsxref("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-nolint setRemoteDescription(sessionDescription) ``` ### Parameters - `sessionDescription` - : An {{domxref("RTCSessionDescriptionInit")}} or {{domxref("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 {{domxref("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`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function)/[`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) syntax, you can further simplify this to: ```js await myPeerConnection.setRemoteDescription(description); createMyStream(); ``` Since it's unnecessary, the {{domxref("RTCSessionDescription.RTCSessionDescription", "RTCSessionDescription()")}} constructor is deprecated. ### Return value A {{jsxref("Promise")}} which is fulfilled once the value of the connection's {{domxref("RTCPeerConnection.remoteDescription", "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](/en-US/docs/Web/API/WebRTC_API/Connectivity#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` {{domxref("DOMException")}} - : Returned if the content of the description is invalid. - `InvalidStateError` {{domxref("DOMException")}} - : Returned if the {{domxref("RTCPeerConnection")}} is closed, or it's in a state that is not compatible with the specified description's {{domxref("RTCSessionDescription.type", "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` {{domxref("DOMException")}} - : Returned if an error does not match the ones specified here. This includes identity validation errors. - `RTCError` {{domxref("DOMException")}} - : Returned with the {{domxref("RTCError.errorDetail", "errorDetail")}} set to `sdp-syntax-error` if the {{Glossary("SDP")}} specified by {{domxref("RTCSessionDescription.sdp")}} is not valid. The error object's {{domxref("RTCError.sdpLineNumber", "sdpLineNumber")}} property indicates the line number within the SDP on which the syntax error was detected. - {{jsxref("TypeError")}} - : Returned if the specified `RTCSessionDescriptionInit` or `RTCSessionDescription` object is missing the {{domxref("RTCSessionDescription.type", "type")}} property, or no description parameter was provided at all. ## Usage notes When you call `setRemoteDescription()`, the ICE agent checks to make sure the {{domxref("RTCPeerConnection")}} is in either the `stable` or `have-remote-offer` {{domxref("RTCPeerConnection.signalingState", "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 {{jsxref("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_inline}} - : A JavaScript {{jsxref("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_inline}} - : A function matching the signature `RTCPeerConnectionErrorCallback` which gets called if the description can't be set. It is passed a single {{domxref("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_inline}} - : The connection's {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is `"closed"`, indicating that the connection is not currently open, so negotiation cannot take place. - `InvalidSessionDescriptionError` {{deprecated_inline}} - : The {{domxref("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](/en-US/docs/Web/API/WebRTC_API/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 {{domxref("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 {{domxref("RTCPeerConnection.setLocalDescription", "setLocalDescription()")}} to set that as the configuration at our end of the call before forwarding that answer to the caller. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection.remoteDescription")}}, {{domxref("RTCPeerConnection.pendingRemoteDescription")}}, {{domxref("RTCPeerConnection.currentRemoteDescription")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/generatecertificate_static/index.md
--- title: "RTCPeerConnection: generateCertificate() static method" short-title: generateCertificate() slug: Web/API/RTCPeerConnection/generateCertificate_static page-type: web-api-static-method browser-compat: api.RTCPeerConnection.generateCertificate_static --- {{APIRef("WebRTC")}} The static **`RTCPeerConnection.generateCertificate()`** function creates an X.509 certificate and corresponding private key, returning a promise that resolves with the new {{domxref("RTCCertificate")}} once it's generated. ## Syntax ```js-nolint RTCPeerConnection.generateCertificate(keygenAlgorithm) ``` ### Parameters - `keygenAlgorithm` - : A [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) {{domxref("AlgorithmIdentifier")}} string or an {{domxref("Algorithm")}} -subclassed object specifying an algorithm to use when creating the certificate's key. > **Note:** `RTCPeerConnection.generateCertificate()` is a static method, so it is > always called on the `RTCPeerConnection` interface itself, not an instance > thereof. ### Return value A promise which resolves to a new {{domxref("RTCCertificate")}} object containing a new key based on the specified options. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the normalized form of `keygenAlgorithm` specifies an algorithm or algorithm settings that the browser doesn't support, or which it does not allow for use with an {{domxref("RTCPeerConnection")}}. Other errors may occur; for example, if the specified `keygenAlgorithm` can't be successfully converted into an {{domxref("RTCCertificateExpiration")}} dictionary, the error that occurs during that conversion will be thrown. ## Description If a string is specified, it must be a [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API)-compatible algorithm name string. Alternatively, you can provide specific details for the algorithm's configuration by providing an object based on one of the Web Crypto API's {{domxref("Algorithm")}} class's subclasses. ### Standard configurations All browsers are required to support the following two configurations. It's entirely possible that a browser's _default_ settings may be different, but these are always supported. #### RSASSA-PKCS1-v1_5 ```js let stdRSACertificate = { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }; ``` #### ECDSA ```js let stdECDSACertificate = { name: "ECDSA", namedCurve: "P-256", }; ``` ### Certificate expiration time By default the new certificate is configured with `expires` set to a value of 2592000000 milliseconds, or 30 days. The expiration time cannot exceed 31536000000 milliseconds, or 365 days. It's also useful to note that browsers may further restrict the expiration time of certificates if they choose. ## Examples ### Specifying algorithm details This example requests a new RSASSA-PKCS1-v1_5 certificate using a SHA-256 hash and a modulus length of 2048. ```js RTCPeerConnection.generateCertificate({ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), }).then((cert) => { const pc = new RTCPeerConnection({ certificates: [cert] }); }); ``` ### Specifying an algorithm by name The example below specifies a string requesting an [ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm) certificate. ```js RTCPeerConnection.generateCertificate("ECDSA"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) - [Website security](/en-US/docs/Learn/Server-side/First_steps/Website_security) - [Web security](/en-US/docs/Web/Security) - {{Glossary("Symmetric-key cryptography")}} - [`crypto`](/en-US/docs/Web/API/Crypto)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/setconfiguration/index.md
--- title: "RTCPeerConnection: setConfiguration() method" short-title: setConfiguration() slug: Web/API/RTCPeerConnection/setConfiguration page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.setConfiguration --- {{APIRef("WebRTC")}} The **`RTCPeerConnection.setConfiguration()`** method sets the current configuration of the {{domxref("RTCPeerConnection")}} based on the values included in the specified object. This lets you change the ICE servers used by the connection and which transport policies to use. The most common use case for this method (and even then, probably not a very common use case) is to replace the set of ICE servers to be used. Two potential scenarios in which this might be done: - The {{domxref("RTCPeerConnection")}} was instantiated without specifying any ICE servers. If, for example, the {{domxref("RTCPeerConnection.RTCPeerConnection()", "RTCPeerConnection()")}} constructor was called with no parameters, you would have to then call `setConfiguration()` to add ICE servers before ICE negotiation could begin. - Renegotiation of the connection is needed, and a different set of ICE servers needs to be used for some reason. Perhaps the user has moved into a new region, so using new regional ICE servers is necessary, for example. In this situation, one might call `setConfiguration()` to switch to new regional ICE servers, then initiate an [ICE restart](/en-US/docs/Web/API/WebRTC_API/Session_lifetime#ice_restart). > **Note:** You cannot change the identity information for a connection once it's already been set. ## Syntax ```js-nolint setConfiguration(configuration) ``` ### Parameters - `configuration` - : An object which provides the options to be set. The changes are not additive; instead, the new values completely replace the existing ones. See [`RTCPeerConnection()`](/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#parameters) for more information on what options are allowed. ### Exceptions - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if one or more of the URLs specified in `configuration.iceServers` is a {{Glossary("TURN")}} server, but complete login information is not provided (that is, either the `username` or `credential` is missing, or if `credentialType` is `"password"` and `credential` is not a string). This prevents successful login to the server. - `InvalidModificationError` {{domxref("DOMException")}} - : Thrown if the `configuration` includes changed identity information, but the connection already has identity information specified. This happens if `configuration.peerIdentity` or `configuration.certificates` are set and their values differ from the current configuration. This may also be thrown if there are changes to `configuration.bundlePolicy` or `configuration.rtcpMuxPolicy`, or to `configuration.iceCandidatePoolSize` when {{domxref("RTCPeerConnection.setLocalDescription()")}} has already been called. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("RTCPeerConnection")}} is closed. - `SyntaxError` {{domxref("DOMException")}} - : Thrown if the `configuration.iceServers` contains no URLs or if one of the values in the list is invalid. - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if `configuration.iceServers` contains a URL with a scheme that is not supported. ## Example In this example, it has already been determined that ICE restart is needed, and that negotiation needs to be done using a different ICE server. ```js const restartConfig = { iceServers: [ { urls: "turn:asia.myturnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword", }, ], }; myPeerConnection.setConfiguration(restartConfig); myPeerConnection .createOffer({ iceRestart: true }) .then((offer) => myPeerConnection.setLocalDescription(offer)) .then(() => { // send the offer to the other peer using the signaling server }) .catch(reportError); ``` First, a new object is created, `restartConfig`, specifying the new ICE server and its credentials. This is then passed into `setConfiguration()`. ICE negotiation is restarted by calling {{domxref("RTCPeerConnection.createOffer()", "createOffer()")}}, specifying `true` as the value of the `iceRestart` option. From there, we handle the process as usual, by setting the local description to the returned offer and then sending that offer to the other peer. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("RTCPeerConnection.getConfiguration()")}} - {{domxref("RTCPeerConnection.RTCPeerConnection", "RTCPeerConnection()")}} - {{domxref("RTCPeerConnection")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/cantrickleicecandidates/index.md
--- title: "RTCPeerConnection: canTrickleIceCandidates property" short-title: canTrickleIceCandidates slug: Web/API/RTCPeerConnection/canTrickleIceCandidates page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.canTrickleIceCandidates --- {{APIRef("WebRTC")}} The read-only **{{domxref("RTCPeerConnection")}}** property **`canTrickleIceCandidates`** returns a boolean value which indicates whether or not the remote peer can accept [trickled ICE candidates](https://datatracker.ietf.org/doc/html/draft-ietf-mmusic-trickle-ice). **ICE trickling** is the process of continuing to send candidates after the initial offer or answer has already been sent to the other peer. This property is only set after having called {{domxref("RTCPeerConnection.setRemoteDescription()")}}. Ideally, your signaling protocol provides a way to detect trickling support, so that you don't need to rely on this property. A WebRTC browser will always support trickle ICE. If trickling isn't supported, or you aren't able to tell, you can check for a falsy value for this property and then wait until the value of {{domxref("RTCPeerConnection.iceGatheringState", "iceGatheringState")}} changes to `"completed"` before creating and sending the initial offer. That way, the offer contains all of the candidates. ## Value A boolean value that is `true` if the remote peer can accept trickled ICE candidates and `false` if it cannot. If no remote peer has been established, this value is `null`. > **Note:** This property's value is determined once the local peer has > called {{domxref("RTCPeerConnection.setRemoteDescription()")}}; the provided > description is used by the ICE agent to determine whether or not the remote peer > supports trickled ICE candidates. ## Examples ```js const pc = new RTCPeerConnection(); function waitToCompleteIceGathering(pc) { return new Promise((resolve) => { pc.addEventListener( "icegatheringstatechange", (e) => e.target.iceGatheringState === "complete" && resolve(pc.localDescription), ); }); } // The following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ICE. async function newPeer(remoteOffer) { await pc.setRemoteDescription(remoteOffer); const offer = await pc.createOffer(); await pc.setLocalDescription(offer); if (pc.canTrickleIceCandidates) return pc.localDescription; const answer = await waitToCompleteIceGathering(pc); sendAnswerToPeer(answer); //To peer via signaling channel } // Handle error with try/catch pc.addEventListener( "icecandidate", (e) => pc.canTrickleIceCandidates && sendCandidateToPeer(e.candidate), ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection.addIceCandidate()")}} - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/icegatheringstate/index.md
--- title: "RTCPeerConnection: iceGatheringState property" short-title: iceGatheringState slug: Web/API/RTCPeerConnection/iceGatheringState page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.iceGatheringState --- {{APIRef("WebRTC")}} The read-only property **`RTCPeerConnection.iceGatheringState`** returns a string that describes the connection's ICE gathering state. This lets you detect, for example, when collection of ICE candidates has finished. You can detect when the value of this property changes by watching for an event of type {{DOMxRef("RTCPeerConnection/icegatheringstatechange_event", "icegatheringstatechange")}}. ## Value The possible values are: - `new` - : The peer connection was just created and hasn't done any networking yet. - `gathering` - : The ICE agent is in the process of gathering candidates for the connection. - `complete` - : The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to `gathering` to gather those candidates. ## Example ```js const pc = new RTCPeerConnection(); const state = pc.iceGatheringState; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("RTCPeerConnection/icegatheringstatechange_event", "icegatheringstatechange")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/remotedescription/index.md
--- title: "RTCPeerConnection: remoteDescription property" short-title: remoteDescription slug: Web/API/RTCPeerConnection/remoteDescription page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.remoteDescription --- {{APIRef("WebRTC")}} The read-only property **`RTCPeerConnection.remoteDescription`** returns a {{domxref("RTCSessionDescription")}} describing the session (which includes configuration and media information) for the remote end of the connection. If this hasn't been set yet, this is `null`. The returned value typically reflects a remote description which has been received over the signaling server (as either an offer or an answer) and then put into effect by your code calling {{domxref("RTCPeerConnection.setRemoteDescription()")}} in response. ## Syntax ```js-nolint const sessionDescription = peerConnection.remoteDescription ``` On a more fundamental level, the returned value is the value of {{domxref("RTCPeerConnection.pendingRemoteDescription")}} if that property isn't `null`; otherwise, the value of {{domxref("RTCPeerConnection.currentRemoteDescription")}} is returned. See [Pending and current descriptions](/en-US/docs/Web/API/WebRTC_API/Connectivity#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 `remoteDescription` and displays an alert containing the {{domxref("RTCSessionDescription")}} object's `type` and `sdp` fields. ```js const pc = new RTCPeerConnection(); // ... const sd = pc.remoteDescription; if (sd) { alert(`Remote session: type='${sd.type}'; sdp description='${sd.sdp}'`); } else { alert("No remote session yet."); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("RTCPeerConnection.setRemoteDescription()")}}, {{domxref("RTCPeerConnection.pendingRemoteDescription")}}, {{domxref("RTCPeerConnection.currentRemoteDescription")}} - {{domxref("RTCPeerConnection.setLocalDescription()")}}, {{domxref("RTCPeerConnection.pendingLocalDescription")}}, {{domxref("RTCPeerConnection.currentLocalDescription")}}, {{domxref("RTCPeerConnection.localDescription")}} - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/iceconnectionstate/index.md
--- title: "RTCPeerConnection: iceConnectionState property" short-title: iceConnectionState slug: Web/API/RTCPeerConnection/iceConnectionState page-type: web-api-instance-property browser-compat: api.RTCPeerConnection.iceConnectionState --- {{APIRef("WebRTC")}} The read-only property **`RTCPeerConnection.iceConnectionState`** returns a string which state of the {{Glossary("ICE")}} agent associated with the {{domxref("RTCPeerConnection")}}: `new`, `checking`, `connected`, `completed`, `failed`, `disconnected`, and `closed`. It describes the current state of the ICE agent and its connection to the ICE server; that is, the {{Glossary("STUN")}} or {{Glossary("TURN")}} server. You can detect when this value has changed by watching for the {{DOMxRef("RTCPeerConnection.iceconnectionstatechange_event", "iceconnectionstatechange")}} event. ## Value The current state of the ICE agent and its connection. The value is one of the following strings: - `new` - : The ICE agent is gathering addresses or is waiting to be given remote candidates through calls to {{domxref("RTCPeerConnection.addIceCandidate()")}} (or both). - `checking` - : The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. It is possible that gathering of candidates is also still underway. - `connected` - : A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It is possible that gathering is still underway, and it is also possible that the ICE agent is still checking candidates against one another looking for a better connection to use. - `completed` - : The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components. - `failed` - : The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for some components. - `disconnected` - : Checks to ensure that components are still connected failed for at least one component of the {{domxref("RTCPeerConnection")}}. This is a less stringent test than `failed` and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. When the problem resolves, the connection may return to the `connected` state. - `closed` - : The ICE agent for this {{domxref("RTCPeerConnection")}} has shut down and is no longer handling requests. ## Examples ```js const pc = new RTCPeerConnection(); const state = pc.iceConnectionState; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - {{DOMxRef("RTCPeerConnection.iceconnectionstatechange_event", "iceconnectionstatechange")}} - {{domxref("RTCPeerConnection")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/connectionstatechange_event/index.md
--- title: "RTCPeerConnection: connectionstatechange event" short-title: connectionstatechange slug: Web/API/RTCPeerConnection/connectionstatechange_event page-type: web-api-event browser-compat: api.RTCPeerConnection.connectionstatechange_event --- {{APIRef("WebRTC")}} The **`connectionstatechange`** event is sent to the `onconnectionstatechange` event handler on an {{domxref("RTCPeerConnection")}} object after a new track has been added to an {{domxref("RTCRtpReceiver")}} which is part of the connection. The new connection state can be found in {{domxref("RTCPeerConnection.connectionState", "connectionState")}}, and is one of the string values: `new`, `connecting`, `connected`, `disconnected`, `failed`, or `closed`. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("connectionstatechange", (event) => {}); onconnectionstatechange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples For an {{domxref("RTCPeerConnection")}} named `peerConnection`, this example uses {{domxref("EventTarget.addEventListener", "addEventListener()")}} to handle changes to the connectivity of the WebRTC session. It calls an app-defined function called `setOnlineStatus()` to update a status display. ```js peerConnection.addEventListener( "connectionstatechange", (event) => { switch (peerConnection.connectionState) { case "new": case "connecting": setOnlineStatus("Connecting…"); break; case "connected": setOnlineStatus("Online"); break; case "disconnected": setOnlineStatus("Disconnecting…"); break; case "closed": setOnlineStatus("Offline"); break; case "failed": setOnlineStatus("Error"); break; default: setOnlineStatus("Unknown"); break; } }, false, ); ``` You can also create a handler for the `connectionstatechange` event using the `RTCPeerConnection.onconnectionstatechange` property: ```js peerConnection.onconnectionstatechange = (ev) => { switch (peerConnection.connectionState) { case "new": case "connecting": setOnlineStatus("Connecting…"); break; // … default: setOnlineStatus("Unknown"); break; } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [WebRTC connectivity](/en-US/docs/Web/API/WebRTC_API/Connectivity) - [Lifetime of a WebRTC session](/en-US/docs/Web/API/WebRTC_API/Session_lifetime) - {{domxref("RTCPeerConnection.connectionState")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/addstream/index.md
--- title: "RTCPeerConnection: addStream() method" short-title: addStream() slug: Web/API/RTCPeerConnection/addStream page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.RTCPeerConnection.addStream --- {{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}} The _obsolete_ {{domxref("RTCPeerConnection")}} method **`addStream()`** adds a {{domxref("MediaStream")}} as a local source of audio or video. Instead of using this obsolete method, you should instead use {{domxref("RTCPeerConnection.addTrack", "addTrack()")}} once for each track you wish to send to the remote peer. If the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is set to `closed`, an `InvalidStateError` is raised. If the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is set to `stable`, the event {{DOMxRef("RTCPeerConnection/negotiationneeded_event", "negotiationneeded")}} is sent on the {{domxref("RTCPeerConnection")}} to indicate that {{Glossary("ICE")}} negotiation must be repeated to consider the new stream. ## Syntax ```js-nolint addStream(mediaStream) ``` ### Parameters - `mediaStream` - : A {{domxref("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](#browser_compatibility), you should update your code to instead use the {{domxref("RTCPeerConnection.addTrack", "addTrack()")}} method: ```js navigator.getUserMedia({ video: true, audio: true }, (stream) => { const pc = new RTCPeerConnection(); stream.getTracks().forEach((track) => { pc.addTrack(track, stream); }); }); ``` The newer {{domxref("RTCPeerConnection.addTrack", "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 {{DOMxRef("RTCPeerConnection/negotiationneeded_event", "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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/close/index.md
--- title: "RTCPeerConnection: close() method" short-title: close() slug: Web/API/RTCPeerConnection/close page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.close --- {{APIRef("WebRTC")}} The **`RTCPeerConnection.close()`** method closes the current peer connection. ## Syntax ```js-nolint 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 {{domxref("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 {{domxref("RTCPeerConnection.signalingState")}} is `closed`. Make sure that you `delete` all references to the previous {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection")}} - {{domxref("RTCPeerConnection.signalingState")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/track_event/index.md
--- title: "RTCPeerConnection: track event" short-title: track slug: Web/API/RTCPeerConnection/track_event page-type: web-api-event browser-compat: api.RTCPeerConnection.track_event --- {{APIRef("WebRTC")}} The **`track`** event is sent to the `ontrack` event handler on {{domxref("RTCPeerConnection")}}s after a new track has been added to an {{domxref("RTCRtpReceiver")}} which is part of the connection. By the time this event is delivered, the new track has been fully added to the peer connection. See [Track event types](/en-US/docs/Web/API/RTCTrackEvent#track_event_types) for details. This event is not cancellable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("track", (event) => {}); ontrack = (event) => {}; ``` ## Event type An {{domxref("RTCTrackEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("RTCTrackEvent")}} ## Event properties _Since `RTCTrackEvent` is based on {{domxref("Event")}}, its properties are also available._ - {{domxref("RTCTrackEvent.receiver", "receiver")}} {{ReadOnlyInline}} - : The {{domxref("RTCRtpReceiver")}} used by the track that's been added to the `RTCPeerConnection`. - {{domxref("RTCTrackEvent.streams", "streams")}} {{ReadOnlyInline}} {{optional_inline}} - : An array of {{domxref("MediaStream")}} objects, each representing one of the media streams to which the added {{domxref("RTCTrackEvent.track", "track")}} belongs. By default, the array is empty, indicating a streamless track. - {{domxref("RTCTrackEvent.track", "track")}} {{ReadOnlyInline}} - : The {{domxref("MediaStreamTrack")}} which has been added to the connection. - {{domxref("RTCTrackEvent.transceiver", "transceiver")}} {{ReadOnlyInline}} - : The {{domxref("RTCRtpTransceiver")}} being used by the new track. ## Examples This example shows code that creates a new {{domxref("RTCPeerConnection")}}, then adds a new `track` event handler. ```js pc = new RTCPeerConnection({ iceServers: [ { urls: "turn:fake.turnserver.url", username: "someusername", credential: "somepassword", }, ], }); pc.addEventListener( "track", (e) => { videoElement.srcObject = e.streams[0]; hangupButton.disabled = false; }, false, ); ``` The event handler assigns the new track's first stream to an existing {{HTMLElement("video")}} element, identified using the variable `videoElement`. You can also assign the event handler function to the `ontrack` property, rather than use {{domxref("EventTarget.addEventListener", "addEventListener()")}}. ```js pc.ontrack = (e) => { videoElement.srcObject = e.streams[0]; hangupButton.disabled = false; return false; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/addtrack/index.md
--- title: "RTCPeerConnection: addTrack() method" short-title: addTrack() slug: Web/API/RTCPeerConnection/addTrack page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.addTrack --- {{APIRef("WebRTC")}} The {{domxref("RTCPeerConnection")}} method **`addTrack()`** adds a new media track to the set of tracks which will be transmitted to the other peer. > **Note:** Adding a track to a connection triggers renegotiation by firing a {{DOMxRef("RTCPeerConnection/negotiationneeded_event", "negotiationneeded")}} event. > See [Starting negotiation](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling#starting_negotiation) for details. ## Syntax ```js-nolint addTrack(track) addTrack(track, stream1) addTrack(track, stream1, stream2) addTrack(track, stream1, stream2, /* …, */ streamN) ``` ### Parameters - `track` - : A {{domxref("MediaStreamTrack")}} object representing the media track to add to the peer connection. - `stream1`, …, `streamN` {{optional_inline}} - : One or more local {{domxref("MediaStream")}} objects to which the track should be added. The specified `track` doesn't necessarily have to already be part of any of the specified `stream`s. Instead, the `stream`s are a way to group tracks together on the receiving end of the connection, making sure they are synchronized. Any tracks that are added to the same stream on the local end of the connection will be on the same stream on the remote end. ### Return value The {{domxref("RTCRtpSender")}} object which will be used to transmit the media data. > **Note:** Every `RTCRtpSender` is paired with an {{domxref("RTCRtpReceiver")}} to make up an {{domxref("RTCRtpTransceiver")}}. > The associated receiver is muted (indicating that it is not able to deliver packets) until and unless one or more streams are added to the receiver by the remote peer. ### Exceptions - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if the specified track (or all of its underlying streams) is already part of the {{domxref("RTCPeerConnection")}}. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("RTCPeerConnection")}} is closed. ## Usage notes ### Adding tracks to multiple streams After the `track` parameter, you can optionally specify one or more {{domxref("MediaStream")}} objects to add the track to. Only tracks are sent from one peer to another, not streams. Since streams are specific to each peer, specifying one or more streams means the other peer will create a corresponding stream (or streams) automatically on the other end of the connection, and will then automatically add the received track to those streams. #### Streamless tracks If no streams are specified, then the track is **streamless**. This is perfectly acceptable, although it will be up to the remote peer to decide what stream to insert the track into, if any. This is a very common way to use `addTrack()` when building many types of simple applications, where only one stream is needed. For example, if all you're sharing with the remote peer is a single stream with an audio track and a video track, you don't need to deal with managing what track is in what stream, so you might as well just let the transceiver handle it for you. Here's an example showing a function that uses {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track: ```js async function openCall(pc) { const gumStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true, }); for (const track of gumStream.getTracks()) { pc.addTrack(track); } } ``` The result is a set of tracks being sent to the remote peer, with no stream associations. The handler for the {{DOMxRef("RTCPeerConnection/track_event", "track")}} event on the remote peer will be responsible for determining what stream to add each track to, even if that means adding them all to the same stream. The {{domxref("RTCPeerConnection.track_event", "ontrack")}} handler might look like this: ```js let inboundStream = null; pc.ontrack = (ev) => { if (ev.streams && ev.streams[0]) { videoElem.srcObject = ev.streams[0]; } else { if (!inboundStream) { inboundStream = new MediaStream(); videoElem.srcObject = inboundStream; } inboundStream.addTrack(ev.track); } }; ``` Here, the `track` event handler adds the track to the first stream specified by the event, if a stream is specified. Otherwise, the first time `ontrack` is called, a new stream is created and attached to the video element, and then the track is added to the new stream. From then on, new tracks are added to that stream. You could also just create a new stream for each track received: ```js pc.ontrack = (ev) => { if (ev.streams && ev.streams[0]) { videoElem.srcObject = ev.streams[0]; } else { let inboundStream = new MediaStream(ev.track); videoElem.srcObject = inboundStream; } }; ``` #### Associating tracks with specific streams By specifying a stream and allowing {{domxref("RTCPeerConnection")}} to create streams for you, the streams' track associations are automatically managed for you by the WebRTC infrastructure. This includes things like changes to the transceiver's {{domxref("RTCRtpTransceiver.direction", "direction")}} and tracks being halted using {{domxref("RTCPeerConnection.removeTrack", "removeTrack()")}}. For example, consider this function that an application might use to begin streaming a device's camera and microphone input over an {{domxref("RTCPeerConnection")}} to a remote peer: ```js async function openCall(pc) { const gumStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true, }); for (const track of gumStream.getTracks()) { pc.addTrack(track, gumStream); } } ``` The remote peer might then use a {{DOMxRef("RTCPeerConnection/track_event", "track")}} event handler that looks like this: ```js pc.ontrack = ({ streams: [stream] }) => (videoElem.srcObject = stream); ``` This sets the video element's current stream to the one that contains the track that's been added to the connection. ### Reused senders This method returns a new `RTCRtpSender` or an existing instance for reuse. An `RTCRtpSender` instance is only compatible for reuse if it meets the following criteria: - There is no track already associated with the sender. - The {{domxref("RTCRtpTransceiver")}} associated with the sender has a {{domxref("RTCRtpReceiver")}} whose {{domxref("RTCRtpReceiver.track", "track")}} property specifies a {{domxref("MediaStreamTrack")}} whose {{domxref("MediaStreamTrack.kind", "kind")}} is the same as the `kind` of the `track` parameter specified when calling `RTCPeerConnection.addTrack()`. This ensures that a transceiver only handles audio or video and never both. - The {{domxref("RTCRtpTransceiver.currentDirection")}} property is not `"stopped"`. - The `RTCRtpSender` being considered has never been used to send data. If the transceiver's {{domxref("RTCRtpTransceiver.currentDirection", "currentDirection")}} has ever been `"sendrecv"` or `"sendonly"`, the sender can't be reused. If all of those criteria are met, the sender gets reused, which results in these changes occurring to the existing `RTCRtpSender` and its `RTCRtpTransceiver`: - The `RTCRtpSender`'s {{domxref("RTCRtpSender.track", "track")}} is set to the specified track. - The sender's set of associated streams is set to the list of streams passed into this method, `stream...`. - The associated {{domxref("RTCRtpTransceiver")}} has its `currentDirection` updated to indicate that it is sending; if its current value is `"recvonly"`, it becomes `"sendrecv"`, and if its current value is `"inactive"`, it becomes `"sendonly"`. ### New senders If no existing sender exists that can be reused, a new one is created. This also results in the creation of the associated objects that must exist. The process of creating a new sender results in these changes: - The new `RTCRtpSender` is created with the specified `track` and set of `stream`(s). - A new {{domxref("RTCRtpReceiver")}} is created with a _new_ {{domxref("MediaStreamTrack")}} as its {{domxref("RTCRtpReceiver.track", "track")}} property (not the track specified as a parameter when calling `addTrack()`). This track's {{domxref("MediaStreamTrack.kind", "kind")}} is set to match the `kind` of the track provided as an input parameter. - A new {{domxref("RTCRtpTransceiver")}} is created and associated with the new sender and receiver. - The new transceiver's {{domxref("RTCRtpTransceiver.direction", "direction")}} is set to `"sendrecv"`. - The new transceiver is added to the `RTCPeerConnection`'s set of transceivers. ## Examples This example is drawn from the code presented in the article [Signaling and video calling](/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling) and its corresponding sample code. It comes from the `handleVideoOfferMsg()` method there, which is called when an offer message is received from the remote peer. ```js const mediaConstraints = { audio: true, // We want an audio track video: true, // And we want a video track }; const desc = new RTCSessionDescription(sdp); pc.setRemoteDescription(desc) .then(() => navigator.mediaDevices.getUserMedia(mediaConstraints)) .then((stream) => { previewElement.srcObject = stream; stream.getTracks().forEach((track) => pc.addTrack(track, stream)); }); ``` This code takes SDP which has been received from the remote peer and constructs a new {{domxref("RTCSessionDescription")}} to pass into {{domxref("RTCPeerConnection.setRemoteDescription", "setRemoteDescription()")}}. Once that succeeds, it uses {{domxref("MediaDevices.getUserMedia()")}} to obtain access to the local webcam and microphone. If that succeeds, the resulting stream is assigned as the source for a {{HTMLElement("video")}} element which is referenced by the variable `previewElement`. The final step is to begin sending the local video across the peer connection to the caller. This is done by adding each track in the stream by iterating over the list returned by {{domxref("MediaStream.getTracks()")}} and passing them to `addTrack()` along with the `stream` which they're a component of. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - [Introduction to the Real-time Transport Protocol (RTP)](/en-US/docs/Web/API/WebRTC_API/Intro_to_RTP) - {{DOMxRef("RTCPeerConnection/track_event", "track")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/createdatachannel/index.md
--- title: "RTCPeerConnection: createDataChannel() method" short-title: createDataChannel() slug: Web/API/RTCPeerConnection/createDataChannel page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.createDataChannel --- {{APIRef("WebRTC")}} The **`createDataChannel()`** method on the {{domxref("RTCPeerConnection")}} interface creates a new channel linked with the remote peer, over which any kind of data may be transmitted. This can be useful for back-channel content, such as images, file transfer, text chat, game update packets, and so forth. If the new data channel is the first one added to the connection, renegotiation is started by delivering a {{DOMxRef("RTCPeerConnection/negotiationneeded_event", "negotiationneeded")}} event. ## Syntax ```js-nolint createDataChannel(label) createDataChannel(label, options) ``` ### Parameters - `label` - : A human-readable name for the channel. This string may not be longer than 65,535 bytes. - `options` {{optional_inline}} - : An object providing configuration options for the data channel. It can contain the following fields: - `ordered` {{optional_inline}} - : Indicates whether or not messages sent on the {{domxref("RTCDataChannel")}} are required to arrive at their destination in the same order in which they were sent (`true`), or if they're allowed to arrive out-of-order (`false`). **Default: `true`.** - `maxPacketLifeTime` {{optional_inline}} - : The maximum number of milliseconds that attempts to transfer a message may take in unreliable mode. While this value is a 16-bit unsigned number, each user agent may clamp it to whatever maximum it deems appropriate. **Default: `null`.** - `maxRetransmits` {{optional_inline}} - : The maximum number of times the user agent should attempt to retransmit a message which fails the first time in unreliable mode. While this value is a 16-bit unsigned number, each user agent may clamp it to whatever maximum it deems appropriate. **Default: `null`.** - `protocol` {{optional_inline}} - : The name of the sub-protocol being used on the {{domxref("RTCDataChannel")}}, if any; otherwise, the empty string (`""`). **Default: empty string (`""`).** This string may not be longer than 65,535 _bytes_. - `negotiated` {{optional_inline}} - : By default (`false`), data channels are negotiated in-band, where one side calls `createDataChannel`, and the other side listens to the {{domxref("RTCDataChannelEvent")}} event using the {{DOMxRef("RTCPeerConnection.datachannel_event", "ondatachannel")}} event handler. Alternatively (`true`), they can be negotiated out of-band, where both sides call `createDataChannel` with an agreed-upon ID. **Default: `false`.** - `id` {{optional_inline}} - : A 16-bit numeric ID for the channel; permitted values are 0 to 65534. If you don't include this option, the user agent will select an ID for you. > **Note:** These options represent the script-settable subset of the properties on the > {{domxref("RTCDataChannel")}} interface. ### Return value A new {{domxref("RTCDataChannel")}} object with the specified `label`, configured using the options specified by `options` if that parameter is included; otherwise, the defaults listed above are established. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("RTCPeerConnection")}} is closed. - {{jsxref("TypeError")}} - : Thrown in the following situations: - The label and/or protocol string is too long; these cannot be longer than 65,535 bytes (bytes, rather than characters). - The `id` is 65535. While this is a valid unsigned 16-bit value, it's not a permitted value for `id`. - `SyntaxError` {{domxref("DOMException")}} - : Thrown if values were specified for both the `maxPacketLifeTime` and `maxRetransmits` options. You may specify a non-`null` value for only one of these. - `ResourceInUse` {{domxref("DOMException")}} - : Thrown if an `id` was specified, but another {{domxref("RTCDataChannel")}} is already using the same value. - `OperationError` {{domxref("DOMException")}} - : Thrown if either the specified `id` is already in use, or if no `id` was specified, the WebRTC layer was unable to automatically generate an ID because all IDs are in use. ## Examples This example shows how to create a data channel and set up handlers for the {{DOMxRef("RTCDataChannel/open_event", "open")}} and {{DOMxRef("RTCDataChannel/message_event", "message")}} events to send and receive messages on it (For brevity, the example assumes onnegotiationneeded is set up). ```js // Offerer side const pc = new RTCPeerConnection(options); const channel = pc.createDataChannel("chat"); channel.onopen = (event) => { channel.send("Hi you!"); }; channel.onmessage = (event) => { console.log(event.data); }; ``` ```js // Answerer side const pc = new RTCPeerConnection(options); pc.ondatachannel = (event) => { const channel = event.channel; channel.onopen = (event) => { channel.send("Hi back!"); }; channel.onmessage = (event) => { console.log(event.data); }; }; ``` Alternatively, more symmetrical out-of-band negotiation can be used, using an agreed-upon id (0 here): ```js // Both sides const pc = new RTCPeerConnection(options); const channel = pc.createDataChannel("chat", { negotiated: true, id: 0 }); channel.onopen = (event) => { channel.send("Hi!"); }; channel.onmessage = (event) => { console.log(event.data); }; ``` For a more thorough example showing how the connection and channel are established, see [A simple RTCDataChannel sample](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("RTCDataChannel")}} - [A simple RTCDataChannel sample](/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample) - {{domxref("RTCPeerConnection")}}
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/setidentityprovider/index.md
--- title: "RTCPeerConnection: setIdentityProvider() method" short-title: setIdentityProvider() slug: Web/API/RTCPeerConnection/setIdentityProvider page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.setIdentityProvider --- {{APIRef("WebRTC")}} The **`RTCPeerConnection.setIdentityProvider()`** method sets the Identity Provider (IdP) to the triplet given in parameter: its name, the protocol used to communicate with it (optional) and an optional username. The IdP will be used only when an assertion is needed. If the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} is set to `"closed"`, an `InvalidStateError` is raised. ## Syntax ```js-nolint setIdentityProvider(domainname) setIdentityProvider(domainname, protocol) setIdentityProvider(domainname, protocol, username) ``` ### Parameters - `domainname` - : A string representing the domain name where the IdP is. - `protocol` {{optional_Inline}} - : A string representing the protocol used to communicate with the IdP. It defaults to `"default"` and is used to determine the URL where the IdP is listening. - `username` {{optional_Inline}} - : A string representing the username associated with the IdP. ### Return value None ({{jsxref("undefined")}}). ## Example ```js const pc = new RTCPeerConnection(); pc.setIdentityAssertion("developer.mozilla.org"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/removetrack/index.md
--- title: "RTCPeerConnection: removeTrack() method" short-title: removeTrack() slug: Web/API/RTCPeerConnection/removeTrack page-type: web-api-instance-method browser-compat: api.RTCPeerConnection.removeTrack --- {{APIRef("WebRTC")}} The **`RTCPeerConnection.removeTrack()`** method tells the local end of the connection to stop sending media from the specified track, without actually removing the corresponding {{domxref("RTCRtpSender")}} from the list of senders as reported by {{domxref("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 ({{domxref("RTCPeerConnection.signalingState", "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 {{DOMxRef("RTCPeerConnection/negotiationneeded_event", "negotiationneeded")}} event is sent to the {{domxref("RTCPeerConnection")}} to let the local end know this negotiation must occur. ## Syntax ```js-nolint removeTrack(sender) ``` ### Parameters - `sender` - : A {{domxref("RTCRtpSender")}} specifying the sender to remove from the connection. ### Return value `undefined`. ### Exceptions - `InvalidStateError` {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcpeerconnection
data/mdn-content/files/en-us/web/api/rtcpeerconnection/signalingstatechange_event/index.md
--- title: "RTCPeerConnection: signalingstatechange event" short-title: signalingstatechange slug: Web/API/RTCPeerConnection/signalingstatechange_event page-type: web-api-event browser-compat: api.RTCPeerConnection.signalingstatechange_event --- {{APIRef("WebRTC")}} A **`signalingstatechange`** event is sent to an {{domxref("RTCPeerConnection")}} to notify it that its signaling state, as indicated by the {{domxref("RTCPeerConnection.signalingState", "signalingState")}} property, has changed. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("signalingstatechange", (event) => {}); onsignalingstatechange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples Given an {{domxref("RTCPeerConnection")}}, `pc`, and an `updateStatus()` function that presents status information to the user, this code sets up an event handler to let the user know when the ICE negotiation process finishes up. ```js pc.addEventListener( "signalingstatechange", (ev) => { switch (pc.signalingState) { case "stable": updateStatus("ICE negotiation complete"); break; } }, false, ); ``` Using `onsignalingstatechange`, it looks like this: ```js pc.onsignalingstatechange = (ev) => { switch (pc.signalingState) { case "stable": updateStatus("ICE negotiation complete"); break; } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCPeerConnection.signalingState")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/canmakepaymentevent/index.md
--- title: CanMakePaymentEvent slug: Web/API/CanMakePaymentEvent page-type: web-api-interface status: - experimental browser-compat: api.CanMakePaymentEvent --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}} The **`CanMakePaymentEvent`** interface of the {{domxref("Payment Handler API", "", "", "nocode")}} is the event object for the {{domxref("ServiceWorkerGlobalScope.canmakepayment_event", "canmakepayment")}} event, fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls {{domxref("PaymentRequest.PaymentRequest", "new PaymentRequest()")}}. {{InheritanceDiagram}} ## Constructor - {{domxref("CanMakePaymentEvent.CanMakePaymentEvent", "CanMakePaymentEvent()")}} {{Experimental_Inline}} - : Creates a new `CanMakePaymentEvent` object instance. ## Instance methods - {{domxref("CanMakePaymentEvent.respondWith", "respondWith()")}} {{Experimental_Inline}} - : Enables the service worker to respond appropriately to signal whether it is ready to handle payments. ## Examples ```js self.addEventListener("canmakepayment", (e) => { e.respondWith( new Promise((resolve, reject) => { someAppSpecificLogic() .then((result) => { resolve(result); }) .catch((error) => { reject(error); }); }), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} - [Web-based payment apps overview](https://web.dev/articles/web-based-payment-apps-overview) - [Setting up a payment method](https://web.dev/articles/setting-up-a-payment-method) - [Life of a payment transaction](https://web.dev/articles/life-of-a-payment-transaction) - [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API) - [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
0
data/mdn-content/files/en-us/web/api/canmakepaymentevent
data/mdn-content/files/en-us/web/api/canmakepaymentevent/canmakepaymentevent/index.md
--- title: "CanMakePaymentEvent: CanMakePaymentEvent() constructor" short-title: CanMakePaymentEvent() slug: Web/API/CanMakePaymentEvent/CanMakePaymentEvent page-type: web-api-constructor status: - experimental browser-compat: api.CanMakePaymentEvent.CanMakePaymentEvent --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}} The **`CanMakePaymentEvent()`** constructor creates a new {{domxref("CanMakePaymentEvent")}} object instance. ## Syntax ```js-nolint new CanMakePaymentEvent(type) ``` ### Parameters - `type` - : A string representing the type of event. In the case of `CanMakePaymentEvent` this is always `canmakepayment`. ## Examples A developer would not use this constructor manually. A new `CanMakePaymentEvent` object is constructed when a handler is invoked as a result of the {{domxref("ServiceWorkerGlobalScope.canmakepayment_event", "canmakepayment")}} event firing. ```js self.addEventListener("canmakepayment", (e) => { e.respondWith( new Promise((resolve, reject) => { someAppSpecificLogic() .then((result) => { resolve(result); }) .catch((error) => { reject(error); }); }), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} - [Web-based payment apps overview](https://web.dev/articles/web-based-payment-apps-overview) - [Setting up a payment method](https://web.dev/articles/setting-up-a-payment-method) - [Life of a payment transaction](https://web.dev/articles/life-of-a-payment-transaction) - [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API) - [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
0
data/mdn-content/files/en-us/web/api/canmakepaymentevent
data/mdn-content/files/en-us/web/api/canmakepaymentevent/respondwith/index.md
--- title: "CanMakePaymentEvent: respondWith() method" short-title: respondWith() slug: Web/API/CanMakePaymentEvent/respondWith page-type: web-api-instance-method status: - experimental browser-compat: api.CanMakePaymentEvent.respondWith --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}} The **`respondWith()`** method of the {{domxref("CanMakePaymentEvent")}} interface enables the service worker to respond appropriately to signal whether it is ready to handle payments. ## Syntax ```js-nolint respondWith(response) ``` ### Parameters - `response` - : A {{jsxref("Promise")}} that resolves with a boolean value to signal that it is ready to handle a payment request: (`true`), or not (`false`). ### Return value None (`undefined`). ## Examples ```js self.addEventListener("canmakepayment", (e) => { e.respondWith( new Promise((resolve, reject) => { someAppSpecificLogic() .then((result) => { resolve(result); }) .catch((error) => { reject(error); }); }), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Payment Handler API", "Payment Handler API", "", "nocode")}} - [Web-based payment apps overview](https://web.dev/articles/web-based-payment-apps-overview) - [Setting up a payment method](https://web.dev/articles/setting-up-a-payment-method) - [Life of a payment transaction](https://web.dev/articles/life-of-a-payment-transaction) - [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API) - [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/performanceentry/index.md
--- title: PerformanceEntry slug: Web/API/PerformanceEntry page-type: web-api-interface browser-compat: api.PerformanceEntry --- {{APIRef("Performance API")}} {{AvailableInWorkers}} The **`PerformanceEntry`** object encapsulates a single performance metric that is part of the browser's performance timeline. The Performance API offers built-in metrics which are specialized subclasses of `PerformanceEntry`. This includes entries for resource loading, event timing, {{Glossary("first input delay")}} (FID), and more. A performance entry can also be created by calling the {{domxref("Performance.mark()")}} or {{domxref("Performance.measure()")}} methods at an explicit point in an application. This allows you to add your own metrics to the performance timeline. The `PerformanceEntry` instances will always be one of the following subclasses: - {{domxref("LargestContentfulPaint")}} - {{domxref("LayoutShift")}} - {{domxref("PerformanceEventTiming")}} - {{domxref("PerformanceLongTaskTiming")}} - {{domxref("PerformanceMark")}} - {{domxref("PerformanceMeasure")}} - {{domxref("PerformanceNavigationTiming")}} - {{domxref("PerformancePaintTiming")}} - {{domxref("PerformanceResourceTiming")}} - {{domxref("PerformanceServerTiming")}} - {{domxref("TaskAttributionTiming")}} - {{domxref("VisibilityStateEntry")}} ## Instance properties - {{domxref("PerformanceEntry.name")}} {{ReadOnlyInline}} - : A string representing the name for a performance entry. The value depends on the subtype. - {{domxref("PerformanceEntry.entryType")}} {{ReadOnlyInline}} - : A string representing the type of performance metric. For example, "`mark`" when {{domxref("PerformanceMark")}} is used. - {{domxref("PerformanceEntry.startTime")}} {{ReadOnlyInline}} - : A {{domxref("DOMHighResTimeStamp")}} representing the starting time for the performance metric. - {{domxref("PerformanceEntry.duration")}} {{ReadOnlyInline}} - : A {{domxref("DOMHighResTimeStamp")}} representing the duration of the performance entry. ## Instance methods - {{domxref("PerformanceEntry.toJSON","PerformanceEntry.toJSON()")}} - : Returns a JSON representation of the `PerformanceEntry` object. ## Example ### Working with performance entries The following example creates `PerformanceEntry` objects that are of the types {{domxref("PerformanceMark")}} and {{domxref("PerformanceMeasure")}}. The `PerformanceMark` and `PerformanceMeasure` subclasses inherit the `duration`, `entryType`, `name`, and `startTime` properties from `PerformanceEntry` and set them to their appropriate values. ```js // Place at a location in the code that starts login performance.mark("login-started"); // Place at a location in the code that finishes login performance.mark("login-finished"); // Measure login duration performance.measure("login-duration", "login-started", "login-finished"); function perfObserver(list, observer) { list.getEntries().forEach((entry) => { if (entry.entryType === "mark") { console.log(`${entry.name}'s startTime: ${entry.startTime}`); } if (entry.entryType === "measure") { console.log(`${entry.name}'s duration: ${entry.duration}`); } }); } const observer = new PerformanceObserver(perfObserver); observer.observe({ entryTypes: ["measure", "mark"] }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceentry
data/mdn-content/files/en-us/web/api/performanceentry/name/index.md
--- title: "PerformanceEntry: name property" short-title: name slug: Web/API/PerformanceEntry/name page-type: web-api-instance-property browser-compat: api.PerformanceEntry.name --- {{APIRef("Performance API")}} {{AvailableInWorkers}} The read-only **`name`** property of the {{domxref("PerformanceEntry")}} interface is a string representing the name for a performance entry. It acts as an identifier, but it does not have to be unique. The value depends on the subclass. ## Value A string. The value depends on the subclass of the `PerformanceEntry` object as shown by the table below. <table class="no-markdown"> <thead> <tr> <th scope="col">Subclass</th> <th scope="col">Value</th> </tr> </thead> <tbody> <tr> <td>{{domxref('LargestContentfulPaint')}}</td> <td>Always returns an empty string.</td> </tr> <tr> <td>{{domxref('LayoutShift')}}</td> <td>Always returns <code>"layout-shift"</code>.</td> </tr> <tr> <td>{{domxref('PerformanceElementTiming')}}</td> <td>One of the following strings: <ul> <li><code>"image-paint"</code></li> <li><code>"text-paint"</code></li> </ul> </td> </tr> <tr> <td>{{domxref('PerformanceEventTiming')}}</td> <td>The associated event's type.</td> </tr> <tr> <td>{{domxref('PerformanceLongTaskTiming')}}</td> <td>One of the following strings: <ul> <li><code>"cross-origin-ancestor"</code></li> <li><code>"cross-origin-descendant"</code></li> <li><code>"cross-origin-unreachable"</code></li> <li><code>"multiple-contexts"</code></li> <li><code>"same-origin-ancestor"</code></li> <li><code>"same-origin-descendant"</code></li> <li><code>"same-origin"</code></li> <li><code>"self"</code></li> <li><code>"unknown"</code></li> </ul> </td> </tr> <tr> <td>{{domxref('PerformanceMark')}}</td> <td> The name used when the mark was created by calling {{domxref("Performance.mark","performance.mark()")}}. </td> </tr> <tr> <td>{{domxref('PerformanceMeasure')}}</td> <td> The name used when the measure was created by calling {{domxref("Performance.measure","performance.measure()")}}. </td> </tr> <tr> <td>{{domxref('PerformanceNavigationTiming')}}</td> <td>The resolved URL of the requested resource. This value doesn't change even if the request is redirected.</td> </tr> <tr> <td>{{domxref('PerformancePaintTiming')}}</td> <td>One of the following strings: <ul> <li><code>"first-paint"</code></li> <li><code>"first-contentful-paint"</code></li> </ul> </td> </tr> <tr> <td>{{domxref('PerformanceResourceTiming')}}</td> <td>The resolved URL of the requested resource. This value doesn't change even if the request is redirected.</td> </tr> <tr> <td>{{domxref('TaskAttributionTiming')}}</td> <td>Always returns <code>"unknown"</code>.</td> </tr> <tr> <td>{{domxref('VisibilityStateEntry')}}</td> <td>One of the following strings: <ul> <li><code>"visible"</code></li> <li><code>"hidden"</code></li> </ul> </td> </tr> </tbody> </table> ## Examples ### Filtering performance entries by name When the `PerformanceEntry` is a {{domxref('PerformanceResourceTiming')}} object, the `name` property refers to the resolved URL of the requested resource. In this case, the `name` property can be useful to filter out specific resources, for example all SVG images. ```js // Log durations of SVG resources performance.getEntriesByType("resource").forEach((entry) => { if (entry.name.endsWith(".svg")) { console.log(`${entry.name}'s duration: ${entry.duration}`); } }); ``` ### Getting performance entries by name Both {{domxref("Performance")}} and {{domxref("PerformanceObserver")}} provide methods that allow you to get performance entries by name directly. You don't necessarily need the `name` property for that, instead you might use {{domxref("Performance.getEntriesByName()")}} or {{domxref("PerformanceObserverEntryList.getEntriesByName()")}}. ```js // Log all marks named "debug-marks" at this point in time const debugMarks = performance.getEntriesByName("debug-mark", "mark"); debugMarks.forEach((entry) => { console.log(`${entry.name}'s startTime: ${entry.startTime}`); }); // PerformanceObserver version // Log all marks named "debug-marks" when they happen function perfObserver(list, observer) { list.getEntriesByName("debug-mark", "mark").forEach((entry) => { console.log(`${entry.name}'s startTime: ${entry.startTime}`); }); } const observer = new PerformanceObserver(perfObserver); observer.observe({ entryTypes: ["measure", "mark"] }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.getEntriesByName()")}} - {{domxref("PerformanceObserverEntryList.getEntriesByName()")}}
0
data/mdn-content/files/en-us/web/api/performanceentry
data/mdn-content/files/en-us/web/api/performanceentry/starttime/index.md
--- title: "PerformanceEntry: startTime property" short-title: startTime slug: Web/API/PerformanceEntry/startTime page-type: web-api-instance-property browser-compat: api.PerformanceEntry.startTime --- {{APIRef("Performance API")}} The read-only **`startTime`** property returns the first {{domxref("DOMHighResTimeStamp","timestamp", "", "no-code")}} recorded for this {{domxref("PerformanceEntry","performance entry", "", "no-code")}}. The meaning of this property depends on the value of this entry's {{domxref("PerformanceEntry.entryType", "entryType")}}. ## Value A {{domxref("DOMHighResTimeStamp")}} representing the first timestamp when the {{domxref("PerformanceEntry","performance entry")}} was created. The meaning of this property depends on the value of this performance entry's {{domxref("PerformanceEntry.entryType","entryType")}}: - `element` - : Either the value of this entry's {{domxref("PerformanceElementTiming.renderTime", "renderTime")}} if it is not `0`, otherwise the value of this entry's {{domxref("PerformanceElementTiming.loadTime", "loadTime")}}. - `event` - : The time the event was created, i.e. the event's [`timeStamp`](/en-US/docs/Web/API/Event/timeStamp) property. - `first-input` - : The time the first input event was created, i.e. that event's [`timeStamp`](/en-US/docs/Web/API/Event/timeStamp). - `largest-contentful-paint` - : The value of this entry's {{domxref("LargestContentfulPaint.renderTime", "renderTime")}} if it is not `0`, otherwise the value of this entry's {{domxref("LargestContentfulPaint.loadTime", "loadTime")}}. - `layout-shift` - : The time when the layout shift started. - `longtask` - : The time when the task started. - `mark` - : The time at which the mark was created by a call to {{domxref("Performance.mark","performance.mark()")}}. - `measure` - : The time at which the measure was created by a call to {{domxref("Performance.measure","performance.measure()")}}. - `navigation` - : Always `0`. - `paint` - : The time when the paint occurred. - `resource` - : The value of this entry's {{domxref("PerformanceResourceTiming.fetchStart", "fetchStart")}} property. - `taskattribution` - : Always `0`. - `visibility-state` - : The time when the visibility state change occurred. ## Examples ### Using the startTime property The following example shows the use of the `startTime` property which you can log during performance observation. Note: The {{domxref("performance.mark()")}} method allows you to set your own `startTime`, and the {{domxref("performance.measure()")}} method allows to set the start of the measure. ```js performance.mark("my-mark"); performance.mark("my-other-mark", { startTime: 12.5 }); loginButton.addEventListener("click", (clickEvent) => { performance.measure("login-click", { start: clickEvent.timeStamp }); }); function perfObserver(list, observer) { list.getEntries().forEach((entry) => { if (entry.entryType === "mark") { console.log(`${entry.name}'s startTime: ${entry.startTime}`); } if (entry.entryType === "measure") { console.log(`${entry.name}'s duration: ${entry.duration}`); } }); } const observer = new PerformanceObserver(perfObserver); observer.observe({ entryTypes: ["measure", "mark"] }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceentry
data/mdn-content/files/en-us/web/api/performanceentry/entrytype/index.md
--- title: "PerformanceEntry: entryType property" short-title: entryType slug: Web/API/PerformanceEntry/entryType page-type: web-api-instance-property browser-compat: api.PerformanceEntry.entryType --- {{APIRef("Performance API")}} {{AvailableInWorkers}} The read-only **`entryType`** property returns a string representing the type of performance metric that this entry represents. All supported `entryTypes` are available using the static property {{domxref("PerformanceObserver.supportedEntryTypes_static", "PerformanceObserver.supportedEntryTypes")}}. ## Value A string. The return value depends on the subtype of the `PerformanceEntry` object. Some subtypes have more than one `entryType`. - `element` - : Reports load time of elements. The entry instance will be a {{domxref("PerformanceElementTiming")}} object. - `event` - : Reports event latencies. The entry instance will be a {{domxref("PerformanceEventTiming")}} object. - `first-input` - : Reports the {{Glossary("first input delay")}} (FID). The entry instance will be a {{domxref("PerformanceEventTiming")}} object. - `largest-contentful-paint` - : Reports the largest paint an element triggered on screen. The entry instance will be a {{domxref("LargestContentfulPaint")}} object. - `layout-shift` - : Reports layout stability of web pages based on movements of the elements on the page. The entry instance will be a {{domxref("LayoutShift")}} object. - `longtask` - : Reports instances of long tasks. The entry instance will be a {{domxref("PerformanceLongTaskTiming")}} object. - `mark` - : Reports your own custom performance markers. The entry instance will be a {{domxref("PerformanceMark")}} object. - `measure` - : Reports your own custom performance measures. The entry instance will be a {{domxref("PerformanceMeasure")}} object. - `navigation` - : Reports document navigation timing. The entry instance will be a {{domxref("PerformanceNavigationTiming")}} object. - `paint` - : Reports key moments of document rendering (first paint, first contentful paint) during page load. The entry instance will be a {{domxref("PerformancePaintTiming")}} object. - `resource` - : Reports timing information for resources in a document. The entry instance will be a {{domxref("PerformanceResourceTiming")}} object. - `taskattribution` - : Reports the type of work that contributed significantly to the long task. The entry instance will be a {{domxref("TaskAttributionTiming")}} object. - `visibility-state` - : Reports the timing of page visibility state changes, i.e., when a tab changes from the foreground to the background or vice versa. The entry instance will be a {{domxref("VisibilityStateEntry")}} object. ## Examples ### Filtering performance entries by type The `entryType` property can be useful when filtering out specific performance entries. For example, you might want to check all script resources, so you would check for an `entryType` of `"resource"` and an {{domxref("PerformanceResourceTiming.initiatorType", "initiatorType")}} of `"script"`. ```js const scriptResources = performance .getEntries() .filter( (entry) => entry.entryType === "resource" && entry.initiatorType === "script", ); console.log(scriptResources); ``` ### Getting performance entries by type Both, {{domxref("Performance")}} and {{domxref("PerformanceObserver")}}, provide methods that allow you to get performance entries by type directly. You don't necessarily need the `entryType` property for that, instead you might use {{domxref("Performance.getEntriesByType()")}} or {{domxref("PerformanceObserverEntryList.getEntriesByType()")}}. Also, when observing with a {{domxref("PerformanceObserver")}}, the {{domxref("PerformanceObserver.observe", "observe()")}} method takes an array of `entryTypes` in its options object where you can decide which entry types to observe. ```js // Log all resource entries at this point const resources = performance.getEntriesByType("resource"); resources.forEach((entry) => { console.log(`${entry.name}'s duration: ${entry.duration}`); }); // PerformanceObserver version // Log all resource entries when they are available function perfObserver(list, observer) { list.getEntriesByType("resource").forEach((entry) => { console.log(`${entry.name}'s duration: ${entry.duration}`); }); } const observer = new PerformanceObserver(perfObserver); observer.observe({ entryTypes: ["resource", "navigation"] }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("PerformanceObserver.supportedEntryTypes_static", "PerformanceObserver.supportedEntryTypes")}} - {{domxref("Performance.getEntriesByType()")}} - {{domxref("PerformanceObserverEntryList.getEntriesByType()")}}
0
data/mdn-content/files/en-us/web/api/performanceentry
data/mdn-content/files/en-us/web/api/performanceentry/duration/index.md
--- title: "PerformanceEntry: duration property" short-title: duration slug: Web/API/PerformanceEntry/duration page-type: web-api-instance-property browser-compat: api.PerformanceEntry.duration --- {{APIRef("Performance API")}} The read-only **`duration`** property returns a {{domxref("DOMHighResTimeStamp","timestamp", "", "no-code")}} that is the duration of the {{domxref("PerformanceEntry","performance entry", "", "no-code")}}. The meaning of this property depends on the value of this entry's {{domxref("PerformanceEntry.entryType", "entryType")}}. ## Value A {{domxref("DOMHighResTimeStamp")}} representing the duration of the {{domxref("PerformanceEntry","performance entry", "", "no-code")}}. If the duration concept doesn't apply for a particular performance metric, a duration of `0` is returned. The meaning of this property depends on the value of this performance entry's {{domxref("PerformanceEntry.entryType","entryType")}}: - `event` - : The time from the event's `startTime` to the next rendering paint (rounded to the nearest 8ms). - `first-input` - : The time from the first input event's `startTime` to the next rendering paint (rounded to the nearest 8ms). - `longtask` - : The elapsed time between the start and end of task, with a 1ms granularity. - `measure` - : The duration of the measure. - `navigation` - : The difference between the entry's {{domxref("PerformanceNavigationTiming.loadEventEnd", "loadEventEnd")}} and {{domxref("PerformanceEntry.startTime", "startTime")}} properties. - `resource` - : The entry's {{domxref("PerformanceResourceTiming/responseEnd", "responseEnd")}} value minus the entry's {{domxref("PerformanceEntry.startTime","startTime")}} value. For the following entry types, `duration` is not applicable, and in this case the value is always `0`: - `element` - `largest-contentful-paint` - `layout-shift` - `mark` - `paint` - `taskattribution` - `visibility-state` ## Examples ### Using the duration property The following example logs all observed performance entries with a `duration` larger than `0`. ```js function perfObserver(list, observer) { list.getEntries().forEach((entry) => { if (entry.duration > 0) { console.log(`${entry.name}'s duration: ${entry.duration}`); } }); } const observer = new PerformanceObserver(perfObserver); observer.observe({ entryTypes: ["measure", "mark", "resource"] }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceentry
data/mdn-content/files/en-us/web/api/performanceentry/tojson/index.md
--- title: "PerformanceEntry: toJSON() method" short-title: toJSON() slug: Web/API/PerformanceEntry/toJSON page-type: web-api-instance-method browser-compat: api.PerformanceEntry.toJSON --- {{APIRef("Performance API")}} The **`toJSON()`** method is a {{Glossary("Serialization","serializer")}}; it returns a JSON representation of the {{domxref("PerformanceEntry")}} object. ## Syntax ```js-nolint toJSON() ``` ### Parameters None. ### Return value A {{jsxref("JSON")}} object that is the serialization of the {{domxref("PerformanceEntry")}} object. ## Examples ### Using the toJSON method In this example, calling `entry.toJSON()` returns a JSON representation of the {{domxref("PerformanceMark")}} object. ```js performance.mark("debug-marker", { detail: "debugging-marker-123", }); const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { console.log(entry.toJSON()); }); }); observer.observe({ entryTypes: ["mark"] }); ``` This would log a JSON object like so: ```json { "name": "debug-marker", "entryType": "mark", "startTime": 158361, "duration": 0 } ``` Note that it doesn't contain `PerformanceMark`'s {{domxref("PerformanceMark.detail", "detail")}} property. To get a JSON string, you can use [`JSON.stringify(entry)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) directly; it will call `toJSON()` automatically. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("JSON")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgelement/index.md
--- title: SVGElement slug: Web/API/SVGElement page-type: web-api-interface browser-compat: api.SVGElement --- {{APIRef("SVG")}} All of the SVG DOM interfaces that correspond directly to elements in the SVG language derive from the `SVGElement` interface. {{InheritanceDiagram}} ## Instance properties _Also inherits properties from the {{DOMxRef("Element")}} interface._ - {{DOMxRef("SVGElement.attributeStyleMap")}} {{ReadOnlyInline}} - : A {{DOMxRef("StylePropertyMap")}} representing the declarations of the element's {{SVGAttr("style")}} attribute. - {{DOMxRef("HTMLElement.dataset")}} {{ReadOnlyInline}} - : A {{DOMxRef("DOMStringMap")}} object which provides a list of key/value pairs of named data attributes which correspond to [custom data attributes](/en-US/docs/Learn/HTML/Howto/Use_data_attributes) attached to the element. These can also be defined in SVG using attributes of the form {{SVGAttr("data-*")}}, where `*` is the key name for the pair. This works just like HTML's {{DOMxRef("HTMLElement.dataset")}} property and HTML's [`data-*`](/en-US/docs/Web/HTML/Global_attributes/data-*) global attribute. - {{DOMxRef("SVGElement.className")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : An {{DOMxRef("SVGAnimatedString")}} that reflects the value of the {{SVGAttr("class")}} attribute on the given element, or the empty string if `class` is not present. This attribute is deprecated and may be removed in a future version of this specification. Authors are advised to use {{DOMxRef("Element.classList")}} instead. - {{DOMxRef("SVGElement.nonce")}} - : Returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed. - {{DOMxRef("SVGElement.ownerSVGElement")}} {{ReadOnlyInline}} - : An {{DOMxRef("SVGSVGElement")}} referring to the nearest ancestor {{SVGElement("svg")}} element. `null` if the given element is the outermost `<svg>` element. - {{DOMxRef("SVGElement.style")}} - : A {{DOMxRef("CSSStyleDeclaration")}} representing the declarations of the element's {{SVGAttr("style")}} attribute. - {{DOMxRef("SVGElement.tabIndex")}} - : The position of the element in the tabbing order. - {{DOMxRef("SVGElement.viewportElement")}} {{ReadOnlyInline}} - : The {{DOMxRef("SVGElement")}} which established the current viewport. Often the nearest ancestor {{SVGElement("svg")}} element. `null` if the given element is the outermost `<svg>` element. ## Instance methods _This interface has no methods, but inherits methods from {{DOMxRef("Element")}}._ ## Events Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the equivalent `on...` handler property. - [`abort`](/en-US/docs/Web/API/SVGElement/abort_event) - : Fired when page loading is stopped before an SVG element has been allowed to load completely. - [`error`](/en-US/docs/Web/API/SVGElement/error_event) - : Fired when an SVG element does not load properly or when an error occurs during script execution. - [`load`](/en-US/docs/Web/API/SVGElement/load_event) - : Fires on an `SVGElement` when it is loaded in the browser. - [`resize`](/en-US/docs/Web/API/SVGElement/resize_event) - : Fired when an SVG document is being resized. - [`scroll`](/en-US/docs/Web/API/SVGElement/scroll_event) - : Fired when an SVG document view is being shifted along the X and/or Y axes. - [`unload`](/en-US/docs/Web/API/SVGElement/unload_event) - : Fired when the DOM implementation removes an SVG document from a window or frame. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML [`data-*`](/en-US/docs/Web/HTML/Global_attributes/data-*) attribute - SVG {{SVGAttr("data-*")}} attribute - [Using custom data attributes in HTML](/en-US/docs/Learn/HTML/Howto/Use_data_attributes)
0
data/mdn-content/files/en-us/web/api/svgelement
data/mdn-content/files/en-us/web/api/svgelement/style/index.md
--- title: "SVGElement: style property" short-title: style slug: Web/API/SVGElement/style page-type: web-api-instance-property browser-compat: api.SVGElement.style --- {{APIRef("CSSOM")}} The read-only **`style`** property of the {{domxref("SVGElement")}} returns the _inline_ style of an element in the form of a live {{domxref("CSSStyleDeclaration")}} object that contains a list of all styles properties for that element with values assigned only for the attributes that are defined in the element's inline [`style`](/en-US/docs/Web/HTML/Global_attributes/style) attribute. Shorthand properties are expanded. If you set `style="border-top: 1px solid black"`, the longhand properties ({{cssxref("border-top-color")}}, {{cssxref("border-top-style")}}, and {{cssxref("border-top-width")}}) are set instead. This property is read-only, meaning it is not possible to assign a {{domxref("CSSStyleDeclaration")}} object to it. Nevertheless, it is possible to set an inline style by assigning a _string_ directly to the `style` property. In this case the string is forwarded to {{domxref("CSSStyleDeclaration.cssText")}}. Using `style` in this manner will completely overwrite all inline styles on the element. Therefore, to add specific styles to an element without altering other style values, it is generally preferable to set individual properties on the {{domxref("CSSStyleDeclaration")}} object. For example, you can write `element.style.backgroundColor = "red"`. A style declaration is reset by setting it to `null` or an empty string, e.g., `elt.style.color = null`. > **Note:** CSS property names are converted to JavaScript identifier with these rules: > > - If the property is made of one word, it remains as it is: `height` stays as is (in lowercase). > - If the property is made of several words, separated by dashes, the dashes are removed and it is converted to {{Glossary("camel_case", "camel case")}}: `background-attachment` becomes `backgroundAttachment`. > - The property `float`, being a reserved JavaScript keyword, is converted to `cssFloat`. > > The `style` property has the same priority in the CSS cascade as an inline style declaration set via the `style` attribute. ## Value A live {{domxref("CSSStyleDeclaration")}} object. ## Examples ### Getting style information The following code snippet demonstrates how the `style` attribute is translated into a list of entries in {{domxref("CSSStyleDeclaration")}} : ```html <svg width="50" height="50" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" id="circle" style="fill: red; stroke: black; stroke-width: 2px;" /> </svg> <pre id="out"></pre> ``` ```js const element = document.querySelector("circle"); const out = document.getElementById("out"); const elementStyle = element.style; // We loop through all styles (for…of doesn't work with CSStyleDeclaration) for (const prop in elementStyle) { if (Object.hasOwn(elementStyle, prop)) { out.textContent += `${ elementStyle[prop] } = '${elementStyle.getPropertyValue(elementStyle[prop])}'\n`; } } ``` {{EmbedLiveSample("Getting_style_information", "100", "130")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information) - {{domxref("HTMLElement.style")}}
0
data/mdn-content/files/en-us/web/api/svgelement
data/mdn-content/files/en-us/web/api/svgelement/load_event/index.md
--- title: "SVGElement: load event" short-title: load slug: Web/API/SVGElement/load_event page-type: web-api-event browser-compat: api.SVGElement.load_event --- {{APIRef("SVG")}} The `load` event fires on an `SVGElement` when it is loaded in the browser, e.g. in the DOM in the case of an embedded `<svg>`. It is basically the same as the standard `load` DOM event. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("load", (event) => {}); onload = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js svgElem.addEventListener("load", () => { console.log("SVG loaded."); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/svgelement
data/mdn-content/files/en-us/web/api/svgelement/error_event/index.md
--- title: "SVGElement: error event" short-title: error slug: Web/API/SVGElement/error_event page-type: web-api-event browser-compat: api.SVGElement.error_event --- {{APIRef("SVG")}} The `error` event is fired when an SVG element does not load properly or when an error occurs during script execution. This basically implements the standard `error` DOM event. This event is not cancelable. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("error", (event) => {}); onerror = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js svgElem.addEventListener("error", () => { console.log("SVG not loaded properly."); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/performance/index.md
--- title: Performance slug: Web/API/Performance page-type: web-api-interface browser-compat: api.Performance --- {{APIRef("Performance API")}} The **`Performance`** interface provides access to performance-related information for the current page. An object of this type can be obtained by calling `window.performance` or `self.performance` in workers. Note that Performance entries are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa. See [`self.performance`](/en-US/docs/Web/API/performance_property) for which APIs are available in window and worker contexts. {{InheritanceDiagram}} ## Instance properties _The `Performance` interface doesn't inherit any properties._ - {{domxref("Performance.eventCounts")}} {{ReadOnlyInline}} - : An {{domxref("EventCounts")}} map containing the number of events which have been dispatched per event type. - {{domxref("Performance.navigation")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : A legacy {{domxref("PerformanceNavigation")}} object that provides useful context about the operations included in the times listed in `timing`, including whether the page was a load or a refresh, how many redirections occurred, and so forth. - {{domxref("Performance.timing")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : A legacy {{domxref("PerformanceTiming")}} object containing latency-related performance information. - {{domxref("Performance.memory")}} {{ReadOnlyInline}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : A _non-standard_ extension added in Chrome, this property provides an object with basic memory usage information. _You **should not use** this non-standard API._ - {{domxref("Performance.timeOrigin")}} {{ReadOnlyInline}} - : Returns the high resolution timestamp of the start time of the performance measurement. ## Instance methods _The `Performance` interface doesn't inherit any methods._ - {{domxref("Performance.clearMarks()")}} - : Removes the given _mark_ from the browser's performance entry buffer. - {{domxref("Performance.clearMeasures()")}} - : Removes the given _measure_ from the browser's performance entry buffer. - {{domxref("Performance.clearResourceTimings()")}} - : Removes all {{domxref("PerformanceEntry","performance entries")}} with a {{domxref("PerformanceEntry.entryType","entryType")}} of "`resource`" from the browser's performance data buffer. - {{domxref("Performance.getEntries()")}} - : Returns a list of {{domxref("PerformanceEntry")}} objects based on the given _filter_. - {{domxref("Performance.getEntriesByName()")}} - : Returns a list of {{domxref("PerformanceEntry")}} objects based on the given _name_ and _entry type_. - {{domxref("Performance.getEntriesByType()")}} - : Returns a list of {{domxref("PerformanceEntry")}} objects of the given _entry type_. - {{domxref("Performance.mark()")}} - : Creates a {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's _performance entry buffer_ with the given name. - {{domxref("Performance.measure()")}} - : Creates a named {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer between two specified marks (known as the _start mark_ and _end mark_, respectively). - {{domxref("Performance.measureUserAgentSpecificMemory()")}} {{Experimental_Inline}} - : Estimates the memory usage of a web application including all its iframes and workers. - {{domxref("Performance.now()")}} - : Returns a {{domxref("DOMHighResTimeStamp")}} representing the number of milliseconds elapsed since a reference instant. - {{domxref("Performance.setResourceTimingBufferSize()")}} - : Sets the browser's resource timing buffer size to the specified number of "`resource`" {{domxref("PerformanceEntry.entryType","type")}} {{domxref("PerformanceEntry","performance entry")}} objects. - {{domxref("Performance.toJSON()")}} - : Returns a JSON representation of the `Performance` object. ## Events Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface. - {{DOMxRef("Performance.resourcetimingbufferfull_event", "resourcetimingbufferfull")}} - : Fired when the browser's [resource timing buffer](/en-US/docs/Web/API/Performance/setResourceTimingBufferSize) is full. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/getentries/index.md
--- title: "Performance: getEntries() method" short-title: getEntries() slug: Web/API/Performance/getEntries page-type: web-api-instance-method browser-compat: api.Performance.getEntries --- {{APIRef("Performance API")}} The **`getEntries()`** method returns an array of all {{domxref("PerformanceEntry")}} objects currently present in the performance timeline. If you are only interested in performance entries of certain types or that have certain names, see {{domxref("Performance.getEntriesByType", "getEntriesByType()")}} and {{domxref("Performance.getEntriesByName", "getEntriesByName()")}}. > **Note:** This method does not notify you about new performance entries; you will only get entries that are present in the performance timeline at the time you call this method. > To receive notifications about entries as they become available, use a {{domxref("PerformanceObserver")}}. The following entry types are not supported by this method at all and won't be returned even if entries for these types might exist: - `"element"` ({{domxref("PerformanceElementTiming")}}) - `"event"` ({{domxref("PerformanceEventTiming")}}) - `"largest-contentful-paint"` ({{domxref("LargestContentfulPaint")}}) - `"layout-shift"` ({{domxref("LayoutShift")}}) - `"longtask"` ({{domxref("PerformanceLongTaskTiming")}}) To access entries of these types, you must use a {{domxref("PerformanceObserver")}} instead. ## Syntax ```js-nolint getEntries() ``` ### Parameters None. ### Return value An {{jsxref("Array")}} of {{domxref("PerformanceEntry")}} objects. The items will be in chronological order based on the entries' {{domxref("PerformanceEntry.startTime","startTime")}}. ## Examples ### Logging all performance markers and measures Assuming you created your own {{domxref("PerformanceMark")}} and {{domxref("PerformanceMeasure")}} objects at appropriate places in your code, you might want to log all them to the console like this: ```js // Example markers/measures performance.mark("login-started"); performance.mark("login-finished"); performance.mark("form-sent"); performance.mark("video-loaded"); performance.measure("login-duration", "login-started", "login-finished"); const entries = performance.getEntries(); entries.forEach((entry) => { if (entry.entryType === "mark") { console.log(`${entry.name}'s startTime: ${entry.startTime}`); } if (entry.entryType === "measure") { console.log(`${entry.name}'s duration: ${entry.duration}`); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.getEntriesByType()")}} - {{domxref("Performance.getEntriesByName()")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/timing/index.md
--- title: "Performance: timing property" short-title: timing slug: Web/API/Performance/timing page-type: web-api-instance-property status: - deprecated browser-compat: api.Performance.timing --- {{APIRef("Performance API")}}{{deprecated_header}} The legacy **`Performance.timing`** read-only property returns a {{domxref("PerformanceTiming")}} object containing latency-related performance information. This property is not available in workers. > **Warning:** This property is deprecated in the [Navigation Timing Level 2 specification](https://w3c.github.io/navigation-timing/#obsolete). Please use the {{domxref("PerformanceNavigationTiming")}} > interface instead. ## Value A {{domxref("PerformanceTiming")}} object. ## Specifications This feature is no longer on track to become a standard, as the [Navigation Timing specification](https://w3c.github.io/navigation-timing/#obsolete) has marked it as deprecated. Use the {{domxref("PerformanceNavigationTiming")}} interface instead. ## Browser compatibility {{Compat}} ## See also - The {{domxref("Performance")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/clearresourcetimings/index.md
--- title: "Performance: clearResourceTimings() method" short-title: clearResourceTimings() slug: Web/API/Performance/clearResourceTimings page-type: web-api-instance-method browser-compat: api.Performance.clearResourceTimings --- {{APIRef("Performance API")}} The **`clearResourceTimings()`** method removes all performance entries with an {{domxref("PerformanceEntry.entryType","entryType")}} of "`resource`" from the browser's performance timeline and sets the size of the performance resource data buffer to zero. To set the size of the browser's performance resource data buffer, use the {{domxref("Performance.setResourceTimingBufferSize()")}} method. To get notified when the browser's resource timing buffer is full, listen for the {{domxref("Performance.resourcetimingbufferfull_event", "resourcetimingbufferfull")}} event. ## Syntax ```js-nolint clearResourceTimings() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Clearing the performance resource data buffer To remove all resource performance entries from the buffer, call the `clearResourceTimings()` at an appropriate point in your code or paste it into the console. ```js performance.clearResourceTimings(); performance.getEntriesByType("resource").length; // 0 ``` ### Taking records and emptying performance observers When using {{domxref("PerformanceObserver")}} objects (especially with the `buffered` flag set to `true`), the performance resource buffer might get full quickly. However, instead of clearing the buffer, you can also store the current list of performance entries and empty the performance observer using the {{domxref("PerformanceObserver.takeRecords()")}} method. This works with all kinds of performance entry types, not just "`resource`" entries. ```js function perfObserver(list, observer) { list.getEntries().forEach((entry) => { // do something with the entries }); } const observer = new PerformanceObserver(perfObserver); observer.observe({ type: "resource", buffered: true }); // Store entries and empty performance observer const records = observer.takeRecords(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.setResourceTimingBufferSize()")}} - {{domxref("Performance.resourcetimingbufferfull_event", "resourcetimingbufferfull")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/timeorigin/index.md
--- title: "Performance: timeOrigin property" short-title: timeOrigin slug: Web/API/Performance/timeOrigin page-type: web-api-instance-property browser-compat: api.Performance.timeOrigin --- {{APIRef("Performance API")}} The **`timeOrigin`** read-only property of the {{domxref("Performance")}} interface returns the high resolution timestamp that is used as the baseline for performance-related timestamps. In Window contexts, this value represents the time when navigation has started. In {{domxref("Worker")}} and {{domxref("ServiceWorker")}} contexts, this value represents the time when the worker is run. You can use this property to synchronize the time origins between the contexts (see example below). > **Note:** The value of `performance.timeOrigin` may differ from the value returned by {{jsxref("Date.now()")}} executed at the time origin, because `Date.now()` may have been impacted by system and user clock adjustments, clock skew, etc. The `timeOrigin` property is a [monotonic clock](https://w3c.github.io/hr-time/#dfn-monotonic-clock) which current time never decreases and which isn't subject to these adjustments. ## Value A high resolution timestamp which considered to be the beginning of the current document's lifetime. It's calculated like this: - If the script's {{Glossary("global object")}} is a {{domxref("Window")}}, the time origin is determined as follows: - If the current {{domxref("Document")}} is the first one loaded in the `Window`, the time origin is the time at which the browser context was created. - If during the process of unloading the previous document which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the new page was acceptable. - If neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current `Document` took place. - If the script's global object is a {{domxref("WorkerGlobalScope")}} (that is, the script is running as a web worker), the time origin is the moment at which the worker was created. - In all other cases, the time origin is undefined. ## Examples ### Synchronizing time between contexts To account for the different time origins in window and worker contexts, you can translate the timestamps coming from worker scripts with the help of the `timeOrigin` property, so the timings synchronize for the entire application. In worker.js ```js self.addEventListener("connect", (event) => { const port = event.ports[0]; port.onmessage = function (event) { const workerTaskStart = performance.now(); // doSomeWork() const workerTaskEnd = performance.now(); }; // Convert worker-relative timestamps to absolute timestamps, then send to the window port.postMessage({ startTime: workerTaskStart + performance.timeOrigin, endTime: workerTaskEnd + performance.timeOrigin, }); }); ``` In main.js ```js const worker = new SharedWorker("worker.js"); worker.port.addEventListener("message", (event) => { // Convert absolute timestamps into window-relative timestamps const workerTaskStart = event.data.startTime - performance.timeOrigin; const workerTaskEnd = event.data.endTime - performance.timeOrigin; console.log("Worker task start: ", workerTaskStart); console.log("Worker task end: ", workerTaskEnd); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/now/index.md
--- title: "Performance: now() method" short-title: now() slug: Web/API/Performance/now page-type: web-api-instance-method browser-compat: api.Performance.now --- {{APIRef("Performance API")}} The **`performance.now()`** method returns a high resolution timestamp in milliseconds. It represents the time elapsed since {{domxref("Performance.timeOrigin")}} (the time when navigation has started in window contexts, or the time when the worker is run in {{domxref("Worker")}} and {{domxref("ServiceWorker")}} contexts). ## Syntax ```js-nolint now() ``` ### Parameters None. ### Return value Returns a {{domxref("DOMHighResTimeStamp")}} measured in milliseconds. ## Description ### `Performance.now` vs. `Date.now` Unlike [`Date.now`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now), the timestamps returned by `performance.now()` are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision. Also, `Date.now()` may have been impacted by system and user clock adjustments, clock skew, etc. as it is relative to the Unix epoch (1970-01-01T00:00:00Z) and dependent on the system clock. The `performance.now()` method on the other hand is relative to the `timeOrigin` property which is a [monotonic clock](https://w3c.github.io/hr-time/#dfn-monotonic-clock): its current time never decreases and isn't subject to adjustments. ### `performance.now` specification changes The semantics of the `performance.now()` method changed between High Resolution Time Level 1 and Level 2. | Changes | Level 1 | Level 2 | | --------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Relative to | [`performance.timing.navigationStart`](/en-US/docs/Web/API/PerformanceTiming/navigationStart) | {{domxref("Performance.timeOrigin")}} | | Triggering conditions | Document fetch or unload prompt (if any). | Creation of the browsing context (if no prior document), unload prompt (if any), or start of the navigation (as defined in HTML, a few steps before fetch). | The `performance.now()` method used to be relative to [`performance.timing.navigationStart`](/en-US/docs/Web/API/PerformanceTiming/navigationStart) property from the Navigation Timing specification. This changed and `performance.now()` is now relative to {{domxref("Performance.timeOrigin")}} which avoids clock change risks when comparing timestamps across webpages. ```js // Level 1 (clock change risks) currentTime = performance.timing.navigationStart + performance.now(); // Level 2 (no clock change risks) currentTime = performance.timeOrigin + performance.now(); ``` ### Ticking during sleep The specification (Level 2) requires that `performance.now()` should tick during sleep. It appears that only Firefox on Windows, and Chromiums on Windows keep ticking during sleep. Relevant browser bugs for other operating systems: - Chrome/Chromium ([bug](https://bugs.chromium.org/p/chromium/issues/detail?id=1206450)) - Firefox ([bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1709767)) - Safari/WebKit ([bug](https://bugs.webkit.org/show_bug.cgi?id=225610)) More details can also be found in the specification issue [hr-time#115](https://github.com/w3c/hr-time/issues/115). ## Examples ### Using `performance.now()` To determine how much time has elapsed since a particular point in your code, you can do something like this: ```js const t0 = performance.now(); doSomething(); const t1 = performance.now(); console.log(`Call to doSomething took ${t1 - t0} milliseconds.`); ``` ## Security requirements To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting), `performance.now()` is coarsened based on site isolation status. - Resolution in isolated contexts: 5 microseconds - Resolution in non-isolated contexts: 100 microseconds Cross-origin isolate your site using the {{HTTPHeader("Cross-Origin-Opener-Policy")}} and {{HTTPHeader("Cross-Origin-Embedder-Policy")}} headers: ```http Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp ``` These headers ensure a top-level document does not share a browsing context group with cross-origin documents. COOP process-isolates your document and potential attackers can't access to your global object if they were opening it in a popup, preventing a set of cross-origin attacks dubbed [XS-Leaks](https://github.com/xsleaks/xsleaks). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.timeOrigin")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/getentriesbyname/index.md
--- title: "Performance: getEntriesByName() method" short-title: getEntriesByName() slug: Web/API/Performance/getEntriesByName page-type: web-api-instance-method browser-compat: api.Performance.getEntriesByName --- {{APIRef("Performance API")}} The **`getEntriesByName()`** method returns an array of {{domxref("PerformanceEntry")}} objects currently present in the performance timeline with the given _name_ and _type_. If you are interested in performance entries of certain types, see {{domxref("Performance.getEntriesByType", "getEntriesByType()")}}. For all performance entries, see {{domxref("Performance.getEntries", "getEntries()")}}. > **Note:** This method does not notify you about new performance entries; you will only get entries that are present in the performance timeline at the time you call this method. > To receive notifications about entries as they become available, use a {{domxref("PerformanceObserver")}}. The following entry types are not supported by this method at all and won't be returned even if entries for these types might exist: - `"element"` ({{domxref("PerformanceElementTiming")}}) - `"event"` ({{domxref("PerformanceEventTiming")}}) - `"largest-contentful-paint"` ({{domxref("LargestContentfulPaint")}}) - `"layout-shift"` ({{domxref("LayoutShift")}}) - `"longtask"` ({{domxref("PerformanceLongTaskTiming")}}) To access entries of these types, you must use a {{domxref("PerformanceObserver")}} instead. ## Syntax ```js-nolint getEntriesByName(name) getEntriesByName(name, type) ``` ### Parameters - `name` - : The name of the entries to retrieve. - `type` {{optional_inline}} - : The type of entries to retrieve such as "`mark`". The valid entry types are listed in {{domxref("PerformanceEntry.entryType")}}. ### Return value An {{jsxref("Array")}} of {{domxref("PerformanceEntry")}} objects that have the specified `name` and `type`. The items will be in chronological order based on the entries' {{domxref("PerformanceEntry.startTime","startTime")}}. If no objects meet the specified criteria, an empty array is returned. ## Examples ### Logging performance markers The following example logs all {{domxref("PerformanceMark")}} objects named "`debug-mark`". ```js const debugMarks = performance.getEntriesByName("debug-mark", "mark"); debugMarks.forEach((entry) => { console.log(`${entry.name}'s startTime: ${entry.startTime}`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.getEntries()")}} - {{domxref("Performance.getEntriesByType()")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/getentriesbytype/index.md
--- title: "Performance: getEntriesByType() method" short-title: getEntriesByType() slug: Web/API/Performance/getEntriesByType page-type: web-api-instance-method browser-compat: api.Performance.getEntriesByType --- {{APIRef("Performance API")}} The **`getEntriesByType()`** method returns an array of {{domxref("PerformanceEntry")}} objects currently present in the performance timeline for a given _type_. If you are interested in performance entries of certain name, see {{domxref("Performance.getEntriesByName", "getEntriesByName()")}}. For all performance entries, see {{domxref("Performance.getEntries", "getEntries()")}}. > **Note:** This method does not notify you about new performance entries; you will only get entries that are present in the performance timeline at the time you call this method. > To receive notifications about entries as they become available, use a {{domxref("PerformanceObserver")}}. The following entry types are not supported by this method at all and won't be returned even if entries for these types might exist: - `"element"` ({{domxref("PerformanceElementTiming")}}) - `"event"` ({{domxref("PerformanceEventTiming")}}) - `"largest-contentful-paint"` ({{domxref("LargestContentfulPaint")}}) - `"layout-shift"` ({{domxref("LayoutShift")}}) - `"longtask"` ({{domxref("PerformanceLongTaskTiming")}}) To access entries of these types, you must use a {{domxref("PerformanceObserver")}} instead. ## Syntax ```js-nolint getEntriesByType(type) ``` ### Parameters - `type` - : The type of entry to retrieve such as "`mark`". The valid entry types are listed in {{domxref("PerformanceEntry.entryType")}}. The supported `entryTypes` can be retrieved using the static property {{domxref("PerformanceObserver.supportedEntryTypes_static", "PerformanceObserver.supportedEntryTypes")}}. ### Return value An {{jsxref("Array")}} of {{domxref("PerformanceEntry")}} objects that have the specified `type`. The items will be in chronological order based on the entries' {{domxref("PerformanceEntry.startTime","startTime")}}. If no objects have the specified `type`, or no argument is provided, an empty array is returned. ## Examples ### Logging resource entries The following example logs all entries with the type "`resource`". ```js const resources = performance.getEntriesByType("resource"); resources.forEach((entry) => { console.log(`${entry.name}'s startTime: ${entry.startTime}`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.getEntries()")}} - {{domxref("Performance.getEntriesByName()")}} - {{domxref("PerformanceObserver.supportedEntryTypes_static", "PerformanceObserver.supportedEntryTypes")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/measureuseragentspecificmemory/index.md
--- title: "Performance: measureUserAgentSpecificMemory() method" short-title: measureUserAgentSpecificMemory() slug: Web/API/Performance/measureUserAgentSpecificMemory page-type: web-api-instance-method status: - experimental browser-compat: api.Performance.measureUserAgentSpecificMemory --- {{APIRef("Performance API")}} {{SeeCompatTable}} The **`measureUserAgentSpecificMemory()`** method is used to estimate the memory usage of a web application including all its iframes and workers. ## Description The browser automatically allocates memory when objects are created and frees it when they are not reachable anymore (garbage collection). This garbage collection (GC) is an approximation since the general problem of determining whether or not a specific piece of memory is still needed is impossible (see also [JavaScript Memory Management](/en-US/docs/Web/JavaScript/Memory_management)). Developers need to make sure that objects are garbage collected, memory isn't leaked, and memory usage doesn't grow unnecessarily over time leading to slow and unresponsive web applications. Memory leaks are typically introduced by forgetting to unregister an event listener, not closing a worker, accumulating objects in arrays, and more. The `measureUserAgentSpecificMemory()` API aggregates memory usage data to help you find memory leaks. It can be used for memory regression detection or for A/B testing features to evaluate their memory impact. Rather than make single calls to this method, it's better to make periodic calls to track how memory usage changes over the duration of a session. The `byte` values this API returns aren't comparable across browsers or between different versions of the same browser as these are highly implementation dependent. Also, how `breakdown` and `attribution` arrays are provided is up to the browser as well. It is best to not hardcode any assumptions about this data. This API is rather meant to be called periodically (with a randomized interval) to aggregate data and analyze the difference between the samples. ## Syntax ```js-nolint measureUserAgentSpecificMemory() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves to an object containing the following properties: - `bytes` - : A number representing the total memory usage. - `breakdown` - : An {{jsxref("Array")}} of objects partitioning the total `bytes` and providing attribution and type information. The object contains the following properties: - `bytes` - : The size of the memory that this entry describes. - `attribution` - : An {{jsxref("Array")}} of container elements of the JavaScript realms that use the memory. This object has the following properties: - `url` - : If this attribution corresponds to a same-origin JavaScript realm, then this property contains the realm's URL. Otherwise it is the string "cross-origin-url". - `container` - : An object describing the DOM element that contains this JavaScript realm. This object has the following properties: - `id` - : The `id` attribute of the container element. - `src` - : The `src` attribute of the container element. If the container element is an {{HTMLElement("object")}} element, then this field contains the value of the `data` attribute. - `scope` - : A string describing the type of the same-origin JavaScript realm. Either `"Window"`, `"DedicatedWorkerGlobalScope"`, `"SharedWorkerGlobalScope"`, `"ServiceWorkerGlobalScope"` or `"cross-origin-aggregated"` for the cross-origin case. - `types` - : An array of implementation-defined memory types associated with the memory. An example return value looks like this: ```js { bytes: 1500000, breakdown: [ { bytes: 1000000, attribution: [ { url: "https://example.com", scope: "Window", }, ], types: ["DOM", "JS"], }, { bytes: 0, attribution: [], types: [], }, { bytes: 500000, attribution: [ { url: "https://example.com/iframe.html" container: { id: "example-id", src: "redirect.html?target=iframe.html", }, scope: "Window", } ], types: ["JS", "DOM"], }, ], } ``` ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the security requirements for preventing cross-origin information leaks aren't fulfilled. ## Security requirements Your site needs to be in a [secure context](/en-US/docs/Web/Security/Secure_Contexts). Two headers need to be set to cross-origin isolate your site: - [`Cross-Origin-Opener-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) with `same-origin` as value (protects your origin from attackers) - [`Cross-Origin-Embedder-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) with `require-corp` or `credentialless` as value (protects victims from your origin) ```http Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp ``` To check if cross origin isolation has been successful, you can test against the [`crossOriginIsolated`](/en-US/docs/Web/API/crossOriginIsolated) property available to window and worker contexts: ```js if (crossOriginIsolated) { // Use measureUserAgentSpecificMemory } ``` ## Examples ### Monitoring memory usage The following code shows how to call the `measureUserAgentSpecificMemory()` method once every five minutes at a random interval using [Exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution#Random_variate_generation). ```js function runMemoryMeasurements() { const interval = -Math.log(Math.random()) * 5 * 60 * 1000; console.log(`Next measurement in ${Math.round(interval / 1000)} seconds.`); setTimeout(measureMemory, interval); } async function measureMemory() { const memorySample = await performance.measureUserAgentSpecificMemory(); console.log(memorySample); runMemoryMeasurements(); } if (crossOriginIsolated) { runMemoryMeasurements(); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("setTimeout()")}} - [Monitor your web page's total memory usage with measureUserAgentSpecificMemory() - web.dev](https://web.dev/articles/monitor-total-page-memory-usage)
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/mark/index.md
--- title: "Performance: mark() method" short-title: mark() slug: Web/API/Performance/mark page-type: web-api-instance-method browser-compat: api.Performance.mark --- {{APIRef("Performance API")}} The **`mark()`** method creates a named {{domxref("PerformanceMark")}} object representing a high resolution timestamp marker in the browser's performance timeline. ## Syntax ```js-nolint mark(name) mark(name, markOptions) ``` ### Parameters - `name` - : A string representing the name of the mark. Must not be the same name as one of the properties of the deprecated {{domxref("PerformanceTiming")}} interface. - `markOptions` {{optional_inline}} - : An object for specifying a timestamp and additional metadata for the mark. - `detail` {{optional_inline}} - : Arbitrary metadata to include in the mark. Defaults to `null`. Must be [structured-cloneable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - `startTime` {{optional_inline}} - : {{domxref("DOMHighResTimeStamp")}} to use as the mark time. Defaults to {{domxref("performance.now()")}}. ### Return value The {{domxref("PerformanceMark")}} entry that was created. ### Exceptions - {{jsxref("SyntaxError")}}: Thrown if the `name` is one of the properties of the deprecated {{domxref("PerformanceTiming")}} interface. See the [example below](#reserved_names). - {{jsxref("TypeError")}}: Thrown if `startTime` is negative. ## Examples ### Creating named markers The following example uses `mark()` to create named {{domxref("PerformanceMark")}} entries. You can create several marks with the same name. You can also assign them, to have a reference to the {{domxref("PerformanceMark")}} object that has been created. ```js performance.mark("login-started"); performance.mark("login-started"); performance.mark("login-finished"); performance.mark("form-sent"); const videoMarker = performance.mark("video-loaded"); ``` ### Creating markers with details The performance mark is configurable using the `markOptions` object where you can put additional information in the `detail` property, which can be of any type. ```js performance.mark("login-started", { detail: "Login started using the login button in the top menu.", }); performance.mark("login-started", { detail: { htmlElement: myElement.id }, }); ``` ### Creating markers with a different start time The default timestamp of the `mark()` method is {{domxref("performance.now()")}}. You can set it to a different time using the `startTime` option in `markOptions`. ```js performance.mark("start-checkout", { startTime: 20.0, }); performance.mark("login-button-pressed", { startTime: myEvent.timeStamp, }); ``` ### Reserved names Note in order to maintain backwards compatibility, names that are part of the deprecated {{domxref("PerformanceTiming")}} interface can't be used. The following example throws: ```js example-bad performance.mark("navigationStart"); // SyntaxError: "navigationStart" is part of // the PerformanceTiming interface, // and cannot be used as a mark name ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/eventcounts/index.md
--- title: "Performance: eventCounts property" short-title: eventCounts slug: Web/API/Performance/eventCounts page-type: web-api-instance-property browser-compat: api.Performance.eventCounts --- {{APIRef("Performance API")}} The read-only `performance.eventCounts` property is an {{domxref("EventCounts")}} map containing the number of events which have been dispatched per event type. Not all event types are exposed. You can only get counts for event types supported by the {{domxref("PerformanceEventTiming")}} interface. ## Value An {{domxref("EventCounts")}} map. (A read-only {{jsxref("Map")}} without the `clear()`, `delete()`, and `set()` methods). ## Examples ### Reporting event types and their counts If you like to send event counts to your analytics, you may want to implement a function like `sendToEventAnalytics` which takes the event counts from the `performance.eventCounts` map and then uses the [Fetch API](/en-US/docs/Web/API/Fetch_API) to post the data to your endpoint. ```js // Report all exposed events for (entry of performance.eventCounts.entries()) { const type = entry[0]; const count = entry[1]; // sendToEventAnalytics(type, count); } // Report a specific event const clickCount = performance.eventCounts.get("click"); // sendToEventAnalytics("click", clickCount); // Check if an event count is exposed for a type const isExposed = performance.eventCounts.has("mousemove"); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("EventCounts")}} - {{domxref("PerformanceEventTiming")}} - {{jsxref("Map")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/clearmarks/index.md
--- title: "Performance: clearMarks() method" short-title: clearMarks() slug: Web/API/Performance/clearMarks page-type: web-api-instance-method browser-compat: api.Performance.clearMarks --- {{APIRef("Performance API")}} The **`clearMarks()`** method removes all or specific {{domxref("PerformanceMark")}} objects from the browser's performance timeline. ## Syntax ```js-nolint clearMarks() clearMarks(name) ``` ### Parameters - `name` {{optional_inline}} - : A string representing the {{domxref("PerformanceEntry.name", "name")}} of the {{domxref("PerformanceMark")}} object. If this argument is omitted, all entries with an {{domxref("PerformanceEntry.entryType","entryType")}} of "`mark`" will be removed. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Removing markers To clean up all performance marks, or just specific entries, use the `clearMarks()` method like this: ```js // Create a bunch of marks performance.mark("login-started"); performance.mark("login-started"); performance.mark("login-finished"); performance.mark("form-sent"); performance.mark("video-loaded"); performance.mark("video-loaded"); performance.getEntriesByType("mark").length; // 6 // Delete just the "login-started" mark entries performance.clearMarks("login-started"); performance.getEntriesByType("mark").length; // 4 // Delete all of the mark entries performance.clearMarks(); performance.getEntriesByType("mark").length; // 0 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("PerformanceMark")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/setresourcetimingbuffersize/index.md
--- title: "Performance: setResourceTimingBufferSize() method" short-title: setResourceTimingBufferSize() slug: Web/API/Performance/setResourceTimingBufferSize page-type: web-api-instance-method browser-compat: api.Performance.setResourceTimingBufferSize --- {{APIRef("Performance API")}} The **`setResourceTimingBufferSize()`** method sets the desired size of the browser's resource timing buffer which stores the "`resource`" performance entries. The specification requires the resource timing buffer initially to be 250 or greater. To clear the browser's performance resource data buffer, use the {{domxref("Performance.clearResourceTimings()")}} method. To get notified when the browser's resource timing buffer is full, listen for the {{domxref("Performance.resourcetimingbufferfull_event", "resourcetimingbufferfull")}} event. ## Syntax ```js-nolint setResourceTimingBufferSize(maxSize) ``` ### Parameters - `maxSize` - : A `number` representing the maximum number of {{domxref("PerformanceEntry","performance entry")}} objects the browser should hold in its performance entry buffer. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Setting a resource timing buffer size The following call allows 500 "`resource`" performance entries in the browser's performance timeline. ```js performance.setResourceTimingBufferSize(500); ``` If you set the buffer size to a number lower than the amount of current entries in the buffer, no entries will be removed. Instead, to clear the buffer, call {{domxref("Performance.clearResourceTimings()")}}. ```js performance.getEntriesByType("resource").length; // 20 performance.setResourceTimingBufferSize(10); performance.getEntriesByType("resource").length; // 20 performance.clearResourceTimings(); performance.getEntriesByType("resource").length; // 0 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.clearResourceTimings()")}} - {{domxref("Performance.resourcetimingbufferfull_event", "resourcetimingbufferfull")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/clearmeasures/index.md
--- title: "Performance: clearMeasures() method" short-title: clearMeasures() slug: Web/API/Performance/clearMeasures page-type: web-api-instance-method browser-compat: api.Performance.clearMeasures --- {{APIRef("Performance API")}} The **`clearMeasures()`** method removes all or specific {{domxref("PerformanceMeasure")}} objects from the browser's performance timeline. ## Syntax ```js-nolint clearMeasures() clearMeasures(name) ``` ### Parameters - `name` {{optional_inline}} - : A string representing the {{domxref("PerformanceEntry.name", "name")}} of the {{domxref("PerformanceMeasure")}} object. If this argument is omitted, all entries with an {{domxref("PerformanceEntry.entryType","entryType")}} of "`measure`" will be removed. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Removing measures To clean up all performance measure, or just specific entries, use the `clearMeasures()` method like this: ```js // Create a bunch of measures performance.measure("from navigation"); performance.mark("a"); performance.measure("from mark a", "a"); performance.measure("from navigation"); performance.measure("from mark a", "a"); performance.mark("b"); performance.measure("between a and b", "a", "b"); performance.getEntriesByType("measure").length; // 5 // Delete just the "from navigation" measure entries performance.clearMeasures("from navigation"); performance.getEntriesByType("measure").length; // 3 // Delete all of the measure entries performance.clearMeasures(); performance.getEntriesByType("measure").length; // 0 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("PerformanceMeasure")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/measure/index.md
--- title: "Performance: measure() method" short-title: measure() slug: Web/API/Performance/measure page-type: web-api-instance-method browser-compat: api.Performance.measure --- {{APIRef("Performance API")}} The **`measure()`** method creates a named {{domxref("PerformanceMeasure")}} object representing a time measurement between two marks in the browser's performance timeline. When measuring between two marks, there is a _start mark_ and _end mark_, respectively. The named timestamp is referred to as a _measure_. ## Syntax ```js-nolint measure(measureName) measure(measureName, startMark) measure(measureName, startMark, endMark) measure(measureName, measureOptions) measure(measureName, measureOptions, endMark) ``` If only `measureName` is specified, the start timestamp is set to zero, and the end timestamp (which is used to calculate the duration) is the value that would be returned by {{domxref("Performance.now()")}}. You can use strings to identify {{domxref("PerformanceMark")}} objects as start and end marks. To only provide an `endMark`, you need to provide an empty `measureOptions` object: `performance.measure("myMeasure", {}, "myEndMarker")`. ### Parameters - `measureName` - : A string representing the name of the measure. - `measureOptions` {{optional_inline}} - : An object that may contain measure options. - `detail` {{optional_inline}} - : Arbitrary metadata to be included in the measure. Defaults to `null`. Must be [structured-cloneable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - `start` {{optional_inline}} - : Timestamp ({{domxref("DOMHighResTimeStamp")}}) to be used as the start time, or string that names a {{domxref("PerformanceMark")}} to use for the start time. If this is a string naming a {{domxref("PerformanceMark")}}, then it is defined in the same way as `startMark`. - `duration` {{optional_inline}} - : Duration (in milliseconds) between the start and end mark times. If omitted, this defaults to {{domxref("performance.now()")}}; the time that has elapsed since the context was created. If provided, you must also specify either `start` or `end` but not both. - `end` {{optional_inline}} - : Timestamp ({{domxref("DOMHighResTimeStamp")}}) to be used as the end time, or string that names a {{domxref("PerformanceMark")}} to use for the end time. If this is a string naming a {{domxref("PerformanceMark")}}, then it is defined in the same way as `endMark`. - `startMark` {{optional_inline}} - : A string naming a {{domxref("PerformanceMark")}} in the performance timeline. The {{domxref("PerformanceEntry.startTime")}} property of this mark will be used for calculating the measure. - `endMark` {{optional_inline}} - : A string naming a {{domxref("PerformanceMark")}} in the performance timeline. The {{domxref("PerformanceEntry.startTime")}} property of this mark will be used for calculating the measure. If you want to pass this argument, you must also pass either `startMark` or an empty `measureOptions` object. ### Return value The {{domxref("PerformanceMeasure")}} entry that was created. The returned _measure_ will have the following property values: - {{domxref("PerformanceEntry.entryType","entryType")}} - set to "`measure`". - {{domxref("PerformanceEntry.name","name")}} - set to the "`name`" argument. - {{domxref("PerformanceEntry.startTime","startTime")}} - set to: - a {{domxref("DOMHighResTimeStamp","timestamp")}}, if specified in `measureOptions.start`. - the {{domxref("DOMHighResTimeStamp","timestamp")}} of a start mark, if specified in `measureOptions.start` or `startMark` - a timestamp calculated from the `measureOptions.end` and `measureOptions.duration` (if `measureOptions.start` was not specified) - 0, if it isn't specified and can't be determined from other values. - {{domxref("PerformanceEntry.duration","duration")}} - set to a {{domxref("DOMHighResTimeStamp")}} that is the duration of the measure calculated by subtracting the `startTime` from the end timestamp. The end timestamp is one of: - a {{domxref("DOMHighResTimeStamp","timestamp")}}, if specified in `measureOptions.end`. - the {{domxref("DOMHighResTimeStamp","timestamp")}} of an end mark, if one is specified in `measureOptions.end` or `endMark` - a timestamp calculated from the `measureOptions.start` and `measureOptions.duration` (if `measureOptions.end` was not specified) - the value returned by {{domxref("Performance.now()")}}, if no end mark is specified or can be determined from other values. - {{domxref("PerformanceMeasure","detail")}} - set to the value passed in `measureOptions`. ### Exceptions - {{jsxref("TypeError")}} - : This can be thrown in any case where the start, end or duration might be ambiguous: - Both `endMark` and `measureOptions` are specified. - `measureOptions` is specified with `duration` but without specifying either `start` or `end`. - `measureOptions` is specified with all of `start`, `end`, and `duration`. - `SyntaxError` {{domxref("DOMException")}} - : The named mark does not exist. - An end mark is specified using either `endMark` or `measureOptions.end`, but there is no {{domxref('PerformanceMark')}} in the performance buffer with the matching name. - An end mark is specified using either `endMark` or `measureOptions.end`, but it cannot be converted to match that of a read only attribute in the {{domxref("PerformanceTiming")}} interface. - A start mark is specified using either `startMark` or `measureOptions.start`, but there is no {{domxref('PerformanceMark')}} in the performance buffer with the matching name. - A start mark is specified using either `startMark` or `measureOptions.start`, but it cannot be converted to match that of a read only attribute in the {{domxref("PerformanceTiming")}} interface. - `DataCloneError` {{domxref("DOMException")}} - : The `measureOptions.detail` value is non-`null` and cannot be serialized using the HTML "StructuredSerialize" algorithm. - {{jsxref("RangeError")}} - : The `measureOptions.detail` value is non-`null` and memory cannot be allocated during serialization using the HTML "StructuredSerialize" algorithm. ## Examples ### Measuring duration between named markers Given two of your own markers `"login-started"` and `"login-finished"`, you can create a measurement called `"login-duration"` as shown in the following example. The returned {{domxref("PerformanceMeasure")}} object will then provide a `duration` property to tell you the elapsed time between the two markers. ```js const loginMeasure = performance.measure( "login-duration", "login-started", "login-finished", ); console.log(loginMeasure.duration); ``` ### Measuring duration with custom start and end times To do more advanced measurements, you can pass a `measureOptions` parameter. For example, you can use the [`event.timeStamp`](/en-US/docs/Web/API/Event/timeStamp) property from a [`click` event](/en-US/docs/Web/API/Element/click_event) as the start time. ```js performance.measure("login-click", { start: myClickEvent.timeStamp, end: myMarker.startTime, }); ``` ### Providing additional measurement details You can use the `details` property to provide additional information of any type. Maybe you want to record which HTML element was clicked, for example. ```js performance.measure("login-click", { detail: { htmlElement: myElement.id }, start: myClickEvent.timeStamp, end: myMarker.startTime, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/resourcetimingbufferfull_event/index.md
--- title: "Performance: resourcetimingbufferfull event" short-title: resourcetimingbufferfull slug: Web/API/Performance/resourcetimingbufferfull_event page-type: web-api-event browser-compat: api.Performance.resourcetimingbufferfull_event --- {{APIRef("Performance API")}} The `resourcetimingbufferfull` event is fired when the browser's [resource timing buffer](/en-US/docs/Web/API/Performance/setResourceTimingBufferSize) is full. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("resourcetimingbufferfull", (event) => {}); onresourcetimingbufferfull = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ### Increasing size when buffer is full The following example listens for the `resourcetimingbufferfull` event and increases the buffer size using the {{domxref("Performance.setResourceTimingBufferSize", "setResourceTimingBufferSize()")}} method. ```js function increaseFilledBufferSize(event) { console.log( "WARNING: Resource Timing Buffer is FULL! Increasing buffer size to 500.", ); performance.setResourceTimingBufferSize(500); } performance.addEventListener( "resourcetimingbufferfull", increaseFilledBufferSize, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.clearResourceTimings()")}} - {{domxref("Performance.setResourceTimingBufferSize()")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/memory/index.md
--- title: "Performance: memory property" short-title: memory slug: Web/API/Performance/memory page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.Performance.memory --- {{APIRef("Performance API")}} {{Deprecated_Header}}{{Non-standard_header}} The non-standard and legacy `performance.memory` property returns the size of the JavaScript heap which can be helpful to measure and reduce the memory footprint of websites. Note that the information this API provides is unreliable as it might overestimate actual memory usage if web pages share the same heap, or might underestimate actual memory usage if web pages use workers and/or cross-site iframes that are allocated in separate heaps. It is not standardized what "heap" means exactly. The API is only available in Chromium-based browsers. A new API aiming to replace `performance.memory` is {{domxref("Performance.measureUserAgentSpecificMemory()")}}. It tries to estimate the memory used by a web page. ## Value The read-only `performance.memory` property is an object with the following properties: - `jsHeapSizeLimit` - : The maximum size of the heap, in bytes, that is available to the context. - `totalJSHeapSize` - : The total allocated heap size, in bytes. - `usedJSHeapSize` - : The currently active segment of JS heap, in bytes. ## Examples ### Getting JavaScript heap sizes Calling `performance.memory` returns an object like this: ```js { totalJSHeapSize: 39973671, usedJSHeapSize: 39127515, jsHeapSizeLimit: 4294705152 } ``` ## Specifications None. ## Browser compatibility {{Compat}} ## See also - {{domxref("Performance.measureUserAgentSpecificMemory()")}}
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/navigation/index.md
--- title: "Performance: navigation property" short-title: navigation slug: Web/API/Performance/navigation page-type: web-api-instance-property status: - deprecated browser-compat: api.Performance.navigation --- {{APIRef("Performance API")}}{{Deprecated_Header}} The legacy **`Performance.navigation`** read-only property returns a {{domxref("PerformanceNavigation")}} object representing the type of navigation that occurs in the given browsing context, such as the number of redirections needed to fetch the resource. This property is not available in workers. > **Warning:** This property is deprecated in the [Navigation Timing Level 2 specification](https://w3c.github.io/navigation-timing/#obsolete). Please use the > {{domxref("PerformanceNavigationTiming")}} interface instead. ## Value A {{domxref("PerformanceNavigation")}} object. ## Specifications This feature is no longer on track to become a standard, as the [Navigation Timing specification](https://w3c.github.io/navigation-timing/#obsolete) has marked it as deprecated. Use the {{domxref("PerformanceNavigationTiming")}} interface instead. ## Browser compatibility {{Compat}} ## See also - The {{domxref("Performance")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api/performance
data/mdn-content/files/en-us/web/api/performance/tojson/index.md
--- title: "Performance: toJSON() method" short-title: toJSON() slug: Web/API/Performance/toJSON page-type: web-api-instance-method browser-compat: api.Performance.toJSON --- {{APIRef("Performance API")}} The **`toJSON()`** method of the {{domxref("Performance")}} interface is a {{Glossary("Serialization","serializer")}}; it returns a JSON representation of the {{domxref("Performance")}} object. ## Syntax ```js-nolint toJSON() ``` ### Parameters None. ### Return value A {{jsxref("JSON")}} object that is the serialization of the {{domxref("Performance")}} object. The returned JSON doesn't contain the {{domxref("Performance.eventCounts", "eventCounts")}} property because it is of type {{domxref("EventCounts")}}, which doesn't provide a `toJSON()` operation. > **Note:** The JSON object contains the serialization of the deprecated {{domxref("performance.timing")}} and {{domxref("performance.navigation")}} properties. To get a JSON representation of the newer {{domxref("PerformanceNavigationTiming")}} interface, call {{domxref("PerformanceNavigationTiming.toJSON()")}} instead. ## Examples ### Using the toJSON method In this example, calling `performance.toJSON()` returns a JSON representation of the `Performance` object. ```js performance.toJSON(); ``` This would log a JSON object like so: ```json { "timeOrigin": 1668077531367.4, "timing": { "connectStart": 1668077531372, "navigationStart": 1668077531367, "secureConnectionStart": 0, "fetchStart": 1668077531372, "domContentLoadedEventStart": 1668077531580, "responseStart": 1668077531372, "domInteractive": 1668077531524, "domainLookupEnd": 1668077531372, "responseEnd": 1668077531500, "redirectStart": 0, "requestStart": 1668077531372, "unloadEventEnd": 0, "unloadEventStart": 0, "domLoading": 1668077531512, "domComplete": 1668077531585, "domainLookupStart": 1668077531372, "loadEventStart": 1668077531585, "domContentLoadedEventEnd": 1668077531580, "loadEventEnd": 1668077531585, "redirectEnd": 0, "connectEnd": 1668077531372 }, "navigation": { "type": 0, "redirectCount": 0 } } ``` To get a JSON string, you can use [`JSON.stringify(performance)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) directly; it will call `toJSON()` automatically. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("JSON")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/csscontainerrule/index.md
--- title: CSSContainerRule slug: Web/API/CSSContainerRule page-type: web-api-interface browser-compat: api.CSSContainerRule --- {{ APIRef("CSSOM") }} The **`CSSContainerRule`** interface represents a single CSS {{cssxref("@container")}} rule. An object of this type can be used to get the query conditions for the {{cssxref("@container")}}, along with the container name if one is defined. Note that the container name and query together define the "condition text", which can be obtained using {{domxref("CSSConditionRule.conditionText")}}. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its ancestors {{domxref("CSSConditionRule")}}, {{domxref("CSSGroupingRule")}}, and {{domxref("CSSRule")}}._ - {{domxref("CSSContainerRule.containerName")}} {{ReadOnlyInline}} - : Returns a string representing the name of an {{cssxref("@container")}}, or an empty string. - {{domxref("CSSContainerRule.containerQuery")}} {{ReadOnlyInline}} - : Returns a string representing the set of features or "container conditions" that are evaluated to determine if the styles in the associated {{cssxref("@container")}} are applied. ## Instance methods _No specific methods; inherits methods from its ancestors {{domxref("CSSConditionRule")}}, {{domxref("CSSGroupingRule")}}, and {{domxref("CSSRule")}}._ ## Examples ### Unnamed container rule The example below defines an unnamed {{cssxref("@container")}} rule, and displays the properties of the associated {{domxref("CSSContainerRule")}}. The CSS is the same as in the `@container` example [Setting styles based on a container's size](/en-US/docs/Web/CSS/@container#setting_styles_based_on_a_containers_size). The first part of the code simply creates a list for logging the container rule properties, along with a JavaScript `log()` method to simplify adding the properties. ```html <div id="log"> <h2>Log</h2> <ul></ul> <hr /> </div> ``` ```js // Store reference to log list const logList = document.querySelector("#log ul"); // Function to log data from underlying source function log(result) { const listItem = document.createElement("li"); listItem.textContent = result; logList.appendChild(listItem); } ``` Then we define the HTML for a `card` (`<div>`) contained within a `post`. ```html <div class="post"> <div class="card"> <h2>Card title</h2> <p>Card content</p> </div> </div> ``` The CSS for the example is shown below. As described in the corresponding {{cssxref("@container")}} example, the CSS for the container element specifies the type of the container. The {{cssxref("@container")}} then applies a new width, font-size and background color to the card if the width is less than 650px. ```html <style id="examplestyles"> /* A container context based on inline size */ .post { container-type: inline-size; } /* Apply styles if the container is narrower than 650px */ @container (width < 650px) { .card { width: 50%; background-color: gray; font-size: 1em; } } </style> ``` The code below gets the {{domxref("HTMLStyleElement")}} associated with the example using its id, and then uses its `sheet` property to get the {{domxref("StyleSheet")}}. From the `StyleSheet` we get the set of `cssRules` added to the sheet. Since we added the `@container` as the second rule above, we can access the associated `CSSContainerRule` using the second entry, with index "1", in the `cssRules`. Last of all, we log the `containerName`, `containerQuery` and `conditionText` (inherited) properties. ```js const exampleStylesheet = document.getElementById("examplestyles").sheet; const exampleRules = exampleStylesheet.cssRules; const containerRule = exampleRules[1]; // a CSSContainerRule representing the container rule. log(`CSSContainerRule.containerName: "${containerRule.containerName}"`); log(`CSSContainerRule.containerQuery: "${containerRule.containerQuery}"`); log(`CSSContainerRule.conditionText: "${containerRule.conditionText}"`); ``` > **Note:** The styles for this example are defined in an inline HTML `style` element with an id in order to make it easy for the code to find the correct sheet. > You might also locate the correct sheets for each example from the document by indexing against the length (e.g. `document.styleSheets[document.styleSheets.length-1]` but that makes working out correct sheet for each example more complicated). The example output is shown below. The log section lists the `containerName`, which is an empty string as no name has been defined. The `containerQuery` and `conditionText` strings are also logged, and have the same value because there is no name defined. The card should change background and as the width of the page transitions through 650px. {{EmbedLiveSample("Unnamed container rule","100%","300px")}} ### Named container rule The example below defines a named {{cssxref("@container")}} rule, and displays the properties of the associated {{domxref("CSSContainerRule")}}. The CSS is very similar to that in the `@container` example [Creating named container contexts](/en-US/docs/Web/CSS/@container#creating_named_container_contexts). ```html hidden <div id="log"> <h2>Log</h2> <ul></ul> <hr /> </div> ``` ```js hidden // Store reference to log list const logList = document.querySelector("#log ul"); // Function to log data from underlying source function log(result) { const listItem = document.createElement("li"); listItem.textContent = result; logList.appendChild(listItem); } ``` First we define the HTML for a `card` (`<div>`) contained within a `post` (the example does not show the logging code, as this is the same as in the previous example). ```html <div class="post"> <div class="card"> <h2>Card title</h2> <p>Card content</p> </div> </div> ``` As described in {{cssxref("@container")}}, the CSS for the container element specifies the type of the container, and may also specify a name for the container. The card has a default font size, which is overridden for the `@container` named `sidebar` if the minimum width is greater than 700px. ```html <style id="examplestyles"> .post { container-type: inline-size; container-name: sidebar; } /* Default heading styles for the card title */ .card h2 { font-size: 1em; } @container sidebar (min-width: 700px) { .card { font-size: 2em; } } </style> ``` The code for getting the sheet and rules is almost identical to the previous example. The only difference is that in this example we have three CSS rules, so to get the associated `CSSContainerRule` we get the third entry in the `cssRules`. ```js const exampleStylesheet = document.getElementById("examplestyles").sheet; const exampleRules = exampleStylesheet.cssRules; const containerRule = exampleRules[2]; // a CSSContainerRule representing the container rule. log(`CSSContainerRule.containerName: "${containerRule.containerName}"`); log(`CSSContainerRule.containerQuery: "${containerRule.containerQuery}"`); log(`CSSContainerRule.conditionText: "${containerRule.conditionText}"`); ``` The example output is shown below. The log section lists the `containerName` and `containerQuery` strings. The `conditionText` is also logged, and shows the combination of these two strings. The title in the card section should double in size as the width of the page goes over 700px. {{EmbedLiveSample("Named container rule","100%","300px")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - CSS {{cssxref("container-name")}}, {{cssxref("container-type")}}, and {{cssxref("container")}} shorthand properties - [CSS containment module](/en-US/docs/Web/CSS/CSS_containment) - [Container queries](/en-US/docs/Web/CSS/CSS_containment/Container_queries) - [Using container size and style queries](/en-US/docs/Web/CSS/CSS_containment/Container_size_and_style_queries)
0
data/mdn-content/files/en-us/web/api/csscontainerrule
data/mdn-content/files/en-us/web/api/csscontainerrule/containername/index.md
--- title: "CSSContainerRule: containerName property" short-title: containerName slug: Web/API/CSSContainerRule/containerName page-type: web-api-instance-property browser-compat: api.CSSContainerRule.containerName --- {{ APIRef("CSSOM") }} The read-only **`containerName`** property of the {{domxref("CSSContainerRule")}} interface represents the container name of the associated CSS {{cssxref("@container")}} at-rule. For example, the value of `containerName` for the {{cssxref("@container")}} below is `sidebar`: ```css @container sidebar (min-width: 700px) { .card { font-size: 2em; } } ``` ## Value A string that contains the [`container-name`](/en-US/docs/Web/CSS/container-name) of the {{cssxref("@container")}} associated with this {{domxref("CSSContainerRule")}}. If the `@container` is not [named](/en-US/docs/Web/API/CSSContainerRule#unnamed_container_rule), the function returns the empty string (`""`). ## Examples The example below defines a named {{cssxref("@container")}} rule, and displays the properties of the associated {{domxref("CSSContainerRule")}}. The CSS is very similar to that in the `@container` example [Creating named container contexts](/en-US/docs/Web/CSS/@container#creating_named_container_contexts). ```html hidden <div id="log"> <h2>Log</h2> <ul></ul> <hr /> </div> ``` ```js hidden // Store reference to log list const logList = document.querySelector("#log ul"); // Function to log data from underlying source function log(result) { const listItem = document.createElement("li"); listItem.textContent = result; logList.appendChild(listItem); } ``` First we define the HTML for a `card` (`<div>`) contained within a `post`. ```html <div class="post"> <div class="card"> <h2>Card title</h2> <p>Card content</p> </div> </div> ``` The CSS for the container element specifies the type of the container, and may also specify a name. The card has a default font size, which is overridden for the `@container` named `sidebar` if the minimum width is greater than 700px. ```html <style id="examplestyles"> .post { container-type: inline-size; container-name: sidebar; } /* Default heading styles for the card title */ .card h2 { font-size: 1em; } @container sidebar (min-width: 700px) { .card { font-size: 2em; } } </style> ``` The code below gets the {{domxref("HTMLStyleElement")}} associated with the example using its `id`, and then uses its `sheet` property to get the {{domxref("StyleSheet")}}. From the `StyleSheet` we get the set of `cssRules` added to the sheet. Since we added the `@container` as the third rule above, we can access the associated `CSSContainerRule` using the third entry (index "2"), in the `cssRules`. Last of all, we log the container name and query properties (the code that does the logging is not shown). ```js const exampleStylesheet = document.getElementById("examplestyles").sheet; const exampleRules = exampleStylesheet.cssRules; const containerRule = exampleRules[2]; // a CSSContainerRule representing the container rule. log(`CSSContainerRule.containerName: "${containerRule.containerName}"`); ``` The example output is shown below. The log section lists the container name string. The title in the card section should double in size as the width of the page goes over 700px. {{EmbedLiveSample("Examples","100%","250px")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - CSS {{cssxref("container")}} shorthand property - [CSS containment module](/en-US/docs/Web/CSS/CSS_containment) - [Container queries](/en-US/docs/Web/CSS/CSS_containment/Container_queries) - [Using container size and style queries](/en-US/docs/Web/CSS/CSS_containment/Container_size_and_style_queries)
0
data/mdn-content/files/en-us/web/api/csscontainerrule
data/mdn-content/files/en-us/web/api/csscontainerrule/containerquery/index.md
--- title: "CSSContainerRule: containerQuery property" short-title: containerQuery slug: Web/API/CSSContainerRule/containerQuery page-type: web-api-instance-property browser-compat: api.CSSContainerRule.containerQuery --- {{ APIRef("CSSOM") }} The read-only **`containerQuery`** property of the {{domxref("CSSContainerRule")}} interface returns a string representing the container conditions that are evaluated when the container changes size in order to determine if the styles in the associated {{cssxref("@container")}} are applied. For example, the value of `containerQuery` for the {{cssxref("@container")}} below is `(min-width: 700px)`: ```css @container sidebar (min-width: 700px) { .card { font-size: 2em; } } ``` ## Value A string containing the container query. Note that the value may not be identical to the original string, as normalizations such as removing whitespace may happen. ## Examples The example below defines an unnamed {{cssxref("@container")}} rule, and displays the properties of the associated {{domxref("CSSContainerRule")}}. The CSS is the same as in the `@container` example [Setting styles based on a container's size](/en-US/docs/Web/CSS/@container#setting_styles_based_on_a_containers_size). ```html hidden <div id="log"> <h2>Log</h2> <ul></ul> <hr /> </div> ``` ```js hidden // Store reference to log list const logList = document.querySelector("#log ul"); // Function to log data from underlying source function log(result) { const listItem = document.createElement("li"); listItem.textContent = result; logList.appendChild(listItem); } ``` First we define the HTML for a `card` (`<div>`) contained within a `post`. ```html <div class="post"> <div class="card"> <h2>Card title</h2> <p>Card content</p> </div> </div> ``` The CSS for the container element specifies the type of the container. The {{cssxref("@container")}} then applies a new width, font-size and background color to the contained element "card" if the width is less than 650px. ```html <style id="examplestyles"> /* A container context based on inline size */ .post { container-type: inline-size; } /* Apply styles if the container is narrower than 650px */ @container (width < 650px) { .card { width: 50%; background-color: gray; font-size: 1em; } } </style> ``` The code below gets the {{domxref("HTMLStyleElement")}} associated with the example using its id, and then uses its `sheet` property to get the {{domxref("StyleSheet")}}. From the `StyleSheet` we get the set of `cssRules` added to the sheet. Since we added the `@container` as the second rule above, we can access the associated `CSSContainerRule` using the second entry (with index "1"), in the `cssRules`. Last of all, we log the container name and query properties. ```js const exampleStylesheet = document.getElementById("examplestyles").sheet; const exampleRules = exampleStylesheet.cssRules; const containerRule = exampleRules[1]; // a CSSContainerRule representing the container rule. log(`CSSContainerRule.containerQuery: "${containerRule.containerQuery}"`); ``` The example output is shown below. The log section lists the query string. The card should change background and as the width of the page transitions through 650px. {{EmbedLiveSample("Examples","100%","250px")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [CSS containment module](/en-US/docs/Web/CSS/CSS_containment) - [Container queries](/en-US/docs/Web/CSS/CSS_containment/Container_queries) - [Using container size and style queries](/en-US/docs/Web/CSS/CSS_containment/Container_size_and_style_queries)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/videocolorspace/index.md
--- title: VideoColorSpace slug: Web/API/VideoColorSpace page-type: web-api-interface browser-compat: api.VideoColorSpace --- {{APIRef("WebCodecs API")}} The **`VideoColorSpace`** interface of the {{domxref('WebCodecs API','','',' ')}} represents the color space of a video. ## Constructor - {{domxref("VideoColorSpace.VideoColorSpace", "VideoColorSpace()")}} - : Creates a new `VideoColorSpace` object. ## Instance properties - {{domxref("VideoColorSpace.primaries")}} {{ReadOnlyInline}} - : A string containing the color primary describing the color {{glossary("gamut")}} of a video sample. - {{domxref("VideoColorSpace.transfer")}} - : A string containing the transfer characteristics of video samples. - {{domxref("VideoColorSpace.matrix")}} - : A string containing the matrix coefficients describing the relationship between sample component values and color coordinates. - {{domxref("VideoColorSpace.fullRange")}} - : A {{jsxref("Boolean")}}. If `true` indicates that full-range color values are used. ## Instance methods - {{domxref("VideoColorSpace.toJSON()")}} - : Returns a JSON representation of the `VideoColorSpace` object. ## Examples In the following example, `colorSpace` is a `VideoColorSpace` object returned from {{domxref("VideoFrame")}}. The object is then printed to the console. ```js let colorSpace = VideoFrame.colorSpace; console.log(colorSpace); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videocolorspace
data/mdn-content/files/en-us/web/api/videocolorspace/transfer/index.md
--- title: "VideoColorSpace: transfer property" short-title: transfer slug: Web/API/VideoColorSpace/transfer page-type: web-api-instance-property browser-compat: api.VideoColorSpace.transfer --- {{DefaultAPISidebar("WebCodecs API")}} The **`transfer`** read-only property of the {{domxref("VideoColorSpace")}} interface returns the opto-electronic transfer characteristics of the video. ## Value A string containing one of the following values: - `"bt709"` - : Transfer characteristics used by BT.709. - `"smpte170m"` - : Transfer characteristics used by BT.601 NTSC. - `"iec61966-2-1"` - : Transfer characteristics used by sRGBA. ## Examples In the following example, `colorSpace` is a `VideoColorSpace` object returned from {{domxref("VideoFrame")}}. The value of `transfer` is printed to the console. ```js let colorSpace = VideoFrame.colorSpace; console.log(colorSpace.transfer); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videocolorspace
data/mdn-content/files/en-us/web/api/videocolorspace/videocolorspace/index.md
--- title: "VideoColorSpace: VideoColorSpace() constructor" short-title: VideoColorSpace() slug: Web/API/VideoColorSpace/VideoColorSpace page-type: web-api-constructor browser-compat: api.VideoColorSpace.VideoColorSpace --- {{APIRef("WebCodecs API")}} The **`VideoColorSpace()`** constructor creates a new {{domxref("VideoColorSpace")}} object which represents a video color space. ## Syntax ```js-nolint new VideoColorSpace() new VideoColorSpace(options) ``` ### Parameters All values default to `null` when they are not present. - `options` {{optional_inline}} - : An object containing the following: - `primaries` {{optional_inline}} - : One of the following strings: - `"bt709"` - `"bt470bg"` - `"smpte170m"` - `transfer` {{optional_inline}} - : One of the following strings: - `"bt709"` - `"smpte170m"` - `"iec61966-2-1"` - `matrix` {{optional_inline}} - : One of the following strings: - `"rgb"` - `"bt709"` - `"bt470bg"` - `"smpte170m"` - `fullRange` {{optional_inline}} - : A {{jsxref("Boolean")}}, `true` if full-range color values are used in the video. ## Examples The following example creates a new `VideoColorSpace` object with {{domxref("VideoColorSpace.primaries")}} set to `"bt709"`, and {{domxref("VideoColorSpace.primaries")}} set to `true`. ```js const options = { primaries: "bt709", fullRange: true, }; const colorSpace = new VideoColorSpace(options); console.log(colorSpace); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videocolorspace
data/mdn-content/files/en-us/web/api/videocolorspace/matrix/index.md
--- title: "VideoColorSpace: matrix property" short-title: matrix slug: Web/API/VideoColorSpace/matrix page-type: web-api-instance-property browser-compat: api.VideoColorSpace.matrix --- {{DefaultAPISidebar("WebCodecs API")}} The **`matrix`** read-only property of the {{domxref("VideoColorSpace")}} interface returns the matrix coefficient of the video. Matrix coefficients describe the relationship between sample component values and color coordinates. ## Value A string containing one of the following values: - `"rgb"` - : Matrix coefficients used by sRGB. - `"bt709"` - : Matrix coefficients used by BT.709. - `"bt470bg"` - : Matrix coefficients used by BT.601 PAL. - `"smpte170m"` - : Matrix coefficients used by BT.601 NTSC. ## Examples In the following example, `colorSpace` is a `VideoColorSpace` object returned from {{domxref("VideoFrame")}}. The value of `matrix` is printed to the console. ```js let colorSpace = VideoFrame.colorSpace; console.log(colorSpace.matrix); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videocolorspace
data/mdn-content/files/en-us/web/api/videocolorspace/primaries/index.md
--- title: "VideoColorSpace: primaries property" short-title: primaries slug: Web/API/VideoColorSpace/primaries page-type: web-api-instance-property browser-compat: api.VideoColorSpace.primaries --- {{DefaultAPISidebar("WebCodecs API")}} The **`primaries`** read-only property of the {{domxref("VideoColorSpace")}} interface returns the color {{glossary("gamut")}} of the video. ## Value A string containing one of the following values: - `"bt709"` - : Color primaries used by BT.709 and sRGB. - `"bt470bg"` - : Color primaries used by BT.601 PAL. - `"smpte170m"` - : Color primaries used by BT.601 NTSC. ## Examples In the following example, `colorSpace` is a `VideoColorSpace` object returned from {{domxref("VideoFrame")}}. The value of `primaries` is printed to the console. ```js let colorSpace = VideoFrame.colorSpace; console.log(colorSpace.primaries); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videocolorspace
data/mdn-content/files/en-us/web/api/videocolorspace/fullrange/index.md
--- title: "VideoColorSpace: fullRange property" short-title: fullRange slug: Web/API/VideoColorSpace/fullRange page-type: web-api-instance-property browser-compat: api.VideoColorSpace.fullRange --- {{DefaultAPISidebar("WebCodecs API")}} The **`fullRange`** read-only property of the {{domxref("VideoColorSpace")}} interface returns `true` if full-range color values are used. ## Value A {{jsxref("Boolean")}}, `true` if full-range color values are used. ## Examples In the following example, `colorSpace` is a `VideoColorSpace` object returned from {{domxref("VideoFrame")}}. The value of `fullRange` is printed to the console. ```js let colorSpace = VideoFrame.colorSpace; console.log(colorSpace.fullRange); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0