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/serviceworkercontainer
data/mdn-content/files/en-us/web/api/serviceworkercontainer/controller/index.md
--- title: "ServiceWorkerContainer: controller property" short-title: controller slug: Web/API/ServiceWorkerContainer/controller page-type: web-api-instance-property browser-compat: api.ServiceWorkerContainer.controller --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`controller`** read-only property of the {{domxref("ServiceWorkerContainer")}} interface returns a {{domxref("ServiceWorker")}} object if its state is `activating` or `activated` (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns `null` if the request is a force refresh (_Shift_ + refresh) or if there is no active worker. ## Value A {{domxref("ServiceWorker")}} object. ## Examples ```js if ("serviceWorker" in navigator) { // Do a one-off check to see if a service worker's in control. if (navigator.serviceWorker.controller) { console.log( `This page is currently controlled by: ${navigator.serviceWorker.controller}`, ); } else { console.log("This page is not currently controlled by a service worker."); } } else { console.log("Service workers are not supported."); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkercontainer
data/mdn-content/files/en-us/web/api/serviceworkercontainer/getregistration/index.md
--- title: "ServiceWorkerContainer: getRegistration() method" short-title: getRegistration() slug: Web/API/ServiceWorkerContainer/getRegistration page-type: web-api-instance-method browser-compat: api.ServiceWorkerContainer.getRegistration --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`getRegistration()`** method of the {{domxref("ServiceWorkerContainer")}} interface gets a {{domxref("ServiceWorkerRegistration")}} object whose scope URL matches the provided client URL. The method returns a {{jsxref("Promise")}} that resolves to a {{domxref("ServiceWorkerRegistration")}} or `undefined`. ## Syntax ```js-nolint getRegistration() getRegistration(clientURL) ``` ### Parameters - `clientURL` {{optional_inline}} - : The registration whose scope matches this URL will be returned. Relative URLs are resolved with the current client as the base. If this parameter is not provided, the current client's URL will be used by default. ### Return value A {{jsxref("Promise")}} that resolves to a {{domxref("ServiceWorkerRegistration")}} object or `undefined`. ## Examples ```js navigator.serviceWorker.getRegistration("/app").then((registration) => { if (registration) { document.querySelector("#status").textContent = "ServiceWorkerRegistration found."; } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkercontainer
data/mdn-content/files/en-us/web/api/serviceworkercontainer/getregistrations/index.md
--- title: "ServiceWorkerContainer: getRegistrations() method" short-title: getRegistrations() slug: Web/API/ServiceWorkerContainer/getRegistrations page-type: web-api-instance-method browser-compat: api.ServiceWorkerContainer.getRegistrations --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`getRegistrations()`** method of the {{domxref("ServiceWorkerContainer")}} interface gets all {{domxref("ServiceWorkerRegistration")}}s associated with a `ServiceWorkerContainer`, in an array. The method returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("ServiceWorkerRegistration")}}. ## Syntax ```js-nolint getRegistrations() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves to an array of {{domxref("ServiceWorkerRegistration")}} objects. ## Examples ```js navigator.serviceWorker.getRegistrations().then((registrations) => { document.querySelector("#status").textContent = "ServiceWorkerRegistrations found."; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkercontainer
data/mdn-content/files/en-us/web/api/serviceworkercontainer/message_event/index.md
--- title: "ServiceWorkerContainer: message event" short-title: message slug: Web/API/ServiceWorkerContainer/message_event page-type: web-api-event browser-compat: api.ServiceWorkerContainer.message_event --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`message`** event is used in a page controlled by a service worker to receive messages from the service worker. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("message", (event) => {}); onmessage = (event) => {}; ``` ## Event type A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MessageEvent")}} ## Event properties _This interface also inherits properties from its parent, {{domxref("Event")}}._ - {{domxref("MessageEvent.data")}} {{ReadOnlyInline}} - : The data sent by the message emitter. - {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}} - : A string representing the origin of the message emitter. - {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}} - : A string representing a unique ID for the event. - {{domxref("MessageEvent.source")}} {{ReadOnlyInline}} - : A `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter. - {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}} - : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). ## Examples In this example the service worker get the client's ID from a [`fetch`](/en-US/docs/Web/API/ServiceWorkerGlobalScope/fetch_event) event and then sends it a message using [`Client.postMessage`](/en-US/docs/Web/API/Client/postMessage): ```js // service-worker.js async function messageClient(clientId) { const client = await clients.get(clientId); client.postMessage("Hi client!"); } addEventListener("fetch", (event) => { messageClient(event.clientId); event.respondWith(() => { // … }); }); ``` The client can receive the message by listening to the `message` event: ```js // main.js navigator.serviceWorker.addEventListener("message", (message) => { console.log(message); }); ``` Alternatively, the client can receive the message with the `onmessage` event handler: ```js // main.js navigator.serviceWorker.onmessage = (message) => { console.log(message); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkercontainer
data/mdn-content/files/en-us/web/api/serviceworkercontainer/ready/index.md
--- title: "ServiceWorkerContainer: ready property" short-title: ready slug: Web/API/ServiceWorkerContainer/ready page-type: web-api-instance-property browser-compat: api.ServiceWorkerContainer.ready --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`ready`** read-only property of the {{domxref("ServiceWorkerContainer")}} interface provides a way of delaying code execution until a service worker is active. It returns a {{jsxref("Promise")}} that will never reject, and which waits indefinitely until the {{domxref("ServiceWorkerRegistration")}} associated with the current page has an {{domxref("ServiceWorkerRegistration.active","active")}} worker. Once that condition is met, it resolves with the {{domxref("ServiceWorkerRegistration")}}. ## Value A {{jsxref("Promise")}} that will never reject, and which may eventually resolve with a {{domxref("ServiceWorkerRegistration")}}. ## Examples ```js if ("serviceWorker" in navigator) { navigator.serviceWorker.ready.then((registration) => { console.log(`A service worker is active: ${registration.active}`); // At this point, you can call methods that require an active // service worker, like registration.pushManager.subscribe() }); } else { console.error("Service workers are not supported."); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkercontainer
data/mdn-content/files/en-us/web/api/serviceworkercontainer/startmessages/index.md
--- title: "ServiceWorkerContainer: startMessages() method" short-title: startMessages() slug: Web/API/ServiceWorkerContainer/startMessages page-type: web-api-instance-method browser-compat: api.ServiceWorkerContainer.startMessages --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`startMessages()`** method of the {{domxref("ServiceWorkerContainer")}} interface explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via {{domxref("Client.postMessage()")}}). This can be used to react to sent messages earlier, even before that page's content has finished loading. ## Explanation By default, all messages sent from a page's controlling service worker to the page (using {{domxref("Client.postMessage()")}}) are queued while the page is loading, and get dispatched once the page's HTML document has been loaded and parsed (i.e. after the {{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}} event fires). It's possible to start dispatching these messages earlier by calling {{domxref("ServiceWorkerContainer.startMessages()")}}, for example if you've invoked a message handler using {{domxref("EventTarget.addEventListener()")}} before the page has finished loading, but want to start processing the messages right away. > **Note:** The messages start being sent automatically when setting the > handler directly using {{domxref("ServiceWorkerContainer.message_event", "onmessage")}}. In this you > don't need `startMessages()`. ## Syntax ```js-nolint startMessages() ``` ### Parameters None. ### Return value `undefined`. ## Examples ```js if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/sw.js").then(() => { console.log("Service Worker Registered"); }); } // … navigator.serviceWorker.addEventListener("message", (e) => { // … }); navigator.serviceWorker.startMessages(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkercontainer
data/mdn-content/files/en-us/web/api/serviceworkercontainer/error_event/index.md
--- title: "ServiceWorkerContainer: error event" short-title: error slug: Web/API/ServiceWorkerContainer/error_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.ServiceWorkerContainer.error_event --- {{APIRef("Service Workers API")}}{{Deprecated_header}}{{Non-standard_header}} The `error` event fires when an error occurs in the service worker. ## 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")}}. ## Example ```js navigator.serviceWorker.onerror = (errorevent) => { console.error(`received error message: ${errorevent.message}`); }; ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssstartingstylerule/index.md
--- title: CSSStartingStyleRule slug: Web/API/CSSStartingStyleRule page-type: web-api-interface status: - experimental browser-compat: api.CSSStartingStyleRule --- {{ APIRef("CSSOM") }}{{SeeCompatTable}} The **`CSSStartingStyleRule`** interface of the [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model) represents a CSS {{CSSxRef("@starting-style")}} at-rule. {{InheritanceDiagram}} ## Instance properties _This interface inherits properties from its parent, {{domxref("CSSGroupingRule")}}._ ## Instance methods _This interface inherits methods from its parent, {{domxref("CSSGroupingRule")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{CSSxRef("@starting-style")}} - [CSS transitions](/en-US/docs/Web/CSS/CSS_transitions) module - [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/idbcursor/index.md
--- title: IDBCursor slug: Web/API/IDBCursor page-type: web-api-interface browser-compat: api.IDBCursor --- {{APIRef("IndexedDB")}} > **Note:** Not to be confused with {{domxref("IDBCursorWithValue")}} which is just an **`IDBCursor`** interface with an additional **`value`** property. The **`IDBCursor`** interface of the [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) represents a [cursor](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology#cursor) for traversing or iterating over multiple records in a database. The cursor has a source that indicates which index or object store it is iterating over. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. The cursor enables an application to asynchronously process all the records in the cursor's range. You can have an unlimited number of cursors at the same time. You always get the same `IDBCursor` object representing a given cursor. Operations are performed on the underlying index or object store. {{AvailableInWorkers}} ## Instance properties > **Note:** {{domxref("IDBCursorWithValue")}} is an **`IDBCursor`** interface with an additional **`value`** property. - {{domxref("IDBCursor.source")}} {{ReadOnlyInline}} - : Returns the {{domxref("IDBObjectStore")}} or {{domxref("IDBIndex")}} that the cursor is iterating. This function never returns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active. - {{domxref("IDBCursor.direction")}} {{ReadOnlyInline}} - : Returns the direction of traversal of the cursor. See [Constants](#const_next) for possible values. - {{domxref("IDBCursor.key")}} {{ReadOnlyInline}} - : Returns the key for the record at the cursor's position. If the cursor is outside its range, this is set to `undefined`. The cursor's key can be any data type. - {{domxref("IDBCursor.primaryKey")}} {{ReadOnlyInline}} - : Returns the cursor's current effective primary key. If the cursor is currently being iterated or has iterated outside its range, this is set to `undefined`. The cursor's primary key can be any data type. - {{domxref("IDBCursor.request")}} {{ReadOnlyInline}} - : Returns the {{domxref("IDBRequest")}} that was used to obtain the cursor. ## Instance methods - {{domxref("IDBCursor.advance()")}} - : Sets the number of times a cursor should move its position forward. - {{domxref("IDBCursor.continue()")}} - : Advances the cursor to the next position along its direction, to the item whose key matches the optional `key` parameter. - {{domxref("IDBCursor.continuePrimaryKey()")}} - : Sets the cursor to the given index key and primary key given as arguments. - {{domxref("IDBCursor.delete()")}} - : Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position. This can be used to delete specific records. - {{domxref("IDBCursor.update()")}} - : Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, updates the value at the current position of the cursor in the object store. This can be used to update specific records. ## Constants {{Deprecated_Header}} > **Warning:** These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. ([Firefox bug 891944](https://bugzil.la/891944)) - `NEXT`: `"next"` : The cursor shows all records, including duplicates. It starts at the lower bound of the key range and moves upwards (monotonically increasing in the order of keys). - `NEXTUNIQUE` : `"nextunique"` : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the lower bound of the key range and moves upwards. - `PREV`: `"prev"` : The cursor shows all records, including duplicates. It starts at the upper bound of the key range and moves downwards (monotonically decreasing in the order of keys). - `PREVUNIQUE`: `"prevunique"` : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the upper bound of the key range and moves downwards. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([view example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/).) ```js function displayData() { const transaction = db.transaction(["rushAlbumList"], "readonly"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); cursor.continue(); } else { console.log("Entries all displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/source/index.md
--- title: "IDBCursor: source property" short-title: source slug: Web/API/IDBCursor/source page-type: web-api-instance-property browser-compat: api.IDBCursor.source --- {{APIRef("IndexedDB")}} The **`source`** read-only property of the {{domxref("IDBCursor")}} interface returns the {{domxref("IDBObjectStore")}} or {{domxref("IDBIndex")}} that the cursor is iterating over. This function never returns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active. {{AvailableInWorkers}} ## Value The {{domxref("IDBObjectStore")}} or {{domxref("IDBIndex")}} that the cursor is iterating over. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. Within each iteration we log the source of the cursor, which will log our {{domxref("IDBObjectStore")}} object to the console, something like this: ```json IDBObjectStore {autoIncrement: false, transaction: IDBTransaction, indexNames: DOMStringList, keyPath: "albumTitle", name: "rushAlbumList"…} ``` The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/)). ```js function displayData() { const transaction = db.transaction(["rushAlbumList"], "readonly"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); console.log(cursor.source); cursor.continue(); } else { console.log("Entries all displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/update/index.md
--- title: "IDBCursor: update() method" short-title: update() slug: Web/API/IDBCursor/update page-type: web-api-instance-method browser-compat: api.IDBCursor.update --- {{APIRef("IndexedDB")}} The **`update()`** method of the {{domxref("IDBCursor")}} interface returns an {{domxref("IDBRequest")}} object, and, in a separate thread, updates the value at the current position of the cursor in the object store. If the cursor points to a record that has just been deleted, a new record is created. Be aware that you can't call `update()` (or {{domxref("IDBCursor.delete()")}}) on cursors obtained from {{domxref("IDBIndex.openKeyCursor()")}}. For such needs, you have to use {{domxref("IDBIndex.openCursor()")}} instead. {{AvailableInWorkers}} ## Syntax ```js-nolint update(value) ``` ### Parameters - `value` - : The new value to be stored at the current position. ### Return value An {{domxref("IDBRequest")}} object on which subsequent events related to this operation are fired. If the operation is successful, the value of the request's {{domxref("IDBRequest.result", "result")}} property is the key for the updated record. ### Exceptions This method may raise a {{domxref("DOMException")}} of one of the following types: - `TransactionInactiveError` {{domxref("DOMException")}} - : Thrown if this IDBCursor's transaction is inactive. - `ReadOnlyError` {{domxref("DOMException")}} - : Thrown if the transaction mode is read-only. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the cursor was created using {{domxref("IDBindex.openKeyCursor")}}, is currently being iterated, or has iterated past its end. - `DataError` {{domxref("DOMException")}} - : Thrown if the underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this cursor's position. - `DataCloneError` {{domxref("DOMException")}} - : Thrown if the data being stored could not be cloned by the internal structured cloning algorithm. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. If the `albumTitle` of the current cursor is "A farewell to kings", we update year the album was released using `const request = cursor.update();`. Note that you cannot change primary keys using `cursor.update()`, hence us not changing the album title; this would ruin the integrity of the data. In such a situation, you would have to delete the record altogether and then add a new one using {{domxref("IDBObjectStore.add")}}. Note also that you can't directly put `cursor.value` into an update call, hence the below example using an intermediary `updateData` variable. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/)). ```js function updateResult() { list.textContent = ""; const transaction = db.transaction(["rushAlbumList"], "readwrite"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (cursor) { if (cursor.value.albumTitle === "A farewell to kings") { const updateData = cursor.value; updateData.year = 2050; const request = cursor.update(updateData); request.onsuccess = () => { console.log("A better album year?"); }; } const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); cursor.continue(); } else { console.log("Entries displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/advance/index.md
--- title: "IDBCursor: advance() method" short-title: advance() slug: Web/API/IDBCursor/advance page-type: web-api-instance-method browser-compat: api.IDBCursor.advance --- {{APIRef("IndexedDB")}} The **`advance()`** method of the {{domxref("IDBCursor")}} interface sets the number of times a cursor should move its position forward. {{AvailableInWorkers}} ## Syntax ```js-nolint advance(count) ``` ### Parameters - `count` - : The number of times to move the cursor forward. ### Return value None ({{jsxref("undefined")}}). ### Exceptions This method may raise a {{domxref("DOMException")}} of one of the following types: - `TransactionInactiveError` {{domxref("DOMException")}} - : Thrown if this IDBCursor's transaction is inactive. - {{jsxref("TypeError")}} - : Thrown if the value passed into the `count` parameter was zero or a negative number. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the cursor is currently being iterated or has iterated past its end. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through the records in the object store. Here we use `cursor.advance(2)` to jump 2 places forward each time, meaning that only every other result will be displayed. `advance()` works in a similar way to {{domxref("IDBCursor.continue")}}, except that it allows you to jump multiple records at a time, not just always go onto the next record. Note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/)). ```js function advanceResult() { list.textContent = ""; const transaction = db.transaction(["rushAlbumList"], "readonly"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); cursor.advance(2); } else { console.log("Every other entry displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/direction/index.md
--- title: "IDBCursor: direction property" short-title: direction slug: Web/API/IDBCursor/direction page-type: web-api-instance-property browser-compat: api.IDBCursor.direction --- {{ APIRef("IndexedDB") }} The **`direction`** read-only property of the {{domxref("IDBCursor")}} interface is a string that returns the direction of traversal of the cursor (set using {{domxref("IDBObjectStore.openCursor")}} for example). See the [Values](#values) section below for possible values. {{AvailableInWorkers}} ## Value A string indicating the direction in which the cursor is traversing the data. Possible values are: - `next` - : This direction causes the cursor to be opened at the start of the source. - `nextunique` - : This direction causes the cursor to be opened at the start of the source. For every key with duplicate values, only the first record is yielded. - `prev` - : This direction causes the cursor to be opened at the end of the source. - `prevunique` - : This direction causes the cursor to be opened at the end of the source. For every key with duplicate values, only the first record is yielded. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. Within each iteration we log the direction of the cursor, something like this: ```plain prev ``` > **Note:** we can't change the direction of travel of the cursor using > the `direction` property, as it is read-only. We specify the direction of > travel using the 2nd argument of {{domxref("IDBObjectStore.openCursor")}}. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/)). ```js function backwards() { list.textContent = ""; const transaction = db.transaction(["rushAlbumList"], "readonly"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor(null, "prev").onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); console.log(cursor.direction); cursor.continue(); } else { console.log("Entries displayed backwards."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/primarykey/index.md
--- title: "IDBCursor: primaryKey property" short-title: primaryKey slug: Web/API/IDBCursor/primaryKey page-type: web-api-instance-property browser-compat: api.IDBCursor.primaryKey --- {{APIRef("IDBCursor")}} The **`primaryKey`** read-only property of the {{domxref("IDBCursor")}} interface returns the cursor's current effective key. If the cursor is currently being iterated or has iterated outside its range, this is set to undefined. The cursor's primary key can be any data type. {{AvailableInWorkers}} ## Value A value of any data type. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. Within each iteration we log the primary key of the cursor to the console, something like this (its the album title in each case, which is our primarykey): ```plain Hemispheres ``` The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/)). ```js function displayData() { const transaction = db.transaction(["rushAlbumList"], "readonly"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); console.log(cursor.primaryKey); cursor.continue(); } else { console.log("Entries all displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/request/index.md
--- title: "IDBCursor: request property" short-title: request slug: Web/API/IDBCursor/request page-type: web-api-instance-property browser-compat: api.IDBCursor.request --- {{APIRef("IndexedDB")}} The **`request`** read-only property of the {{domxref("IDBCursor")}} interface returns the {{domxref("IDBRequest")}} used to obtain the cursor. {{AvailableInWorkers}} ## Value An {{domxref("IDBRequest")}} object instance. ## Examples When you open a cursor, the `request` property is then available on that cursor object, to tell you what request object the cursor originated from. For example: ```js function displayData() { list.textContent = ""; const transaction = db.transaction(["rushAlbumList"], "readonly"); const objectStore = transaction.objectStore("rushAlbumList"); const request = objectStore.openCursor(); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); console.log(cursor.request); cursor.continue(); } else { console.log("Entries all displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/delete/index.md
--- title: "IDBCursor: delete() method" short-title: delete() slug: Web/API/IDBCursor/delete page-type: web-api-instance-method browser-compat: api.IDBCursor.delete --- {{APIRef("IndexedDB")}} The **`delete()`** method of the {{domxref("IDBCursor")}} interface returns an {{domxref("IDBRequest")}} object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position. Once the record is deleted, the cursor's value is set to null. Be aware that you can't call `delete()` (or {{domxref("IDBCursor.update()")}}) on cursors obtained from {{domxref("IDBIndex.openKeyCursor()")}}. For such needs, you have to use {{domxref("IDBIndex.openCursor()")}} instead. {{AvailableInWorkers}} ## Syntax ```js-nolint delete() ``` ### Parameters None. ### Return value An {{domxref("IDBRequest")}} object on which subsequent events related to this operation are fired. If the operation is successful, the value of the request's {{domxref("IDBRequest.result", "result")}} property is `undefined`. ### Exceptions This method may raise a {{domxref("DOMException")}} of one of the following types: - `TransactionInactiveError` {{domxref("DOMException")}} - : Thrown if this IDBCursor's transaction is inactive. - `ReadOnlyError` {{domxref("DOMException")}} - : Thrown if the transaction mode is read-only. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the cursor was created using {{domxref("IDBindex.openKeyCursor")}}, is currently being iterated, or has iterated past its end. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. If the `albumTitle` of the current cursor is "Grace under pressure", we delete that entire record using `const request = cursor.delete();`. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/)). ```js function deleteResult() { list.textContent = ""; const transaction = db.transaction(["rushAlbumList"], "readwrite"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (cursor) { if (cursor.value.albumTitle === "Grace under pressure") { const request = cursor.delete(); request.onsuccess = () => { console.log( "Deleted that mediocre album from 1984. Even Power windows is better.", ); }; } else { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); } cursor.continue(); } else { console.log("Entries displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/continueprimarykey/index.md
--- title: "IDBCursor: continuePrimaryKey() method" short-title: continuePrimaryKey() slug: Web/API/IDBCursor/continuePrimaryKey page-type: web-api-instance-method browser-compat: api.IDBCursor.continuePrimaryKey --- {{APIRef("IndexedDB")}} The **`continuePrimaryKey()`** method of the {{domxref("IDBCursor")}} interface advances the cursor to the item whose key matches the key parameter as well as whose primary key matches the primary key parameter. A typical use case, is to resume the iteration where a previous cursor has been closed, without having to compare the keys one by one. Calling this method more than once before new cursor data has been loaded - for example, calling `continuePrimaryKey()` twice from the same onsuccess handler \- results in an `InvalidStateError` being thrown on the second call because the cursor's got value flag has been unset. This method is only valid for cursors coming from an index. Using it for cursors coming from an object store will throw an error. {{AvailableInWorkers}} ## Syntax ```js-nolint continuePrimaryKey(key, primaryKey) ``` ### Parameters - `key` - : The key to position the cursor at. - `primaryKey` - : The primary key to position the cursor at. ### Return value None ({{jsxref("undefined")}}). ### Exceptions This method may raise a {{domxref("DOMException")}} of one of the following types: - `TransactionInactiveError` {{domxref("DOMException")}} - : Thrown if this IDBCursor's transaction is inactive. - `DataError` {{domxref("DOMException")}} - : Thrown if the key parameter has any of the following conditions: - The key is not a valid key. - The key is less than or equal to this cursor's position and the cursor's direction is `next` or `nextunique`. - The key is greater than or equal to this cursor's position and this cursor's direction is `prev` or `prevunique`. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the cursor is currently being iterated or has iterated past its end. - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if the cursor's direction is not `prev` or `next`. ## Examples here's how you can resume an iteration of all articles tagged with `"javascript"` since your last visit: ```js let request = articleStore.index("tag").openCursor(); let count = 0; let unreadList = []; request.onsuccess = (event) => { let cursor = event.target.result; if (!cursor) { return; } let lastPrimaryKey = getLastIteratedArticleId(); if (lastPrimaryKey > cursor.primaryKey) { cursor.continuePrimaryKey("javascript", lastPrimaryKey); return; } // update lastIteratedArticleId setLastIteratedArticleId(cursor.primaryKey); // preload 5 articles into the unread list; unreadList.push(cursor.value); if (++count < 5) { cursor.continue(); } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/key/index.md
--- title: "IDBCursor: key property" short-title: key slug: Web/API/IDBCursor/key page-type: web-api-instance-property browser-compat: api.IDBCursor.key --- {{APIRef("IndexedDB")}} The **`key`** read-only property of the {{domxref("IDBCursor")}} interface returns the key for the record at the cursor's position. If the cursor is outside its range, this is set to undefined. The cursor's key can be any data type. {{AvailableInWorkers}} ## Value A value of any type. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. Within each iteration we log the key of the cursor to the console, something like this (its the album title in each case, which is our key). The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/)). ```js function displayData() { const transaction = db.transaction(["rushAlbumList"], "readonly"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); console.log(cursor.key); cursor.continue(); } else { console.log("Entries all displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api/idbcursor
data/mdn-content/files/en-us/web/api/idbcursor/continue/index.md
--- title: "IDBCursor: continue() method" short-title: continue() slug: Web/API/IDBCursor/continue page-type: web-api-instance-method browser-compat: api.IDBCursor.continue --- {{APIRef("IndexedDB")}} The **`continue()`** method of the {{domxref("IDBCursor")}} interface advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. If no key is specified, the cursor advances to the immediate next position, based on its direction. {{AvailableInWorkers}} ## Syntax ```js-nolint continue() continue(key) ``` ### Parameters - `key` {{optional_inline}} - : The key to position the cursor at. ### Return value None ({{jsxref("undefined")}}). ### Exceptions This method may raise a {{domxref("DOMException")}} of one of the following types: - `TransactionInactiveError` {{domxref("DOMException")}} - : Thrown if this IDBCursor's transaction is inactive. - `DataError` {{domxref("DOMException")}} - : Thrown if the key parameter has any of the following conditions: - The key is not a valid key. - The key is less than or equal to this cursor's position, and the cursor's direction is `next` or `nextunique`. - The key is greater than or equal to this cursor's position and this cursor's direction is `prev` or `prevunique`. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the cursor is currently being iterated or has iterated past its end. ## Examples In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/)). ```js function displayData() { const transaction = db.transaction(["rushAlbumList"], "readonly"); const objectStore = transaction.objectStore("rushAlbumList"); objectStore.openCursor().onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const listItem = document.createElement("li"); listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`; list.appendChild(listItem); cursor.continue(); } else { console.log("Entries all displayed."); } }; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB) - Starting transactions: {{domxref("IDBDatabase")}} - Using transactions: {{domxref("IDBTransaction")}} - Setting a range of keys: {{domxref("IDBKeyRange")}} - Retrieving and making changes to your data: {{domxref("IDBObjectStore")}} - Using cursors: {{domxref("IDBCursor")}} - Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/trustedscript/index.md
--- title: TrustedScript slug: Web/API/TrustedScript page-type: web-api-interface browser-compat: api.TrustedScript --- {{DefaultAPISidebar("Trusted Types API")}} The **`TrustedScript`** interface of the {{domxref('Trusted Types API')}} represents a string with an uncompiled script body that a developer can insert into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks) that might execute the script. These objects are created via {{domxref("TrustedTypePolicy.createScript","TrustedTypePolicy.createScript()")}} and therefore have no constructor. The value of a **TrustedScript** object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed. ## Instance methods - {{domxref("TrustedScript.toJSON()")}} - : Returns a JSON representation of the stored data. - {{domxref("TrustedScript.toString()")}} - : A string containing the sanitized script. ## Examples The constant `sanitized` is an object created via a Trusted Types policy. ```js const sanitized = scriptPolicy.createScript("eval('2 + 2')"); console.log(sanitized); /* a TrustedScript object */ ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types](https://web.dev/articles/trusted-types)
0
data/mdn-content/files/en-us/web/api/trustedscript
data/mdn-content/files/en-us/web/api/trustedscript/tostring/index.md
--- title: "TrustedScript: toString() method" short-title: toString() slug: Web/API/TrustedScript/toString page-type: web-api-instance-method browser-compat: api.TrustedScript.toString --- {{DefaultAPISidebar("Trusted Types API")}} The **`toString()`** method of the {{domxref("TrustedScript")}} interface returns a string which may safely inserted into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks). ## Syntax ```js-nolint toString() ``` ### Parameters None. ### Return value A string containing the sanitized script. ## Examples The constant `sanitized` is an object created via a Trusted Types policy. The `toString()` method returns a string to safely execute as a script. ```js const sanitized = scriptPolicy.createScript("eval('2 + 2')"); console.log(sanitized.toString()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/trustedscript
data/mdn-content/files/en-us/web/api/trustedscript/tojson/index.md
--- title: "TrustedScript: toJSON() method" short-title: toJSON() slug: Web/API/TrustedScript/toJSON page-type: web-api-instance-method browser-compat: api.TrustedScript.toJSON --- {{DefaultAPISidebar("Trusted Types API")}} The **`toJSON()`** method of the {{domxref("TrustedScript")}} interface returns a JSON representation of the stored data. ## Syntax ```js-nolint toJSON() ``` ### Parameters None. ### Return value A string containing a JSON representation of the stored data. ## Examples The constant `sanitized` is an object created via a Trusted Types policy. The `toString()` method returns a string to safely execute as a script. ```js const sanitized = scriptPolicy.createScript("eval('2 + 2')"); console.log(sanitized.toJSON()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/presentation_api/index.md
--- title: Presentation API slug: Web/API/Presentation_API page-type: web-api-overview status: - experimental browser-compat: api.Presentation --- {{securecontext_header}}{{SeeCompatTable}}{{DefaultAPISidebar("Presentation API")}} The Presentation API lets a {{Glossary("user agent")}} (such as a Web browser) effectively display web content through large presentation devices such as projectors and network-connected televisions. Supported types of multimedia devices include both displays which are wired using HDMI, DVI, or the like, or wireless, using [DLNA](https://www.dlna.org/), [Chromecast](https://developers.google.com/cast/), [AirPlay](https://developer.apple.com/airplay/), or [Miracast](https://www.wi-fi.org/discover-wi-fi/miracast). ![1-UA mode loaded the Controlling and Presenting pages together before outputting to displays. 2-UA mode loaded them separately using the Presentation Control Protocol.](presentation_mode_illustration.png) In general, a web page uses the Presentation Controller API to specify the web content to be rendered on presentation device and initiate the presentation session. With Presentation Receiver API, the presenting web content obtains the session status. With providing both the controller page and the receiver one with a messaged-based channel, a Web developer can implement the interaction between these two pages. Depending on the connection mechanism provided by the presentation device, any controller- and receiver page can be rendered by the same user agent, or by separated user agents. - For 1-UA mode devices, both pages are loaded by the same user agent. However, rendering result of the receiver page will be sent to the presentation device via supported remote rendering protocol. - For 2-UAs mode device, the receiver page is loaded directly on the presentation device. Controlling user agent communicates with presentation device via supported presentation control protocol, to control the presentation session and to transmit the message between two pages. ## Interfaces - {{domxref("Presentation")}} - : In controlling browsing context, the `Presentation` interface provides a mechanism to override the browser default behavior of launching presentation to external screen. In receiving browsing context, `Presentation` interface provides the access to the available presentation connections. - {{domxref("PresentationRequest")}} - : Initiates or reconnects to a presentation made by a controlling browsing context. - {{domxref("PresentationAvailability")}} - : A [PresentationAvailability](/en-US/docs/Web/API/PresentationAvailability) object is associated with available presentation displays and represents the _presentation display availability_ for a presentation request. - {{domxref("PresentationConnectionAvailableEvent")}} - : The `PresentationConnectionAvailableEvent` is fired on a [`PresentationRequest`](/en-US/docs/Web/API/PresentationRequest) when a connection associated with the object is created. - {{domxref("PresentationConnection")}} - : Each presentation connection is represented by a [PresentationConnection](/en-US/docs/Web/API/PresentationConnection) object. - {{domxref("PresentationConnectionCloseEvent")}} - : A `PresentationConnectionCloseEvent` is fired when a presentation connection enters a `closed` state. - {{domxref("PresentationReceiver")}} - : The [PresentationReceiver](/en-US/docs/Web/API/PresentationReceiver) allows a receiving browsing context to access the controlling browsing contexts and communicate with them. - {{domxref("PresentationConnectionList")}} - : `PresentationConnectionList` represents the collection of non-terminated presentation connections. It is also a monitor for the event of new available presentation connection. ## Example Example codes below highlight the usage of main features of the Presentation API: `controller.html` implements the controller and `presentation.html` implements the presentation. Both pages are served from the domain `https://example.org` (`https://example.org/controller.html` and `https://example.org/presentation.html`). These examples assume that the controlling page is managing one presentation at a time. Please refer to the comments in the code examples for further details. ### Monitor availability of presentation displays In `controller.html`: ```html <button id="presentBtn" style="display: none;">Present</button> <script> // The Present button is visible if at least one presentation display is available const presentBtn = document.getElementById("presentBtn"); // It is also possible to use relative presentation URL e.g. "presentation.html" const presUrls = [ "https://example.com/presentation.html", "https://example.net/alternate.html", ]; // Show or hide present button depending on display availability const handleAvailabilityChange = (available) => { presentBtn.style.display = available ? "inline" : "none"; }; // Promise is resolved as soon as the presentation display availability is known. const request = new PresentationRequest(presUrls); request .getAvailability() .then((availability) => { // availability.value may be kept up-to-date by the controlling UA as long // as the availability object is alive. It is advised for the web developers // to discard the object as soon as it's not needed. handleAvailabilityChange(availability.value); availability.onchange = () => { handleAvailabilityChange(availability.value); }; }) .catch(() => { // Availability monitoring is not supported by the platform, so discovery of // presentation displays will happen only after request.start() is called. // Pretend the devices are available for simplicity; or, one could implement // a third state for the button. handleAvailabilityChange(true); }); </script> ``` ### Starting a new presentation In `controller.html`: ```html <script> presentBtn.onclick = () => { // Start new presentation. request .start() // The connection to the presentation will be passed to setConnection on success. .then(setConnection); // Otherwise, the user canceled the selection dialog or no screens were found. }; </script> ``` ### Reconnect to a presentation In the `controller.html` file: ```html <button id="reconnectBtn" style="display: none;">Reconnect</button> <script> const reconnect = () => { // read presId from localStorage if exists const presId = localStorage["presId"]; // presId is mandatory when reconnecting to a presentation. if (presId) { request .reconnect(presId) // The new connection to the presentation will be passed to // setConnection on success. .then(setConnection); // No connection found for presUrl and presId, or an error occurred. } }; // On navigation of the controller, reconnect automatically. document.addEventListener("DOMContentLoaded", reconnect); // Or allow manual reconnection. reconnectBtn.onclick = reconnect; </script> ``` ### Presentation initiation by the controlling UA In the `controller.html` file: ```html <script> navigator.presentation.defaultRequest = new PresentationRequest(presUrls); navigator.presentation.defaultRequest.onconnectionavailable = (evt) => { setConnection(evt.connection); }; </script> ``` Setting `presentation.defaultRequest` allows the page to specify the `PresentationRequest` to use when the controlling UA initiates a presentation. ### Monitor connection's state and exchange data In `controller.html`: ```html <button id="disconnectBtn" style="display: none;">Disconnect</button> <button id="stopBtn" style="display: none;">Stop</button> <button id="reconnectBtn" style="display: none;">Reconnect</button> <script> let connection; // The Disconnect and Stop buttons are visible if there is a connected presentation const stopBtn = document.querySelector("#stopBtn"); const reconnectBtn = document.querySelector("#reconnectBtn"); const disconnectBtn = document.querySelector("#disconnectBtn"); stopBtn.onclick = () => { connection?.terminate(); }; disconnectBtn.onclick = () => { connection?.close(); }; function setConnection(newConnection) { // Disconnect from existing presentation, if not attempting to reconnect if ( connection && connection !== newConnection && connection.state !== "closed" ) { connection.onclose = undefined; connection.close(); } // Set the new connection and save the presentation ID connection = newConnection; localStorage["presId"] = connection.id; function showConnectedUI() { // Allow the user to disconnect from or terminate the presentation stopBtn.style.display = "inline"; disconnectBtn.style.display = "inline"; reconnectBtn.style.display = "none"; } function showDisconnectedUI() { disconnectBtn.style.display = "none"; stopBtn.style.display = "none"; reconnectBtn.style.display = localStorage["presId"] ? "inline" : "none"; } // Monitor the connection state connection.onconnect = () => { showConnectedUI(); // Register message handler connection.onmessage = (message) => { console.log(`Received message: ${message.data}`); }; // Send initial message to presentation page connection.send("Say hello"); }; connection.onclose = () => { connection = null; showDisconnectedUI(); }; connection.onterminate = () => { // Remove presId from localStorage if exists delete localStorage["presId"]; connection = null; showDisconnectedUI(); }; } </script> ``` ### Monitor available connection(s) and say hello In `presentation.html`: ```js const addConnection = (connection) => { connection.onmessage = (message) => { if (message.data === "Say hello") connection.send("hello"); }; }; navigator.presentation.receiver.connectionList.then((list) => { list.connections.forEach((connection) => { addConnection(connection); }); list.onconnectionavailable = (evt) => { addConnection(evt.connection); }; }); ``` ### Passing locale information with a message In the `controller.html` file: ```html <script> connection.send('{"string": "你好,世界!", "lang": "zh-CN"}'); connection.send('{"string": "こんにちは、世界!", "lang": "ja"}'); connection.send('{"string": "안녕하세요, 세계!", "lang": "ko"}'); connection.send('{"string": "Hello, world!", "lang": "en-US"}'); </script> ``` In the `presentation.html` file: ```html <script> connection.onmessage = (message) => { const messageObj = JSON.parse(message.data); const spanElt = document.createElement("SPAN"); spanElt.lang = messageObj.lang; spanElt.textContent = messageObj.string; document.body.appendChild(spanElt); }; </script> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also [Presentation API polyfill](https://mediascape.github.io/presentation-api-polyfill/) contains a JavaScript polyfill of the [Presentation API](https://w3c.github.io/presentation-api/) specification under standardization within the [Second Screen Working Group](https://www.w3.org/2014/secondscreen/) at W3C. The polyfill is mostly intended for exploring how the Presentation API may be implemented on top of different presentation mechanisms.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/intersectionobserverentry/index.md
--- title: IntersectionObserverEntry slug: Web/API/IntersectionObserverEntry page-type: web-api-interface browser-compat: api.IntersectionObserverEntry --- {{APIRef("Intersection Observer API")}} The **`IntersectionObserverEntry`** interface of the [Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API) describes the intersection between the target element and its root container at a specific moment of transition. Instances of `IntersectionObserverEntry` are delivered to an {{domxref("IntersectionObserver")}} callback in its `entries` parameter; otherwise, these objects can only be obtained by calling {{domxref("IntersectionObserver.takeRecords()")}}. ## Instance properties - {{domxref("IntersectionObserverEntry.boundingClientRect")}} {{ReadOnlyInline}} - : Returns the bounds rectangle of the target element as a {{domxref("DOMRectReadOnly")}}. The bounds are computed as described in the documentation for {{domxref("Element.getBoundingClientRect()")}}. - {{domxref("IntersectionObserverEntry.intersectionRatio")}} {{ReadOnlyInline}} - : Returns the ratio of the `intersectionRect` to the `boundingClientRect`. - {{domxref("IntersectionObserverEntry.intersectionRect")}} {{ReadOnlyInline}} - : Returns a {{domxref("DOMRectReadOnly")}} representing the target's visible area. - {{domxref("IntersectionObserverEntry.isIntersecting")}} {{ReadOnlyInline}} - : A Boolean value which is `true` if the target element intersects with the intersection observer's root. If this is `true`, then, the `IntersectionObserverEntry` describes a transition into a state of intersection; if it's `false`, then you know the transition is from intersecting to not-intersecting. - {{domxref("IntersectionObserverEntry.rootBounds")}} {{ReadOnlyInline}} - : Returns a {{domxref("DOMRectReadOnly")}} for the intersection observer's root. - {{domxref("IntersectionObserverEntry.target")}} {{ReadOnlyInline}} - : The {{domxref("Element")}} whose intersection with the root changed. - {{domxref("IntersectionObserverEntry.time")}} {{ReadOnlyInline}} - : A {{domxref("DOMHighResTimeStamp")}} indicating the time at which the intersection was recorded, relative to the `IntersectionObserver`'s [time origin](/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin). ## Instance methods _This interface has no methods._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/intersectionobserverentry
data/mdn-content/files/en-us/web/api/intersectionobserverentry/rootbounds/index.md
--- title: "IntersectionObserverEntry: rootBounds property" short-title: rootBounds slug: Web/API/IntersectionObserverEntry/rootBounds page-type: web-api-instance-property browser-compat: api.IntersectionObserverEntry.rootBounds --- {{APIRef("Intersection Observer API")}} The {{domxref("IntersectionObserverEntry")}} interface's read-only **`rootBounds`** property is a {{domxref("DOMRectReadOnly")}} corresponding to the {{domxref("IntersectionObserverEntry.target", "target")}}'s root intersection rectangle, offset by the {{domxref("IntersectionObserver.rootMargin")}} if one is specified. ## Value A {{domxref("DOMRectReadOnly")}} which describes the root intersection rectangle. For roots which are the {{domxref("Document")}}'s viewport, this rectangle is the bounds rectangle of the entire document. Otherwise, it's the bounds of the root element. This rectangle is offset by the values in {{domxref("IntersectionObserver.rootMargin")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/intersectionobserverentry
data/mdn-content/files/en-us/web/api/intersectionobserverentry/intersectionratio/index.md
--- title: "IntersectionObserverEntry: intersectionRatio property" short-title: intersectionRatio slug: Web/API/IntersectionObserverEntry/intersectionRatio page-type: web-api-instance-property browser-compat: api.IntersectionObserverEntry.intersectionRatio --- {{APIRef("Intersection Observer API")}} The {{domxref("IntersectionObserverEntry")}} interface's read-only **`intersectionRatio`** property tells you how much of the target element is currently visible within the root's intersection ratio, as a value between 0.0 and 1.0. ## Value A number between 0.0 and 1.0 which indicates how much of the target element is actually visible within the root's intersection rectangle. More precisely, this value is the ratio of the area of the intersection rectangle ({{domxref("IntersectionObserverEntry.intersectionRect", "intersectionRect")}}) to the area of the target's bounds rectangle ({{domxref("IntersectionObserverEntry.boundingClientRect", "boundingClientRect")}}). If the area of the target's bounds rectangle is zero, the returned value is 1 if {{domxref("IntersectionObserverEntry.isIntersecting", "isIntersecting")}} is `true` or 0 if not. ## Examples In this simple example, an intersection callback sets each target element's {{cssxref("opacity")}} to the intersection ratio of that element with the root. ```js function intersectionCallback(entries) { entries.forEach((entry) => { entry.target.style.opacity = entry.intersectionRatio; }); } ``` To see a more concrete example, take a look at [Handling intersection changes](/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility#handling_intersection_changes). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/intersectionobserverentry
data/mdn-content/files/en-us/web/api/intersectionobserverentry/target/index.md
--- title: "IntersectionObserverEntry: target property" short-title: target slug: Web/API/IntersectionObserverEntry/target page-type: web-api-instance-property browser-compat: api.IntersectionObserverEntry.target --- {{APIRef("Intersection Observer API")}} The {{domxref("IntersectionObserverEntry")}} interface's read-only **`target`** property indicates which targeted {{domxref("Element")}} has changed its amount of intersection with the intersection root. ## Value The `IntersectionObserverEntry`'s `target` property specifies which {{domxref("Element")}} previously targeted by calling {{domxref("IntersectionObserver.observe()")}} experienced a change in intersection with the root. ## Examples In this simple example, each targeted element's {{cssxref("opacity")}} is set to its {{domxref("IntersectionObserverEntry.intersectionRatio", "intersectionRatio")}}. ```js function intersectionCallback(entries) { entries.forEach((entry) => { entry.target.style.opacity = entry.intersectionRatio; }); } ``` To see a more concrete example, take a look at [Handling intersection changes](/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility#handling_intersection_changes). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/intersectionobserverentry
data/mdn-content/files/en-us/web/api/intersectionobserverentry/boundingclientrect/index.md
--- title: "IntersectionObserverEntry: boundingClientRect property" short-title: boundingClientRect slug: Web/API/IntersectionObserverEntry/boundingClientRect page-type: web-api-instance-property browser-compat: api.IntersectionObserverEntry.boundingClientRect --- {{APIRef("Intersection Observer API")}} The {{domxref("IntersectionObserverEntry")}} interface's read-only **`boundingClientRect`** property returns a {{domxref("DOMRectReadOnly")}} which in essence describes a rectangle describing the smallest rectangle that contains the entire target element. ## Value A {{domxref("DOMRectReadOnly")}} which describes the smallest rectangle that contains every part of the target element whose intersection change is being described. This value is obtained using the same algorithm as {{domxref("Element.getBoundingClientRect()")}}, so refer to that article for details on precisely what is done to obtain this rectangle and what is and is not included within its bounds. In the general case, however, it's safe to think of this as the bounds rectangle of the target element. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/intersectionobserverentry
data/mdn-content/files/en-us/web/api/intersectionobserverentry/isintersecting/index.md
--- title: "IntersectionObserverEntry: isIntersecting property" short-title: isIntersecting slug: Web/API/IntersectionObserverEntry/isIntersecting page-type: web-api-instance-property browser-compat: api.IntersectionObserverEntry.isIntersecting --- {{APIRef("Intersection Observer API")}} The {{domxref("IntersectionObserverEntry")}} interface's read-only **`isIntersecting`** property is a Boolean value which is `true` if the target element intersects with the intersection observer's root. If this is `true`, then, the `IntersectionObserverEntry` describes a transition into a state of intersection; if it's `false`, then you know the transition is from intersecting to not-intersecting. ## Value A Boolean value which indicates whether the {{domxref("IntersectionObserverEntry.target", "target")}} element has transitioned into a state of intersection (`true`) or out of a state of intersection (`false`). ## Examples In this simple example, an intersection callback is used to update a counter of how many targeted elements are currently intersecting with the {{domxref("IntersectionObserver.root", "intersection root", "", 1)}}. ```js function intersectionCallback(entries) { entries.forEach((entry) => { if (entry.isIntersecting) { intersectingCount += 1; } else { intersectingCount -= 1; } }); } ``` To see a more concrete example, take a look at [Handling intersection changes](/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility#handling_intersection_changes). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/intersectionobserverentry
data/mdn-content/files/en-us/web/api/intersectionobserverentry/intersectionrect/index.md
--- title: "IntersectionObserverEntry: intersectionRect property" short-title: intersectionRect slug: Web/API/IntersectionObserverEntry/intersectionRect page-type: web-api-instance-property browser-compat: api.IntersectionObserverEntry.intersectionRect --- {{APIRef("Intersection Observer API")}} The {{domxref("IntersectionObserverEntry")}} interface's read-only **`intersectionRect`** property is a {{domxref("DOMRectReadOnly")}} object which describes the smallest rectangle that contains the entire portion of the target element which is currently visible within the intersection root. ## Value A {{domxref("DOMRectReadOnly")}} which describes the part of the target element that's currently visible within the root's intersection rectangle. This rectangle is computed by taking the intersection of {{domxref("IntersectionObserverEntry", "boundingClientRect")}} with each of the {{domxref("IntersectionObserverEntry.target", "target")}}'s ancestors' clip rectangles, with the exception of the intersection {{domxref("IntersectionObserver.root", "root")}} itself. ## Examples In this simple example, an intersection callback stores the intersection rectangle for later use by the code that draws the target elements' contents, so that only the visible area is redrawn. ```js function intersectionCallback(entries) { entries.forEach((entry) => { refreshZones.push({ element: entry.target, rect: entry.intersectionRect, }); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/intersectionobserverentry
data/mdn-content/files/en-us/web/api/intersectionobserverentry/time/index.md
--- title: "IntersectionObserverEntry: time property" short-title: time slug: Web/API/IntersectionObserverEntry/time page-type: web-api-instance-property browser-compat: api.IntersectionObserverEntry.time --- {{APIRef("Intersection Observer API")}} The {{domxref("IntersectionObserverEntry")}} interface's read-only **`time`** property is a {{domxref("DOMHighResTimeStamp")}} that indicates the time at which the intersection change occurred relative to the time at which the document was created. ## Value A {{domxref("DOMHighResTimeStamp")}} which indicates the time at which the {{domxref("IntersectionObserverEntry.target", "target")}} element experienced the intersection change described by the `IntersectionObserverEntry`. The time is specified in milliseconds since the creation of the containing document. ## Examples See [Timing element visibility with the Intersection Observer API](/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility) for a complete example which uses the `time` property to track how long elements are visible to the user. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmloptionscollection/index.md
--- title: HTMLOptionsCollection slug: Web/API/HTMLOptionsCollection page-type: web-api-interface browser-compat: api.HTMLOptionsCollection --- {{ APIRef("HTML DOM") }} The **`HTMLOptionsCollection`** interface represents a collection of [`<option>`](/en-US/docs/Web/HTML/Element/option) HTML elements (in document order) and offers methods and properties for selecting from the list as well as optionally altering its items. This object is returned only by the `options` property of [select](/en-US/docs/Web/API/HTMLSelectElement). {{InheritanceDiagram}} ## Instance properties - `length` - : `unsigned long`. As optionally allowed by the spec, this property isn't read-only. You can either remove options from the end by lowering the value, or add blank options at the end by raising the value. Mozilla allows this, while other implementations could potentially throw a [DOMException](/en-US/docs/Web/API/DOMException). ## Instance methods _This interface inherits the methods of its parent, [`HTMLCollection`](/en-US/docs/Web/API/HTMLCollection)._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTMLCollection](/en-US/docs/Web/API/HTMLCollection)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmldataelement/index.md
--- title: HTMLDataElement slug: Web/API/HTMLDataElement page-type: web-api-interface browser-compat: api.HTMLDataElement --- {{APIRef("HTML DOM")}} The **`HTMLDataElement`** interface provides special properties (beyond the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating {{HTMLElement("data")}} elements. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLDataElement.value")}} - : A string reflecting the [`value`](/en-US/docs/Web/HTML/Element/data#value) HTML attribute, containing a machine-readable form of the element's value. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{HTMLElement("data")}}.
0
data/mdn-content/files/en-us/web/api/htmldataelement
data/mdn-content/files/en-us/web/api/htmldataelement/value/index.md
--- title: "HTMLDataElement: value property" short-title: value slug: Web/API/HTMLDataElement/value page-type: web-api-instance-property browser-compat: api.HTMLDataElement.value --- {{APIRef("HTML DOM")}} The **`value`** property of the {{domxref("HTMLDataElement")}} interface returns a string reflecting the [`value`](/en-US/docs/Web/HTML/Element/data#value) HTML attribute. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/web_storage_api/index.md
--- title: Web Storage API slug: Web/API/Web_Storage_API page-type: web-api-overview browser-compat: - api.Window.localStorage - api.Window.sessionStorage --- {{DefaultAPISidebar("Web Storage API")}} The **Web Storage API** provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using {{glossary("cookie", "cookies")}}. ## Web Storage concepts and usage The two mechanisms within Web Storage are as follows: - `sessionStorage` maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores). - Stores data only for a session, meaning that the data is stored until the browser (or tab) is closed. - Data is never transferred to the server. - Storage limit is larger than a cookie (at most 5MB). - `localStorage` does the same thing, but persists even when the browser is closed and reopened. - Stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data. - Storage limit is the maximum amongst the two. These mechanisms are available via the {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} properties (to be more precise, the `Window` object implements the `WindowLocalStorage` and `WindowSessionStorage` objects, which the `localStorage` and `sessionStorage` properties hang off) — invoking one of these will create an instance of the {{domxref("Storage")}} object, through which data items can be set, retrieved and removed. A different Storage object is used for the `sessionStorage` and `localStorage` for each origin — they function and are controlled separately. > **Note:** In Firefox, when the browser crashes/restarts, to avoid memory issues caused by excessive usage of web storage, the amount of data saved per origin is limited to 10MB. See [storage quotas and eviction criteria](/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria#firefox) for more information. > **Note:** Access to Web Storage from third-party IFrames is denied if the user has [disabled third-party cookies](https://support.mozilla.org/en-US/kb/third-party-cookies-firefox-tracking-protection). ## Determining storage access by a third party Each origin has its own storage — this is true for both web storage and [shared storage](/en-US/docs/Web/API/Shared_Storage_API)). However, access of third-party (i.e., embedded) code to shared storage depends on its [browsing context](/en-US/docs/Glossary/Browsing_context). The context in which a third-party code from another origin runs determines the storage access of the third-party code. ![A box diagram showing a top-level browsing context called publisher.com, with third-party content embedded in it](embedded-content.png) Third-party code can be added to another site by injecting it with a {{htmlelement("script")}} element or by setting the source of an {{htmlelement("iframe")}} to a site that contains third-party code. The method used for integrating third-party code determines the browsing context of the code. - If your third-party code is added to another site with a `<script>` element, your code will be executed in the browsing context of the embedder. Therefore, when you call {{domxref("Storage.setItem()")}} or {{domxref("SharedStorage.set()")}}, the key/value pair will be written to the embedder's storage. From the browser's perspective, there is no difference between first-party code and third-party code when a `<script>` tag is used. - When your third-party code is added to another site within an `<iframe>`, the code inside the `<iframe>` will be executed with the origin of the `<iframe>`'s browsing context. If the code inside the `<iframe>` calls {{domxref("Storage.setItem()")}}, data will be written into the local or session storage of the `<iframe>`'s origin. If the `<iframe>` code calls {{domxref("SharedStorage.set()")}}, the data will be written into the shared storage of the `<iframe>`'s origin. ## Web Storage interfaces - {{domxref("Storage")}} - : Allows you to set, retrieve and remove data for a specific domain and storage type (session or local). - {{domxref("Window")}} - : The Web Storage API extends the {{domxref("Window")}} object with two new properties — {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} — which provide access to the current domain's session and local {{domxref("Storage")}} objects respectively, and a {{domxref("Window/storage_event", "storage")}} event handler that fires when a storage area changes (e.g., a new item is stored). - {{domxref("StorageEvent")}} - : The `storage` event is fired on a document's `Window` object when a storage area changes. ## Examples To illustrate some typical web storage usage, we have created a simple example, imaginatively called [Web Storage Demo](https://github.com/mdn/dom-examples/tree/main/web-storage). The [landing page](https://mdn.github.io/dom-examples/web-storage/) provides controls that can be used to customize the color, font and decorative image. When you choose different options, the page is instantly updated; in addition your choices are stored in `localStorage`, so that when you leave the page then load it again later on your choices are remembered. In addition, we have provided an [event output page](https://mdn.github.io/dom-examples/web-storage/event.html) — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as the {{domxref("StorageEvent")}} is fired. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Private Browsing / Incognito modes Private windows, incognito mode, and similarly named privacy browsing options, don't store data like history and cookies. In private mode, `localStorage` is treated like `sessionStorage`. The storage APIs are still available and fully functional, but all data stored in the private window is deleted when the browser or browser tab is closed. ## See also - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) - [Browser storage quotas and eviction criteria](/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria)
0
data/mdn-content/files/en-us/web/api/web_storage_api
data/mdn-content/files/en-us/web/api/web_storage_api/using_the_web_storage_api/index.md
--- title: Using the Web Storage API slug: Web/API/Web_Storage_API/Using_the_Web_Storage_API page-type: guide browser-compat: - api.Window.localStorage - api.Window.sessionStorage --- {{DefaultAPISidebar("Web Storage API")}} The Web Storage API provides mechanisms by which browsers can securely store key/value pairs. This article provides a walkthrough of how to make use of this technology. ## Basic concepts Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings). You can access these values like an object, or with the {{domxref("Storage.getItem()")}} and {{domxref("Storage.setItem()")}} methods. These three lines all set the (same) colorSetting entry: ```js localStorage.colorSetting = "#a4509b"; localStorage["colorSetting"] = "#a4509b"; localStorage.setItem("colorSetting", "#a4509b"); ``` > **Note:** It's recommended to use the Web Storage API (`setItem`, `getItem`, `removeItem`, `key`, `length`) to prevent the [pitfalls](https://2ality.com/2012/01/objects-as-maps.html) associated with using plain objects as key-value stores. The two mechanisms within Web Storage are as follows: - `sessionStorage` maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores). - `localStorage` does the same thing, but persists even when the browser is closed and reopened. These mechanisms are available via the {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} properties (to be more precise, in supporting browsers the `Window` object implements the `WindowLocalStorage` and `WindowSessionStorage` objects, which the `localStorage` and `sessionStorage` properties are members of) — invoking one of these will create an instance of the {{domxref("Storage")}} object, through which data items can be set, retrieved, and removed. A different Storage object is used for the `sessionStorage` and `localStorage` for each origin — they function and are controlled separately. So, for example, initially calling `localStorage` on a document will return a {{domxref("Storage")}} object; calling `sessionStorage` on a document will return a different {{domxref("Storage")}} object. Both of these can be manipulated in the same way, but separately. ## Feature-detecting localStorage To be able to use localStorage, we should first verify that it is supported and available in the current browsing session. ### Testing for availability > **Note:** This API is available in current versions of all major browsers. Testing for availability is necessary only if you must support very old browsers, or in the limited circumstances described below. Browsers that support localStorage have a property on the window object named `localStorage`. However, just asserting that the property exists may throw exceptions. If the `localStorage` object does exist, there is still no guarantee that the localStorage API is actually available, as various browsers offer settings that disable localStorage. So a browser may _support_ localStorage, but not make it _available_ to the scripts on the page. For example, for a document viewed in a browser's private browsing mode, some browsers might give us an empty `localStorage` object with a quota of zero, effectively making it unusable. Conversely, we might get a legitimate `QuotaExceededError`, which means that we've used up all available storage space, but storage _is_ actually _available_. Our feature detection should take these scenarios into account. Here is a function that detects whether localStorage is both supported and available: ```js function storageAvailable(type) { let storage; try { storage = window[type]; const x = "__storage_test__"; storage.setItem(x, x); storage.removeItem(x); return true; } catch (e) { return ( e instanceof DOMException && // everything except Firefox (e.code === 22 || // Firefox e.code === 1014 || // test name field too, because code might not be present // everything except Firefox e.name === "QuotaExceededError" || // Firefox e.name === "NS_ERROR_DOM_QUOTA_REACHED") && // acknowledge QuotaExceededError only if there's something already stored storage && storage.length !== 0 ); } } ``` And here is how you would use it: ```js if (storageAvailable("localStorage")) { // Yippee! We can use localStorage awesomeness } else { // Too bad, no localStorage for us } ``` You can test for sessionStorage instead by calling `storageAvailable('sessionStorage')`. See here for a [brief history of feature-detecting localStorage](https://gist.github.com/paulirish/5558557). ## Example To illustrate some typical web storage usage, we have created an example, imaginatively called **Web Storage Demo**. The [landing page](https://mdn.github.io/dom-examples/web-storage/) provides controls that can be used to customize the color, font, and decorative image: ![Web storage example with text box to choose the color by entering a hex value, and two dropdown menus to choose the font style, and decorative image.](landing.png)When you choose different options, the page is instantly updated; in addition, your choices are stored in `localStorage`, so that when you leave the page and load it again, later on, your choices are remembered. We have also provided an [event output page](https://mdn.github.io/dom-examples/web-storage/event.html) — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as a {{domxref("StorageEvent")}} is fired. ![Event output page](event-output.png) > **Note:** As well as viewing the example pages live using the above links, you can also [check out the source code](https://github.com/mdn/dom-examples/tree/main/web-storage). ### Testing whether your storage has been populated To start with, in [main.js](https://github.com/mdn/dom-examples/blob/main/web-storage/main.js), we test whether the storage object has already been populated (i.e., the page was previously accessed): ```js if (!localStorage.getItem("bgcolor")) { populateStorage(); } else { setStyles(); } ``` The {{domxref("Storage.getItem()")}} method is used to get a data item from storage; in this case, we are testing to see whether the `bgcolor` item exists; if not, we run `populateStorage()` to add the existing customization values to the storage. If there are already values there, we run `setStyles()` to update the page styling with the stored values. > **Note:** You could also use {{domxref("Storage.length")}} to test whether the storage object is empty or not. ### Getting values from storage As noted above, values can be retrieved from storage using {{domxref("Storage.getItem()")}}. This takes the key of the data item as an argument, and returns the data value. For example: ```js function setStyles() { const currentColor = localStorage.getItem("bgcolor"); const currentFont = localStorage.getItem("font"); const currentImage = localStorage.getItem("image"); document.getElementById("bgcolor").value = currentColor; document.getElementById("font").value = currentFont; document.getElementById("image").value = currentImage; htmlElem.style.backgroundColor = `#${currentColor}`; pElem.style.fontFamily = currentFont; imgElem.setAttribute("src", currentImage); } ``` Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. Finally, we update the styles/decorative image on the page, so your customization options come up again on reload. ### Setting values in storage {{domxref("Storage.setItem()")}} is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments — the key of the data item to create/modify, and the value to store in it. ```js function populateStorage() { localStorage.setItem("bgcolor", document.getElementById("bgcolor").value); localStorage.setItem("font", document.getElementById("font").value); localStorage.setItem("image", document.getElementById("image").value); setStyles(); } ``` The `populateStorage()` function sets three items in local storage — the background color, font, and image path. It then runs the `setStyles()` function to update the page styles, etc. We've also included an `onchange` handler on each form element so that the data and styling are updated whenever a form value is changed: ```js bgcolorForm.onchange = populateStorage; fontForm.onchange = populateStorage; imageForm.onchange = populateStorage; ``` `Storage` only supports storing and retrieving strings. If you want to save other data types, you have to convert them to strings. For plain objects and arrays, you can use {{jsxref("JSON.stringify()")}}. ```js const person = { name: "Alex" }; localStorage.setItem("user", person); console.log(localStorage.getItem("user")); // "[object Object]"; not useful! localStorage.setItem("user", JSON.stringify(person)); console.log(JSON.parse(localStorage.getItem("user"))); // { name: "Alex" } ``` However, there's no generic way to store arbitrary data types. Furthermore, the retrieved object is a [deep copy](/en-US/docs/Glossary/Deep_copy) of the original object and mutations to it do not affect the original object. ### Responding to storage changes with the StorageEvent The {{domxref("StorageEvent")}} is fired whenever a change is made to the {{domxref("Storage")}} object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects. On the events page (see [events.js](https://github.com/mdn/dom-examples/blob/main/web-storage/event.js)) the only JavaScript is as follows: ```js window.addEventListener("storage", (e) => { document.querySelector(".my-key").textContent = e.key; document.querySelector(".my-old").textContent = e.oldValue; document.querySelector(".my-new").textContent = e.newValue; document.querySelector(".my-url").textContent = e.url; document.querySelector(".my-storage").textContent = JSON.stringify( e.storageArea, ); }); ``` Here we add an event listener to the `window` object that fires when the {{domxref("Storage")}} object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself (which we've stringified so you can see its content). ### Deleting data records Web Storage also provides a couple of simple methods to remove data. We don't use these in our demo, but they are very simple to add to your project: - {{domxref("Storage.removeItem()")}} takes a single argument — the key of the data item you want to remove — and removes it from the storage object for that domain. - {{domxref("Storage.clear()")}} takes no arguments, and empties the entire storage object for that domain. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Storage API landing page](/en-US/docs/Web/API/Web_Storage_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlmeterelement/index.md
--- title: HTMLMeterElement slug: Web/API/HTMLMeterElement page-type: web-api-interface browser-compat: api.HTMLMeterElement --- {{APIRef("HTML DOM")}} The HTML {{HTMLElement("meter")}} elements expose the **`HTMLMeterElement`** interface, which provides special properties and methods (beyond the {{domxref("HTMLElement")}} object interface they also have available to them by inheritance) for manipulating the layout and presentation of {{HTMLElement("meter")}} elements. {{InheritanceDiagram}} ## Instance properties _Also inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLMeterElement.high")}} - : A `double` representing the value of the high boundary, reflecting the [`high`](/en-US/docs/Web/HTML/Element/meter#high) attribute. - {{domxref("HTMLMeterElement.low")}} - : A `double` representing the value of the low boundary, reflecting the [`low`](/en-US/docs/Web/HTML/Element/meter#low)attribute. - {{domxref("HTMLMeterElement.max")}} - : A `double` representing the maximum value, reflecting the [`max`](/en-US/docs/Web/HTML/Element/meter#max) attribute. - {{domxref("HTMLMeterElement.min")}} - : A `double` representing the minimum value, reflecting the [`min`](/en-US/docs/Web/HTML/Element/meter#min) attribute. - {{domxref("HTMLMeterElement.optimum")}} - : A `double` representing the optimum, reflecting the [`optimum`](/en-US/docs/Web/HTML/Element/meter#optimum) attribute. - {{domxref("HTMLMeterElement.value")}} - : A `double` representing the current value, reflecting the [`value`](/en-US/docs/Web/HTML/Element/meter#value) attribute. - {{domxref("HTMLMeterElement.labels")}} {{ReadOnlyInline}} - : A {{domxref("NodeList")}} of {{HTMLElement("label")}} elements that are associated with the element. ## Instance methods _This interface does not implement any specific methods but inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{HTMLElement("meter")}}
0
data/mdn-content/files/en-us/web/api/htmlmeterelement
data/mdn-content/files/en-us/web/api/htmlmeterelement/labels/index.md
--- title: "HTMLMeterElement: labels property" short-title: labels slug: Web/API/HTMLMeterElement/labels page-type: web-api-instance-property browser-compat: api.HTMLMeterElement.labels --- {{APIRef("DOM")}} The **`HTMLMeterElement.labels`** read-only property returns a {{domxref("NodeList")}} of the {{HTMLElement("label")}} elements associated with the {{HTMLElement("meter")}} element. ## Value A {{domxref("NodeList")}} containing the `<label>` elements associated with the `<meter>` element. ## Examples ### HTML ```html <label id="label1" for="test">Label 1</label> <meter id="test" min="0" max="100" value="70">70</meter> <label id="label2" for="test">Label 2</label> ``` ### JavaScript ```js window.addEventListener("DOMContentLoaded", () => { const meter = document.getElementById("test"); for (const label of meter.labels) { console.log(label.textContent); // "Label 1" and "Label 2" } }); ``` {{EmbedLiveSample("Examples", "100%", 30)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/user-agent_client_hints_api/index.md
--- title: User-Agent Client Hints API slug: Web/API/User-Agent_Client_Hints_API page-type: web-api-overview status: - experimental browser-compat: api.NavigatorUAData --- {{DefaultAPISidebar("User-Agent Client Hints API")}}{{SeeCompatTable}} The User-Agent Client Hints API extends [Client Hints](/en-US/docs/Web/HTTP/Client_hints) to provide a way of exposing browser and platform information via User-Agent response and request headers, and a JavaScript API. ## Concepts and Usage Parsing the User-Agent string has historically been the way to get information about the user's browser or device. A typical user agent string looks like the following example, identifying Chrome 92 on Windows: ```plain Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 ``` User agent Client Hints aims to provide this information in a more privacy-preserving way by enforcing a model where the server requests a set of information. The browser decides what to return. This approach means that a user-agent could provide settings that allow a user to hide some of the information that could fingerprint them from such requests. In order to decide what to return, the information accessed via this API is split into two groups—**low entropy** and **high entropy** hints. Low entropy hints are those that do not give away much information, the API makes these easily accessible with every request. High entropy hints have the potential to give away more information and therefore are gated in such a way that the browser can make a decision as to whether to provide them. This decision could potentially be based on user preferences, or behind a permission request. ### Use cases for User-Agent Client Hints Potential use cases include: - Providing custom-tailored polyfills to users on identifying that their browser lacked some web platform feature. - Working around browser bugs. - Recording browser analytics. - Adapting content based on user-agent information. This includes serving different content to mobile devices, in particular devices identified as low-powered. It might also include adapting the design to tailor the interfaces to the user's OS, or providing links to OS-specific ones. - Providing a notification when a user logs in from a different browser or device, as a security feature. - Providing the correct binary executable, on a site offering a download. - Collecting information about the browser and device to identify application errors. - Blocking spammers, bots, and crawlers. ## Interfaces - {{domxref("NavigatorUAData")}} - : Provides properties and methods to access data about the user's browser and operating system. ## Examples ### Getting the brands The following example prints the value of {{domxref("NavigatorUAData.brands")}} to the console. ```js console.log(navigator.userAgentData.brands); ``` ### Returning high entropy values In the following example a number of hints are requested using the {{domxref("NavigatorUAData.getHighEntropyValues()")}} method. When the promise resolves, this information is printed to the console. ```js navigator.userAgentData .getHighEntropyValues([ "architecture", "model", "platform", "platformVersion", "fullVersionList", ]) .then((ua) => { console.log(ua); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Improving user privacy and developer experience with User-Agent Client Hints](https://developer.chrome.com/docs/privacy-security/user-agent-client-hints) - [Migrate to User-Agent Client Hints](https://web.dev/articles/migrate-to-ua-ch)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/navigator/index.md
--- title: Navigator slug: Web/API/Navigator page-type: web-api-interface browser-compat: api.Navigator --- {{APIRef("DOM")}} The **`Navigator`** interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities. A `Navigator` object can be retrieved using the read-only {{domxref("window.navigator")}} property. ## Instance properties _Doesn't inherit any properties._ ### Standard properties - {{domxref("Navigator.bluetooth")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("Bluetooth")}} object for the current document, providing access to [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API) functionality. - {{domxref("Navigator.clipboard")}} {{ReadOnlyInline}} {{securecontext_inline}} - : Returns a {{domxref("Clipboard")}} object that provides read and write access to the system clipboard. - {{domxref("Navigator.connection")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("NetworkInformation")}} object containing information about the network connection of a device. - {{domxref("Navigator.contacts")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref('ContactsManager')}} interface which allows users to select entries from their contact list and share limited details of the selected entries with a website or application. - {{domxref("Navigator.cookieEnabled")}} {{ReadOnlyInline}} - : Returns false if setting a cookie will be ignored and true otherwise. - {{domxref("Navigator.credentials")}} {{ReadOnlyInline}} - : Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. - {{domxref("Navigator.deviceMemory")}} {{ReadOnlyInline}} - : Returns the amount of device memory in gigabytes. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024. - {{domxref("Navigator.geolocation")}} {{ReadOnlyInline}} - : Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device. - {{domxref("Navigator.gpu")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the {{domxref("GPU")}} object for the current browsing context. The entry point for the {{domxref("WebGPU_API", "WebGPU API", "", "nocode")}}. - {{domxref("Navigator.hardwareConcurrency")}} {{ReadOnlyInline}} - : Returns the number of logical processor cores available. - {{domxref("Navigator.hid")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns an {{domxref("HID")}} object providing methods for connecting to HID devices, listing attached HID devices, and event handlers for connected HID devices. - {{domxref("Navigator.ink")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns an {{domxref("Ink")}} object for the current document, providing access to [Ink API](/en-US/docs/Web/API/Ink_API) functionality. - {{domxref('Navigator.keyboard')}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref('Keyboard')}} object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. - {{domxref("Navigator.language")}} {{ReadOnlyInline}} - : Returns a string representing the preferred language of the user, usually the language of the browser UI. The `null` value is returned when this is unknown. - {{domxref("Navigator.languages")}} {{ReadOnlyInline}} - : Returns an array of strings representing the languages known to the user, by order of preference. - {{domxref("Navigator.locks")}} {{ReadOnlyInline}} - : Returns a {{domxref("LockManager")}} object that provides methods for requesting a new {{domxref('Lock')}} object and querying for an existing {{domxref('Lock')}} object. - {{domxref("Navigator.login")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Provides access to the browser's {{domxref("NavigatorLogin")}} object, which a federated identity provider (IdP) can use to set a user's login status when they sign into or out of the IdP. See [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API) for more details. - {{domxref("Navigator.maxTouchPoints")}} {{ReadOnlyInline}} - : Returns the maximum number of simultaneous touch contact points are supported by the current device. - {{domxref("Navigator.mediaCapabilities")}} {{ReadOnlyInline}} - : Returns a {{domxref("MediaCapabilities")}} object that can expose information about the decoding and encoding capabilities for a given format and output capabilities. - {{domxref("Navigator.mediaDevices")}} {{ReadOnlyInline}} - : Returns a reference to a {{domxref("MediaDevices")}} object which can then be used to get information about available media devices ({{domxref("MediaDevices.enumerateDevices()")}}), find out what constrainable properties are supported for media on the user's computer and user agent ({{domxref("MediaDevices.getSupportedConstraints()")}}), and to request access to media using {{domxref("MediaDevices.getUserMedia()")}}. - {{domxref("Navigator.mediaSession")}} {{ReadOnlyInline}} - : Returns {{domxref("MediaSession")}} object which can be used to provide metadata that can be used by the browser to present information about the currently-playing media to the user, such as in a global media controls UI. - {{domxref("Navigator.onLine")}} {{ReadOnlyInline}} - : Returns a boolean value indicating whether the browser is working online. - {{domxref("Navigator.pdfViewerEnabled")}} {{ReadOnlyInline}} - : Returns `true` if the browser can display PDF files inline when navigating to them, and `false` otherwise. - {{domxref("Navigator.permissions")}} {{ReadOnlyInline}} - : Returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the [Permissions API](/en-US/docs/Web/API/Permissions_API). - {{domxref("Navigator.presentation")}} {{ReadOnlyInline}} - : Returns a reference to the {{domxref("Presentation")}} API. - {{domxref("Navigator.scheduling")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("Scheduling")}} object for the current document. - {{domxref("Navigator.serial")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("Serial")}} object, which represents the entry point into the {{domxref("Web Serial API")}} to enable the control of serial ports. - {{domxref("Navigator.serviceWorker")}} {{ReadOnlyInline}} - : Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the [associated document](https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window). - {{domxref("Navigator.storage")}} {{ReadOnlyInline}} - : Returns the singleton {{domxref('StorageManager')}} object used for managing persistence permissions and estimating available storage on a site-by-site/app-by-app basis. - {{domxref("Navigator.usb")}} {{ReadOnlyInline}} - : Returns a {{domxref("USB")}} object for the current document, providing access to [WebUSB API](/en-US/docs/Web/API/WebUSB_API) functionality. - {{domxref("Navigator.userActivation")}} {{ReadOnlyInline}} - : Returns a {{domxref("UserActivation")}} object containing information about the current window's user activation state. - {{domxref("Navigator.userAgent")}} {{ReadOnlyInline}} - : Returns the user agent string for the current browser. - {{domxref("Navigator.userAgentData")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("NavigatorUAData")}} object, which gives access to information about the browser and operating system of the user. - {{domxref("Navigator.virtualKeyboard")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to the {{domxref("VirtualKeyboard")}} API, to take control of the on-screen virtual keyboard. - {{domxref("Navigator.wakeLock")}} {{ReadOnlyInline}} - : Returns a {{domxref("WakeLock")}} interface you can use to request screen wake locks and prevent screen from dimming, turning off, or showing a screen saver. - {{domxref("Navigator.webdriver")}} {{ReadOnlyInline}} - : Indicates whether the user agent is controlled by automation. - {{domxref("Navigator.windowControlsOverlay")}} {{ReadOnlyInline}} - : Returns the {{domxref("WindowControlsOverlay")}} interface which exposes information about the geometry of the title bar in desktop Progressive Web Apps, and an event to know whenever it changes. - {{domxref("Navigator.xr")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns {{domxref("XRSystem")}} object, which represents the entry point into the [WebXR API](/en-US/docs/Web/API/WebXR_Device_API). ### Non-standard properties - {{domxref("Navigator.buildID")}} {{ReadOnlyInline}} {{Non-standard_Inline}} - : Returns the build identifier of the browser. In modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. `20181001000000` in Firefox 64 onwards. - {{domxref("Navigator.globalPrivacyControl")}} {{ReadOnlyInline}} {{Experimental_Inline}} {{non-standard_inline}} - : Returns a boolean indicating a user's consent to their information being shared or sold. - {{domxref("Navigator.standalone")}} {{Non-standard_Inline}} - : Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only. ### Deprecated properties - {{domxref("Navigator.activeVRDisplays")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is `true`). - {{domxref("Navigator.appCodeName")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Always returns `'Mozilla'`, in any browser. - {{domxref("Navigator.appName")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Always returns `'Netscape'`, in any browser. - {{domxref("Navigator.appVersion")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Returns the version of the browser as a string. Do not rely on this property to return the correct value. - {{domxref("Navigator.doNotTrack")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{non-standard_inline}} - : Reports the value of the user's do-not-track preference. When this value is "1", your website or application should not track the user. - {{domxref("Navigator.mimeTypes")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser. - {{domxref("Navigator.oscpu")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Returns a string that represents the current operating system. - {{domxref("Navigator.platform")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Returns a string representing the platform of the browser. Do not rely on this function to return a significant value. - {{domxref("Navigator.plugins")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser. - {{domxref("Navigator.product")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Always returns `'Gecko'`, in any browser. - {{domxref("Navigator.productSub")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Returns either the string `'20030107'`, or `'"20100101'`. - {{domxref("Navigator.vendor")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Returns either the empty string, `'Apple Computer Inc.'`, or `'Google Inc.'`. - {{domxref("Navigator.vendorSub")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Always returns the empty string. ## Instance methods _Doesn't inherit any method._ - {{domxref("Navigator.canShare()")}} - : Returns `true` if a call to `Navigator.share()` would succeed. - {{domxref("Navigator.clearAppBadge()")}} - : Clears a badge on the current app's icon and returns a {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}}. - {{domxref("Navigator.getAutoplayPolicy()")}} {{Experimental_Inline}} - : Returns a value indicating whether the specified media element, audio context, or media feature "type" is allowed to autoplay. - {{domxref("Navigator.getBattery()")}} - : Returns a promise that resolves with a {{domxref("BatteryManager")}} object that returns information about the battery charging status. - {{domxref("Navigator.getGamepads()")}} - : returns an array of {{domxref("Gamepad")}} objects, one for each gamepad connected to the device. - {{domxref("Navigator.getInstalledRelatedApps()")}} {{Experimental_Inline}} - : Returns a promise that resolves with an array of objects representing any related native or [Progressive Web Applications](/en-US/docs/Web/Progressive_web_apps) that the user has installed. - {{domxref("Navigator.registerProtocolHandler()")}} - : Allows websites to register themselves as a possible handler for a given protocol. - {{domxref("Navigator.requestMediaKeySystemAccess()")}} - : Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object. - {{domxref("Navigator.requestMIDIAccess()")}} - : Returns a {{jsxref('Promise')}} representing a request for access to MIDI devices on the user's system. - {{domxref("Navigator.sendBeacon()")}} - : Used to asynchronously transfer a small amount of data using {{Glossary("HTTP")}} from the User Agent to a web server. - {{domxref("Navigator.setAppBadge()")}} - : Sets a badge on the icon associated with this app and returns a {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}}. - {{domxref("Navigator.share()")}} - : Invokes the native sharing mechanism of the current platform. - {{domxref("Navigator.vibrate()")}} - : Causes vibration on devices with support for it. Does nothing if vibration support isn't available. - {{domxref("Navigator.unregisterProtocolHandler()")}} - : Unregister a website that is a handler for a given protocol. ### Deprecated methods - {{domxref("Navigator.getUserMedia()")}} {{Deprecated_Inline}} - : After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer. - {{domxref("Navigator.getVRDisplays()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer. - {{domxref("Navigator.javaEnabled()")}} {{Deprecated_Inline}} - : Always returns false. - {{domxref("Navigator.taintEnabled()")}} {{Deprecated_Inline}} - : Returns `false`. JavaScript taint/untaint functions removed in JavaScript 1.2. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/pdfviewerenabled/index.md
--- title: "Navigator: pdfViewerEnabled property" short-title: pdfViewerEnabled slug: Web/API/Navigator/pdfViewerEnabled page-type: web-api-instance-property browser-compat: api.Navigator.pdfViewerEnabled --- {{APIRef("HTML DOM")}} The **`pdfViewerEnabled`** read-only property of the {{domxref("Navigator")}} interface indicates whether the browser supports inline display of PDF files when navigating to them. If inline viewing is not supported the PDF is downloaded and may then be handled by some external application. > **Note:** This method replaces a number of legacy methods of inferring support for inline viewing of PDF files. ## Value `true` if the browser can display PDF files inline when navigating to the file (using either an internal viewer or a PDF viewer extension); otherwise `false`. ## Examples To check PDF inline viewing support: ```js if (!navigator.pdfViewerEnabled) { // The browser does not support inline viewing of PDF files. } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/registerprotocolhandler/index.md
--- title: "Navigator: registerProtocolHandler() method" short-title: registerProtocolHandler() slug: Web/API/Navigator/registerProtocolHandler page-type: web-api-instance-method browser-compat: api.Navigator.registerProtocolHandler --- {{APIRef("HTML DOM")}}{{securecontext_header}} The **{{domxref("Navigator")}}** method **`registerProtocolHandler()`** lets websites register their ability to open or handle particular URL schemes (aka protocols). For example, this API lets webmail sites open `mailto:` URLs, or VoIP sites open `tel:` URLs. ## Syntax ```js-nolint registerProtocolHandler(scheme, url) ``` ### Parameters - `scheme` - : A string containing the [permitted scheme](#permitted_schemes) for the protocol that the site wishes to handle. For example, you can register to handle SMS text message links by passing the `"sms"` scheme. - `url` - : A string containing the URL of the handler. **This URL must include `%s`**, as a placeholder that will be replaced with the [escaped](/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) URL to be handled. > **Note:** The handler URL must use the `https` scheme. Older browsers also supported `http`. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : The user agent blocked the registration. This might happen if: - The registered scheme (protocol) is invalid, such as a scheme the browser handles itself (`https:`, `about:`, etc.) - The handler URL's {{Glossary("origin")}} does not match the origin of the page calling this API. - The browser requires that this function is called from a secure context. - The browser requires that the handler's URL be over HTTPS. - `SyntaxError` {{domxref("DOMException")}} - : The `%s` placeholder is missing from the handler URL. ## Permitted schemes For security reasons, `registerProtocolHandler()` restricts which schemes can be registered. A **custom scheme** may be registered as long as: - The custom scheme's name begins with `web+` - The custom scheme's name includes at least 1 letter after the `web+` prefix - The custom scheme has only lowercase {{Glossary("ASCII")}} letters in its name. For example, `web+burger`, as shown in the [Example](#examples) below. Otherwise, the scheme must be one of the following: - `bitcoin` - `ftp` - `ftps` - `geo` - `im` - `irc` - `ircs` - `magnet` - `mailto` - `matrix` - `mms` - `news` - `nntp` - `openpgp4fpr` - `sftp` - `sip` - `sms` - `smsto` - `ssh` - `tel` - `urn` - `webcal` - `wtai` - `xmpp` <!-- This must match: https://html.spec.whatwg.org/multipage/system-state.html#safelisted-scheme --> ## Examples If your site is `burgers.example.com`, you can register a protocol handler for it to handle `web+burger:` links, like so: ```js navigator.registerProtocolHandler( "web+burger", "https://burgers.example.com/?burger=%s", ); ``` This creates a handler that lets `web+burger:` links send the user to your site, inserting the accessed burger URL into the `%s` placeholder. This script must be run from the same origin as the handler URL (so any page at `https://burgers.example.com`), and the handler URL must be `http` or `https`. The user will be notified that your code asked to register the protocol handler, so that they can decide whether or not to allow it. See the screenshot below for an example on `google.co.uk`: ![A browser notification reads "Add Burger handler (www.google.co.uk) as an application for burger links?", and offers an "Add Application" button and a close to ignore the handler request.](protocolregister.png) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web-based protocol handlers](/en-US/docs/Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers) - [RegisterProtocolHandler Enhancing the Federated Web](https://blog.mozilla.org/webdev/2010/07/26/registerprotocolhandler-enhancing-the-federated-web/) (Mozilla Webdev)
0
data/mdn-content/files/en-us/web/api/navigator/registerprotocolhandler
data/mdn-content/files/en-us/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.md
--- title: Web-based protocol handlers slug: Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers page-type: guide --- ## Background It's fairly common to find web pages link to resources using non-`http` protocols. An example is the `mailto:` protocol: ```html <a href="mailto:[email protected]">Web Master</a> ``` Web authors can use a `mailto:` link when they want to provide a convenient way for users to send an email, directly from the webpage. When the link is activated, the browser should launch the default desktop application for handling email. You can think of this as a _desktop-based_ protocol handler. Web-based protocol handlers allow web-based applications to participate in the process too. This is becoming more important as more types of applications migrate to the web. In fact, there are many web-based email handling applications that could process a `mailto` link. ## Registering Setting up a web application as a protocol handler is not a difficult process. Basically, the web application uses [`registerProtocolHandler()`](/en-US/docs/Web/API/Navigator/registerProtocolHandler) to register itself with the browser as a potential handler for a given protocol. For example: ```js navigator.registerProtocolHandler( "web+burger", "http://www.google.co.uk/?uri=%s", "Burger handler", ); ``` Where the parameters are: - The protocol. - The URL template, used as the handler. The "%s" is replaced with the `href` of the link and a GET is executed on the resultant URL. - The user friendly name for the protocol handler. When a browser executes this code, it should let the user choose how to handle the protocol. The browser could prompt the user for registration immediately, or wait until the user clicks on a link that uses the protocol. Firefox displays a prompt in the notification bar area: ![Screenshot of a prompt that reads: Add Burger handler (google.co.uk) as an application for burger links. An Add Application button is next to the text.](protocolregister.png) > **Note:** The URL template supplied when registering **must** be of the same domain as the webpage attempting to perform the registration or the registration will fail. For example, `http://example.com/homepage.html` can register a protocol handler for `http://example.com/handle_mailto/%s`, but not for `http://example.org/handle_mailto/%s`. ### Example ```html <!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Web Protocol Handler Sample - Register</title> <script> navigator.registerProtocolHandler( "web+burger", "http://www.google.co.uk/?uri=%s", "Burger handler", ); </script> </head> <body> <h1>Web Protocol Handler Sample</h1> <p> This web page will install a web protocol handler for the <code>web+burger:</code> protocol. </p> </body> </html> ``` ## Activating Now, anytime the user activates a link that uses the registered protocol, the browser will route the action to the URL supplied when the web application registered. Firefox will, by default, prompt the user before handling off the action. ### Example ```html <!doctype html> <html lang="en"> <head> <title>Web Protocol Handler Sample - Test</title> </head> <body> <p>Hey have you seen <a href="web+burger:cheeseburger">this</a> before?</p> </body> </html> ``` ## Handling The next phase is handling the action. The browser extracts the `href` from the activated link, combines it with the URL template supplied during handler registration and performs an HTTP GET on the URL. So, using the above examples, the browser would perform a GET on this URL: ```url http://www.google.co.uk/?uri=web+burger:cheeseburger ``` Server side code can extract the query string parameters and perform the desired action. > **Note:** The server side code is passed the **entire** contents of the `href`. This means the server side code will have to parse out the protocol from the data. ### Example ```php <?php $value = ""; if ( isset ( $_GET["value"] ) ) { $value = $_GET["value"]; } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Web Protocol Handler Sample</title> </head> <body> <h1>Web Protocol Handler Sample - Handler</h1> <p>This web page is called when handling a <code>web+burger:</code> protocol action. The data sent:</p> <textarea> <?php echo(htmlspecialchars($value, ENT_QUOTES, 'UTF-8')); ?> </textarea> </body> </html> ``` ## References - [http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#custom-handlers](https://www.w3.org/TR/2011/WD-html5-20110525/timers.html#custom-handlers) ## See also - `nsIProtocolHandler` (XUL only) - [RegisterProtocolHandler Enhancing the Federated Web](https://blog.mozilla.org/webdev/2010/07/26/registerprotocolhandler-enhancing-the-federated-web/) at Mozilla Webdev - [Register a custom protocolHandler](https://web.dev/articles/registering-a-custom-protocol-handler) at web.dev.
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/appcodename/index.md
--- title: "Navigator: appCodeName property" short-title: appCodeName slug: Web/API/Navigator/appCodeName page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.appCodeName --- {{APIRef("HTML DOM")}} {{Deprecated_Header}} The value of the **`Navigator.appCodeName`** property is always "`Mozilla`", in any browser. This property is kept only for compatibility purposes. > **Note:** Do not rely on this property to return a real > product name. All browsers return "`Mozilla`" as the value of this property. ## Value The string "`Mozilla`". ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Navigator.appName")}} - {{domxref("Navigator.product")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/buildid/index.md
--- title: "Navigator: buildID property" short-title: buildID slug: Web/API/Navigator/buildID page-type: web-api-instance-property status: - non-standard browser-compat: api.Navigator.buildID --- {{ApiRef("HTML DOM")}}{{Non-standard_Header}} Returns the build identifier of the browser. In modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. `20181001000000` in Firefox 64 onwards. ## Value A string representing the build identifier of the application. The build ID is in the form `YYYYMMDDHHMMSS`. ## Examples ```js console.log(navigator.buildID); ``` ## Specifications Not part of any public standard. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/presentation/index.md
--- title: "Navigator: presentation property" short-title: presentation slug: Web/API/Navigator/presentation page-type: web-api-instance-property browser-compat: api.Navigator.presentation --- {{securecontext_header}}{{APIRef("Presentation API")}} The `presentation` read-only property of {{DOMxRef("Navigator")}} serves as the entry point for the [Presentation API](/en-US/docs/Web/API/Presentation_API) and returns a reference to {{DOMxRef("Presentation")}} object. ## Syntax ```js-nolint const presentation = navigator.presentation ``` ### Value A reference to {{DOMxRef("Presentation")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Presentation API](/en-US/docs/Web/API/Presentation_API) - {{DOMxRef("Presentation")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/virtualkeyboard/index.md
--- title: "Navigator: virtualKeyboard property" short-title: virtualKeyboard slug: Web/API/Navigator/virtualKeyboard page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.virtualKeyboard --- {{APIRef("VirtualKeyboard")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`virtualKeyboard`** read-only property of the {{domxref("navigator")}} interface returns a reference to the {{domxref("VirtualKeyboard")}} instance object. The {{domxref("VirtualKeyboard_API", "VirtualKeyboard API", "", "nocode")}} gives developers control over the layout of their applications when the on-screen virtual keyboard appears and disappears on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available. ## Value A {{domxref("VirtualKeyboard")}} object you can use to opt-out of the automatic virtual keyboard behavior, show or hide the virtual keyboard programmatically, and get the current position and size of the virtual keyboard. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/share/index.md
--- title: "Navigator: share() method" short-title: share() slug: Web/API/Navigator/share page-type: web-api-instance-method browser-compat: api.Navigator.share --- {{APIRef("Web Share API")}}{{securecontext_header}} The **`navigator.share()`** method of the [Web Share API](/en-US/docs/Web/API/Web_Share_API) invokes the native sharing mechanism of the device to share data such as text, URLs, or files. The available _share targets_ depend on the device, but might include the clipboard, contacts and email applications, websites, Bluetooth, etc. The method resolves a {{jsxref("Promise")}} with `undefined`. On Windows this happens when the share popup is launched, while on Android the promise resolves once the data has successfully been passed to the _share target_. ## Syntax ```js-nolint navigator.share(data) ``` ### Parameters - `data` - : An object containing data to share. Properties that are unknown to the user agent are ignored; share data is only assessed on properties understood by the user agent. All properties are optional but at least one known data property must be specified. Possible values are: - `url`: A string representing a URL to be shared. - `text`: A string representing text to be shared. - `title`: A string representing a title to be shared. May be ignored by the target. - `files`: An array of {{domxref("File")}} objects representing files to be shared. See [below](#shareable_file_types) for shareable file types. ### Return value A {{jsxref("Promise")}} that resolves with `undefined`, or rejected with one of the [Exceptions](#exceptions) given below. ### Exceptions The {{jsxref("Promise")}} may be rejected with one of the following `DOMException` values: - `InvalidStateError` {{domxref("DOMException")}} - : The document is not fully active, or other sharing operations are in progress. - `NotAllowedError` {{domxref("DOMException")}} - : A `web-share` [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) has been used to block the use of this feature, the window does not have {{Glossary("transient activation")}}, or a file share is being blocked due to security considerations. - {{jsxref("TypeError")}} - : The specified share data cannot be validated. Possible reasons include: - The `data` parameter was omitted completely or only contains properties with unknown values. Note that any properties that are not recognized by the user agent are ignored. - A URL is badly formatted. - Files are specified but the implementation does not support file sharing. - Sharing the specified data would be considered a "hostile share" by the user-agent. - `AbortError` {{domxref("DOMException")}} - : The user canceled the share operation or there are no share targets available. - `DataError` {{domxref("DOMException")}} - : There was a problem starting the share target or transmitting the data. ## Shareable file types The following is a list of usually shareable file types. However, you should always test with {{domxref("navigator.canShare()")}} if sharing would succeed. - Application - `.pdf` - `application/pdf` - Audio - `.flac` - `audio/flac` - `.m4a` - `audio/x-m4a` - `.mp3` - `audio/mpeg` (also accepts `audio/mp3`) - `.oga` - `audio/ogg` - `.ogg` - `audio/ogg` - `.opus` - `audio/ogg` - `.wav` - `audio/wav` - `.weba` - `audio/webm` - Image - `.avif` - `image/avif` - `.bmp` - `image/bmp` - `.gif` - `image/gif` - `.ico` - `image/x-icon` - `.jfif` - `image/jpeg` - `.jpeg` - `image/jpeg` - `.jpg` - `image/jpeg` - `.pjp` - `image/jpeg` - `.pjpeg` - `image/jpeg` - `.png` - `image/png` - `.svg` - `image/svg+xml` - `.svgz` - `image/svg+xml` - `.tif` - `image/tiff` - `.tiff` - `image/tiff` - `.webp` - `image/webp` - `.xbm` - `image/x-xbitmap` - Text - `.css` - `text/css` - `.csv` - `text/csv` - `.ehtml` - `text/html` - `.htm` - `text/html` - `.html` - `text/html` - `.shtm` - `text/html` - `.shtml` - `text/html` - `.text` - `text/plain` - `.txt` - `text/plain` - Video - `.m4v` - `video/mp4` - `.mp4` - `video/mp4` - `.mpeg` - `video/mpeg` - `.mpg` - `video/mpeg` - `.ogm` - `video/ogg` - `.ogv` - `video/ogg` - `.webm` - `video/webm` ## Security This method requires that the current document have the [web-share](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/web-share) Permissions Policy and {{Glossary("transient activation")}}. (It must be triggered off a UI event like a button click and cannot be launched at arbitrary points by a script.) Further, the method must specify valid data that is supported for sharing by the native implementation. ## Examples ### Sharing a URL The example below shows a button click invoking the Web Share API to share MDN's URL. This is taken from our [Web share test](https://mdn.github.io/dom-examples/web-share/) ([see the source code](https://github.com/mdn/dom-examples/blob/main/web-share/index.html)). #### HTML The HTML just creates a button to trigger the share, and a paragraph in which to display the result of the test. ```html <p><button>Share MDN!</button></p> <p class="result"></p> ``` #### JavaScript ```js const shareData = { title: "MDN", text: "Learn web development on MDN!", url: "https://developer.mozilla.org", }; const btn = document.querySelector("button"); const resultPara = document.querySelector(".result"); // Share must be triggered by "user activation" btn.addEventListener("click", async () => { try { await navigator.share(shareData); resultPara.textContent = "MDN shared successfully"; } catch (err) { resultPara.textContent = `Error: ${err}`; } }); ``` #### Result Click the button to launch the share dialog on your platform. Text will appear below the button to indicate whether the share was successful or provide an error code. {{EmbedLiveSample('Sharing a URL')}} ### Sharing files To share files, first test for and call {{domxref("navigator.canShare()")}}. Then include the list of files in the call to `navigator.share()`. #### HTML ```html <div> <label for="files">Select images to share:</label> <input id="files" type="file" accept="image/*" multiple /> </div> <button id="share" type="button">Share your images!</button> <output id="output"></output> ``` #### JavaScript Note that the data object passed to the `navigator.canShare()` only includes the `files` property, as the `title` and `text` shouldn't matter. ```js const input = document.getElementById("files"); const output = document.getElementById("output"); document.getElementById("share").addEventListener("click", async () => { const files = input.files; if (files.length === 0) { output.textContent = "No files selected."; return; } // feature detecting navigator.canShare() also implies // the same for the navigator.share() if (!navigator.canShare) { output.textContent = `Your browser doesn't support the Web Share API.`; return; } if (navigator.canShare({ files })) { try { await navigator.share({ files, title: "Images", text: "Beautiful images", }); output.textContent = "Shared!"; } catch (error) { output.textContent = `Error: ${error.message}`; } } else { output.textContent = `Your system doesn't support sharing these files.`; } }); ``` #### Result {{EmbedLiveSample('Sharing files')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("navigator.canShare()")}} - <https://wpt.live/web-share/> (web platform tests)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/mimetypes/index.md
--- title: "Navigator: mimeTypes property" short-title: mimeTypes slug: Web/API/Navigator/mimeTypes page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.mimeTypes --- {{ ApiRef("HTML DOM") }}{{deprecated_header}} Returns a {{domxref("MimeTypeArray")}} object, which contains a list of {{domxref("MimeType")}} objects representing the MIME types recognized and supported by the browser. The array can be queried for information about the enabled plugin that is used to handle a file of the specified type. Named properties of the returned object are not enumerable (except in very old browser versions). Recent versions of the specification hard-code the returned set of MIME types. If PDF files can be displayed inline then `application/pdf` and `text/pdf` are listed. Otherwise an empty list is returned. > **Note:** Use {{domxref("Navigator.pdfViewerEnabled")}} to determine if inline viewing of PDF files is supported. Do not infer it from this property. Legacy browser versions do not hard-code the list returned by the property, and might return other MIME types. ## Value A `MimeTypeArray` object which has a `length` property as well as `item(index)` and `namedItem(name)` methods. If PDF inline viewing is supported this has entries for MIME types `application/pdf` and `text/pdf`. Otherwise an empty `MimeTypeArray` is returned. The description and file suffixes supported by enabled plugins are hard coded to `'pdf'` and `'Portable Document Format'`, respectively. ## Examples The code below tests whether PDF files can be viewed inline, and then prints the description of the plugin and the file suffixes it supports. ```js if ("application/pdf" in navigator.mimeTypes) { // browser supports inline viewing of PDF files. const { description, suffixes } = navigator.mimeTypes["application/pdf"]; console.log(`Description: ${description}, Suffix: ${suffixes}`); // expected output: Description: Portable Document Format, Suffix: pdf } ``` Note that while the above code tests for `application/pdf` you could equally well check `text/pdf`. (Either both or neither MIME type will be true.) In addition, on current browsers you don't actually need to get the plugin description and suffixes, because this information is also hard-coded. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/clipboard/index.md
--- title: "Navigator: clipboard property" short-title: clipboard slug: Web/API/Navigator/clipboard page-type: web-api-instance-property browser-compat: api.Navigator.clipboard --- {{APIRef("Clipboard API")}} {{securecontext_header}} The **`clipboard`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("Clipboard")}} object used to read and write the clipboard's contents. This is the entry point to the [Clipboard API](/en-US/docs/Web/API/Clipboard_API), which can be used to implement cut, copy, and paste features within a web application. ## Value The {{domxref("Clipboard")}} object used to access the system clipboard. ## Examples The following code uses `navigator.clipboard` to access the system clipboard in order to read text contents from the clipboard. ```js navigator.clipboard .readText() .then( (clipText) => (document.querySelector(".cliptext").innerText = clipText), ); ``` This snippet replaces the contents of the element whose class is `"cliptext"` with the text contents of the clipboard. Perhaps this code is being used in a browser extension that displays the current clipboard contents, automatically updating periodically or when specific events fire. If the clipboard is empty or doesn't contain text, the `"cliptext"` element's contents are cleared. This happens because {{domxref("Clipboard.readText", "readText()")}} returns an empty string if the clipboard is empty or doesn't contain text. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/wakelock/index.md
--- title: "Navigator: wakeLock property" short-title: wakeLock slug: Web/API/Navigator/wakeLock page-type: web-api-instance-property browser-compat: api.Navigator.wakeLock --- {{ApiRef("Screen Wake Lock API")}}{{securecontext_header}} The **`wakeLock`** read-only property of the {{domxref("Navigator")}} interface returns a {{DOMxRef("WakeLock")}} interface that allows a document to acquire a screen wake lock. While a screen wake lock is active, the user agent will try to prevent the device from dimming the screen, turning it off completely, or showing a screensaver. ## Syntax ```js-nolint navigator.wakeLock ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("WakeLock.request()")}} - [Screen Wake Lock API](/en-US/docs/Web/API/Screen_Wake_Lock_API) - [Stay awake with the Screen Wake Lock API](https://developer.chrome.com/docs/capabilities/web-apis/wake-lock/)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/windowcontrolsoverlay/index.md
--- title: "Navigator: windowControlsOverlay property" short-title: windowControlsOverlay slug: Web/API/Navigator/windowControlsOverlay page-type: web-api-instance-property browser-compat: api.Navigator.windowControlsOverlay --- {{SecureContext_Header}}{{APIRef("")}} The **`windowControlsOverlay`** read-only property of the {{domxref("Navigator")}} interface returns the {{domxref("WindowControlsOverlay")}} interface, which exposes information about the title bar geometry in desktop Progressive Web Apps that use the [Window Controls Overlay API](/en-US/docs/Web/API/Window_Controls_Overlay_API). Progressive Web Apps installed on desktop Operating Systems can opt-in to the Window Controls Overlay feature by using the `window-controls-overlay` value in the [`display_override`](/en-US/docs/Web/Manifest/display_override) web app manifest member. Doing so hides the default window title bar and gives the app access to the full area of the app window. ## Value The {{domxref("WindowControlsOverlay")}} interface. ## Examples ```js if ("windowControlsOverlay" in navigator) { const rect = navigator.windowControlsOverlay.getTitlebarAreaRect(); // Do something with the title bar area rectangle. } else { // The Window Controls Overlay feature is not available. } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/login/index.md
--- title: "Navigator: login property" short-title: login slug: Web/API/Navigator/login page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.login --- {{securecontext_header}}{{APIRef("FedCM API")}}{{SeeCompatTable}} The **`login`** read-only property of the {{domxref("Navigator")}} interface provides access to the browser's {{domxref("NavigatorLogin")}} object, which a federated identity provider (IdP) can use to set its login status when a user signs into or out of the IdP. See [Update login status using the Login Status API](/en-US/docs/Web/API/FedCM_API/IDP_integration#update_login_status_using_the_login_status_api) for more details of how this is used. ## Value A {{domxref("NavigatorLogin")}} object. ## Examples ```js /* Set logged-in status */ navigator.login.setStatus("logged-in"); /* Set logged-out status */ navigator.login.setStatus("logged-out"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Federated Credential Management (FedCM) API](/en-US/docs/Web/API/FedCM_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/vibrate/index.md
--- title: "Navigator: vibrate() method" short-title: vibrate() slug: Web/API/Navigator/vibrate page-type: web-api-instance-method browser-compat: api.Navigator.vibrate --- {{APIRef("Vibration API")}} The **`Navigator.vibrate()`** method pulses the vibration hardware on the device, if such hardware exists. If the device doesn't support vibration, this method has no effect. If a vibration pattern is already in progress when this method is called, the previous pattern is halted and the new one begins instead. If the method was unable to vibrate because of invalid parameters, it will return `false`, else it returns `true`. If the pattern leads to a too long vibration, it is truncated: the max length depends on the implementation. ## Syntax ```js-nolint vibrate(pattern) ``` ### Parameters - `pattern` - : Provides a pattern of vibration and pause intervals. Each value indicates a number of milliseconds to vibrate or pause, in alternation. You may provide either a single value (to vibrate once for that many milliseconds) or an array of values to alternately vibrate, pause, then vibrate again. See [Vibration API](/en-US/docs/Web/API/Vibration_API) for details. Passing a value of `0`, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern. ### Return value A boolean. ## Security [Sticky user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work. ## Examples ```js navigator.vibrate(200); // vibrate for 200ms navigator.vibrate([ 100, 30, 100, 30, 100, 30, 200, 30, 200, 30, 200, 30, 100, 30, 100, 30, 100, ]); // Vibrate 'SOS' in Morse. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Vibration API](/en-US/docs/Web/API/Vibration_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/languages/index.md
--- title: "Navigator: languages property" short-title: languages slug: Web/API/Navigator/languages page-type: web-api-instance-property browser-compat: api.Navigator.languages --- {{APIRef("HTML DOM")}} The **`Navigator.languages`** read-only property returns an array of strings representing the user's preferred languages. The language is described using language tags according to {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}. In the returned array they are ordered by preference with the most preferred language first. The value of {{domxref("Navigator.language","navigator.language")}} is the first element of the returned array. When its value changes, as the user's preferred languages are changed a {{domxref("Window.languagechange_event", "languagechange")}} event is fired on the {{domxref("Window")}} object. The `Accept-Language` HTTP header in every HTTP request from the user's browser uses the same value for the `navigator.languages` property except for the extra `qvalues` (quality values) field (e.g. `en-US;q=0.8`). ## Value An array of strings. ## Examples ### Listing the contents of navigator.language and navigator.languages ```js navigator.language; // "en-US" navigator.languages; // ["en-US", "zh-CN", "ja-JP"] ``` ### Using Intl constructors to do language-specific formatting, with fallback The array of language identifiers contained in `navigator.languages` can be passed directly to the {{jsxref("Intl")}} constructors to implement preference-based fallback selection of locales, where the first entry in the list that matches a locale supported by `Intl` is used: ```js const date = new Date("2012-05-24"); const formattedDate = new Intl.DateTimeFormat(navigator.languages).format(date); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("navigator.language")}} - {{domxref("navigator")}} - {{domxref("Window.languagechange_event", "languagechange")}} event - {{jsxref("Intl")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/appname/index.md
--- title: "Navigator: appName property" short-title: appName slug: Web/API/Navigator/appName page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.appName --- {{APIRef("HTML DOM")}} {{Deprecated_Header}} The value of the **`Navigator.appName`** property is always "`Netscape`", in any browser. This property is kept only for compatibility purposes. > **Note:** Do not rely on this property to return a real browser name. All browsers return "`Netscape`" as the value of this property. ## Value The string "`Netscape`". ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Navigator.appCodeName")}} - {{domxref("Navigator.product")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/serial/index.md
--- title: "Navigator: serial property" short-title: serial slug: Web/API/Navigator/serial page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.serial --- {{APIRef("Web Serial API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`serial`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("Serial")}} object which represents the entry point into the {{domxref("Web Serial API")}}. When getting, the same instance of the {{domxref("Serial")}} object will always be returned. ## Value A {{domxref("Serial")}} object. ## Examples The following example uses the `getPorts()` method to initialize a list of available ports. ```js navigator.serial.getPorts().then((ports) => { // Initialize the list of available ports with `ports` on page load. }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Read from and write to a serial port](https://developer.chrome.com/docs/capabilities/serial) - [Getting started with the web serial API](https://codelabs.developers.google.com/codelabs/web-serial#0)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/donottrack/index.md
--- title: "Navigator: doNotTrack property" short-title: doNotTrack slug: Web/API/Navigator/doNotTrack page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.Navigator.doNotTrack --- {{ApiRef("HTML DOM")}}{{Deprecated_header}}{{non-standard_header}} The **`Navigator.doNotTrack`** property returns the user's Do Not Track setting, which indicates whether the user is requesting websites and advertisers to not track them. The value of the property reflects that of the {{httpheader("DNT")}} HTTP header, i.e. values of `"1"`, `"0"`, or `null`. ## Value A string or `null`. ## Examples ```js console.log(navigator.doNotTrack); // prints "1" if DNT is enabled; "0" if the user opted-in for tracking; otherwise null ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{httpheader("DNT")}} HTTP header
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/product/index.md
--- title: "Navigator: product property" short-title: product slug: Web/API/Navigator/product page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.product --- {{APIRef("HTML DOM")}} {{Deprecated_Header}} The value of the **`Navigator.product`** property is always "`Gecko`", in any browser. This property is kept only for compatibility purposes. > **Note:** Do not rely on this property to return a real product name. All browsers return "`Gecko`" as the value of this property. ## Value The string "`Gecko`". ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Navigator.appCodeName")}} - {{domxref("Navigator.appName")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/vendorsub/index.md
--- title: "Navigator: vendorSub property" short-title: vendorSub slug: Web/API/Navigator/vendorSub page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.vendorSub --- {{ApiRef}} {{Deprecated_Header}} The value of the **`Navigator.vendorSub`** property is always the empty string, in any browser. ## Value - The empty string ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/platform/index.md
--- title: "Navigator: platform property" short-title: platform slug: Web/API/Navigator/platform page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.platform --- {{APIRef("HTML DOM")}}{{Deprecated_Header}} The **`platform`** property read-only property of the {{domxref("Navigator")}} interface returns a string identifying the platform on which the user's browser is running. > **Note:** In general, you should whenever possible avoid writing code that uses methods or properties like this one to try to find out information about the user's environment, and instead write code that does [feature detection](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection). ## Value A string identifying the platform on which the user's browser is running; for example: `"MacIntel"`, `"Win32"`, `"Linux x86_64"`, `"Linux armv81"`. ## Examples `navigator.platform` should almost always be avoided in favor of [feature detection](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection). But there is one case where, among the options you could use, `navigator.platform` may be the least-bad option: When you need to show users advice about whether the modifier key for keyboard shortcuts is the `⌘` command key (found on Apple systems) rather than the `⌃` control key (on non-Apple systems): ```js let modifierKeyPrefix = "^"; // control key if ( navigator.platform.indexOf("Mac") === 0 || navigator.platform === "iPhone" ) { modifierKeyPrefix = "⌘"; // command key } ``` That is, check if `navigator.platform` starts with `"Mac"` or else is an exact match for `"iPhone"`, and then based on whether either of those is true, choose the modifier key your web application's UI will advise users to press in keyboard shortcuts. ## Usage notes On Windows, modern browsers return `"Win32"` even if running on a 64-bit version of Windows. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`navigator.userAgentData.platform`](/en-US/docs/Web/API/NavigatorUAData/platform)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/hardwareconcurrency/index.md
--- title: "Navigator: hardwareConcurrency property" short-title: hardwareConcurrency slug: Web/API/Navigator/hardwareConcurrency page-type: web-api-instance-property browser-compat: api.Navigator.hardwareConcurrency --- {{APIRef("HTML DOM")}} The **`navigator.hardwareConcurrency`** read-only property returns the number of logical processors available to run threads on the user's computer. ## Value A number between 1 and the number of logical processors potentially available to the user agent. Modern computers have multiple physical processor cores in their CPU (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. So a four-core CPU may offer eight **logical processor cores**, for example. The number of logical processor cores can be used to measure the number of threads which can effectively be run at once without them having to context switch. The browser may, however, choose to report a lower number of logical cores in order to represent more accurately the number of {{domxref("Worker")}}s that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system. ## Examples In this example, one {{domxref("Worker")}} is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a Boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use. This creates a pool of workers we can use to process requests later. ```js let workerList = []; for (let i = 0; i < window.navigator.hardwareConcurrency; i++) { let newWorker = { worker: new Worker("cpuworker.js"), inUse: false, }; workerList.push(newWorker); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Navigator")}} - {{domxref("WorkerNavigator")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/hid/index.md
--- title: "Navigator: hid property" short-title: hid slug: Web/API/Navigator/hid page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.hid --- {{APIRef("WebHID API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`Navigator.hid`** read-only property returns an {{domxref("HID")}} object providing methods for connecting to HID devices, listing attached HID devices, and event handlers for connected HID devices. Where a defined [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) blocks WebHID usage, the `Navigator.hid` property will not be available. ## Value An {{domxref("HID")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebHID API](/en-US/docs/Web/API/WebHID_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/getusermedia/index.md
--- title: "Navigator: getUserMedia() method" short-title: getUserMedia() slug: Web/API/Navigator/getUserMedia page-type: web-api-instance-method status: - deprecated browser-compat: api.Navigator.getUserMedia --- {{APIRef("Media Capture and Streams")}}{{deprecated_header}}{{SecureContext_Header}} The deprecated **`Navigator.getUserMedia()`** method prompts the user for permission to use up to one video input device (such as a camera or shared screen) and up to one audio input device (such as a microphone) as the source for a {{domxref("MediaStream")}}. If permission is granted, a `MediaStream` whose video and/or audio tracks come from those devices is delivered to the specified success callback. If permission is denied, no compatible input devices exist, or any other error condition occurs, the error callback is executed with an object describing what went wrong. If the user instead doesn't make a choice at all, neither callback is executed. > **Note:** This is a legacy method. > Please use the newer {{domxref("MediaDevices.getUserMedia", "navigator.mediaDevices.getUserMedia()")}} instead. > While technically not deprecated, this old callback version is marked as such, since the specification strongly encourages using the newer promise returning version. ## Syntax ```js-nolint getUserMedia(constraints, successCallback, errorCallback) ``` ### Parameters - `constraints` - : An object specifying the types of media to request, along with any requirements for each type. For details, see the [constraints](/en-US/docs/Web/API/MediaDevices/getUserMedia#parameters) section under the modern {{domxref("MediaDevices.getUserMedia()")}} method, as well as the article [Capabilities, constraints, and settings](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Constraints). - `successCallback` - : A function which is invoked when the request for media access is approved. The function is called with one parameter: the {{domxref("MediaStream")}} object that contains the media stream. Your callback can then assign the stream to the desired object (such as an {{HTMLElement("audio")}} or {{HTMLElement("video")}} element), as shown in the following example: ```js function successCallback(stream) { const video = document.querySelector("video"); video.srcObject = stream; video.onloadedmetadata = (e) => { // Do something with the video here. }; } ``` - `errorCallback` - : When the call fails, the function specified in the `errorCallback` is invoked with an object as its sole argument; this object is modeled on {{domxref("DOMException")}}. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Width and height Here's an example of using `getUserMedia()`, including code to cope with various browsers' prefixes. Note that this is the deprecated way of doing it: See the [Examples](/en-US/docs/Web/API/MediaDevices/getUserMedia#frame_rate) section under the {{domxref("MediaDevices.getUserMedia()")}} for modern examples. ```js navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (navigator.getUserMedia) { navigator.getUserMedia( { audio: true, video: { width: 1280, height: 720 } }, (stream) => { const video = document.querySelector("video"); video.srcObject = stream; video.onloadedmetadata = (e) => { video.play(); }; }, (err) => { console.error(`The following error occurred: ${err.name}`); }, ); } else { console.log("getUserMedia not supported"); } ``` ## Browser compatibility > **Warning:** New code should use {{domxref("MediaDevices.getUserMedia")}} instead. {{Compat}} ## See also - {{domxref("MediaDevices.getUserMedia()")}} that replaces this deprecated method. - [WebRTC](/en-US/docs/Web/API/WebRTC_API) - the introductory page to the API - [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API) - the API for the media stream objects - [Taking webcam photos](/en-US/docs/Web/API/Media_Capture_and_Streams_API/Taking_still_photos) - a tutorial on using `getUserMedia()` for taking photos rather than video.
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/vendor/index.md
--- title: "Navigator: vendor property" short-title: vendor slug: Web/API/Navigator/vendor page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.vendor --- {{APIRef("HTML DOM")}}{{Deprecated_Header}} The value of the {{DomXref("Navigator")}} **`vendor`** property is always either "`Google Inc.`", "`Apple Computer, Inc.`", or (in Firefox) the empty string. ## Value - Either "`Google Inc.`", "`Apple Computer, Inc.`", or (in Firefox) the empty string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/serviceworker/index.md
--- title: "Navigator: serviceWorker property" short-title: serviceWorker slug: Web/API/Navigator/serviceWorker page-type: web-api-instance-property browser-compat: api.Navigator.serviceWorker --- {{securecontext_header}}{{APIRef("Service Workers API")}} The **`serviceWorker`** read-only property of the {{domxref("Navigator")}} interface returns the {{domxref("ServiceWorkerContainer")}} object for the [associated document](https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window), which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}}. The feature may not be available in private mode. ## Value {{domxref("ServiceWorkerContainer")}}. ## Examples This code checks if the browser supports service workers. ```js if ("serviceWorker" in navigator) { // Supported! } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Service Worker API", "", "", "nocode")}} - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/activevrdisplays/index.md
--- title: "Navigator: activeVRDisplays property" short-title: activeVRDisplays slug: Web/API/Navigator/activeVRDisplays page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.Navigator.activeVRDisplays --- {{APIRef("WebVR API")}}{{SecureContext_Header}}{{Deprecated_Header}}{{Non-standard_Header}} The **`activeVRDisplays`** read-only property of the {{domxref("Navigator")}} interface returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is `true`). > **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). ## Value An array of {{domxref("VRDisplay")}} objects. ## Examples ```js function showActive() { const displays = navigator.activeVRDisplays; for (const display of displays) { console.log(`Display ${display.displayId} is active.`); } } ``` ## Specifications This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard. Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/). ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/canshare/index.md
--- title: "Navigator: canShare() method" short-title: canShare() slug: Web/API/Navigator/canShare page-type: web-api-instance-method browser-compat: api.Navigator.canShare --- {{APIRef("Web Share API")}}{{securecontext_header}} The **`Navigator.canShare()`** method of the [Web Share API](/en-US/docs/Web/API/Web_Share_API) returns `true` if the equivalent call to {{domxref("navigator.share()")}} would succeed. The method returns `false` if the data cannot be _validated_. Reasons the data might be invalid include: - The `data` parameter has been omitted or only contains properties with unknown values. Note that any properties that are not recognized by the user agent are ignored. - A URL is badly formatted. - Files are specified but the implementation does not support file sharing. - Sharing the specified data would be considered a "hostile share" by the user-agent. The Web Share API is gated by the [web-share](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/web-share) permission policy. The **`canShare()`** method will return `false` if the permission is supported but has not been granted. ## Syntax ```js-nolint canShare() canShare(data) ``` ### Parameters - `data` {{optional_inline}} - : An object defining the share data to test. Typically, an object with the same properties is passed to {{domxref("navigator.share()")}} if this call returns `true`. Properties that are unknown to the user agent are ignored; share data is only assessed on properties understood by the user agent. All properties are optional but at least one known data property must be specified or the method will return `false`. Possible values are: - `url`: A string representing a URL to be shared. - `text`: A string representing text to be shared. - `title`: A string representing the title to be shared. - `files`: An array of {{domxref("File")}} objects representing files to be shared. ### Return value Returns `true` if the specified `data` can be shared with {{domxref("Navigator.share()")}}, otherwise `false`. ## Examples ### Sending the MDN URL The example uses `navigator.canShare()` to check whether `navigator.share()` can share the specified data. #### HTML The HTML just creates a paragraph in which to display the result of the test. ```html <p class="result"></p> ``` #### JavaScript ```js let shareData = { title: "MDN", text: "Learn web development on MDN!", url: "https://developer.mozilla.org", }; const resultPara = document.querySelector(".result"); if (!navigator.canShare) { resultPara.textContent = "navigator.canShare() not supported."; } else if (navigator.canShare(shareData)) { resultPara.textContent = "navigator.canShare() supported. We can use navigator.share() to send the data."; } else { resultPara.textContent = "Specified data cannot be shared."; } ``` #### Result The box below should state whether `navigator.canShare()` is supported on this browser, and if so, whether or not we can use `navigator.share()` to share the specified data: {{EmbedLiveSample('Sending_the_MDN_URL')}} ### Feature checking example This method feature tests whether a particular data property is valid and shareable. If used with a single `data` property it will return `true` only if that property is valid and can be shared on the platform. The code below demonstrates verifying that a data property is supported. ```js // Feature that may not be supported let testShare = { someNewProperty: "Data to share" }; // Complex data that uses new key const shareData = { title: "MDN", text: "Learn web development on MDN!", url: "https://developer.mozilla.org", someNewProperty: "Data to share", }; // Test that the key is valid and supported before sharing if (navigator.canShare(testShare)) { // Use navigator.share() to share 'shareData' } else { // Handle case that new data property can't be shared. } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("navigator.share()")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/useragent/index.md
--- title: "Navigator: userAgent property" short-title: userAgent slug: Web/API/Navigator/userAgent page-type: web-api-instance-property browser-compat: api.Navigator.userAgent --- {{ApiRef("HTML DOM")}} The **`Navigator.userAgent`** read-only property returns the user agent string for the current browser. > **Note:** The specification asks browsers to provide as little information via this field as > possible. Never assume that the value of this property will stay the same in future > versions of the same browser. Try not to use it at all, or only for current and past > versions of a browser. New browsers may start using the same UA, or part of it, as an > older browser: you really have no guarantee that the browser agent is indeed the one > advertised by this property. > > Also keep in mind that users of a browser can change the value of this field if they > want (UA spoofing). Browser identification based on detecting the user agent string is **unreliable** and **is not recommended**, as the user agent string is user configurable. For example: - In Firefox, you can change the preference `general.useragent.override` in `about:config`. Some Firefox extensions do that; however, this only changes the HTTP header that gets sent and that is returned by `navigator.userAgent`. There might be other methods that utilize JavaScript code to identify the browser. - Opera 6+ allows users to set the browser identification string via a menu. ## Value A string specifying the complete user agent string the browser provides both in {{Glossary("HTTP")}} headers and in response to this and other related methods on the {{domxref("Navigator")}} object. The user agent string is built on a formal structure which can be decomposed into several pieces of info. Each of these pieces of info comes from other navigator properties which are also settable by the user. Gecko-based browsers comply with the following general structure: ```plain userAgent = appCodeName/appVersion number (Platform; Security; OS-or-CPU; Localization; rv: revision-version-number) product/productSub Application-Name Application-Name-version ``` ## Examples ```js alert(window.navigator.userAgent); // alerts "Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape6/6.1" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{httpheader("User-Agent")}} HTTP header
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/ink/index.md
--- title: "Navigator: ink property" short-title: ink slug: Web/API/Navigator/ink page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.ink --- {{SeeCompatTable}}{{APIRef("Ink API")}} The **`ink`** read-only property of the {{domxref("Navigator")}} interface returns an {{domxref("Ink")}} object for the current document, providing access to [Ink API](/en-US/docs/Web/API/Ink_API) functionality. ## Value An {{domxref('Ink')}} object. ## Example ```js async function inkInit() { const ink = navigator.ink; let presenter = await ink.requestPresenter({ presentationArea: canvas }); //... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/getinstalledrelatedapps/index.md
--- title: "Navigator: getInstalledRelatedApps() method" short-title: getInstalledRelatedApps() slug: Web/API/Navigator/getInstalledRelatedApps page-type: web-api-instance-method status: - experimental browser-compat: api.Navigator.getInstalledRelatedApps --- {{ ApiRef() }}{{SeeCompatTable}}{{SecureContext_Header}} The **`getInstalledRelatedApps()`** method returns a promise that resolves with an array of objects representing any related platform-specific apps or [Progressive Web Apps](/en-US/docs/Web/Progressive_web_apps) that the user has installed. This could be used for content personalization such as removing "install our app" banners from the web app if the platform-specific app and/or PWA is already installed. > **Note:** This method must be invoked in a top-level [secure context](/en-US/docs/Web/Security/Secure_Contexts), that is, not embedded in an {{htmlelement("iframe")}}. ## Description `getInstalledRelatedApps()` can be used to check for the installation of Universal Windows Platform (UWP) apps, Android apps, and PWAs that are related to the web app calling this method. To associate the invoking web app with a platform-specific app or PWA, two things must be done: 1. The invoking web app must be specified in the [`related_applications`](/en-US/docs/Web/Manifest/related_applications) member of its [manifest file](/en-US/docs/Web/Manifest). 2. The platform-specific app or PWA must have its relationship with the invoking app defined. Defining the relationship is done in a different way depending on the type of app: - An Android app does this via the [Digital Asset Links system](https://developers.google.com/digital-asset-links/v1/getting-started). - A Windows UWP app does this via [URI Handlers](https://docs.microsoft.com/en-us/windows/uwp/launch-resume/web-to-app-linking). - A PWA does this via: - A self-defining entry inside its own `related_applications` manifest member in the case of a PWA checking if it is installed on the underlying platform. - An `assetlinks.json` file in its [`/.well-known/`](https://tools.ietf.org/html/rfc5785) directory in the case of an app outside the scope of the PWA checking whether it is installed. See [Is your app installed? getInstalledRelatedApps() will tell you!](https://web.dev/articles/get-installed-related-apps) for more details on how to handle each one of these cases. > **Note:** Most supporting browsers provide their own install UI when an installable PWA is detected, which won't appear if it is already installed — see [Making PWAs installable > Installation from the web](/en-US/docs/Web/Progressive_web_apps/Guides/Making_PWAs_installable#installation_from_the_web). This can be suppressed using the {{domxref("Window.beforeinstallprompt_event", "beforeinstallprompt")}} event, which could also be combined with `getInstalledRelatedApps()` to suppress it based on a platform-specific app being available. See [Trigger installation from your PWA](/en-US/docs/Web/Progressive_web_apps/How_to/Trigger_install_prompt#responding_to_platform-specific_apps_being_installed) for further useful information. ## Syntax ```js-nolint getInstalledRelatedApps() ``` ### Parameters None. ### Return value A {{JSxRef("Promise")}} that fulfills with an array of objects representing any installed related apps. Each object can contain the following properties: - `id` {{optional_inline}} - : A string representing the ID used to represent the application on the specified platform. The exact form of the string will vary by platform. - `platform` - : A string representing the [platform](https://github.com/w3c/manifest/wiki/Platforms) (ecosystem or operating system) the related app is associated with. This can be: - `"chrome_web_store"`: A [Google Chrome Web Store](https://chrome.google.com/webstore) app. - `"play"`: A [Google Play Store](https://play.google.com/) app. - `"chromeos_play"`: A [ChromeOS Play](https://support.google.com/googleplay/answer/7021273) app. - `"webapp"`: A [Progressive Web App](/en-US/docs/Web/Progressive_web_apps). - `"windows"`: A [Windows Store](https://www.microsoft.com/store/apps) app. - `"f-droid"`: An [F-Droid](https://f-droid.org/) app. - `"amazon"`: An [Amazon App Store](https://www.amazon.com/gp/browse.html?node=2350149011) app. - `url` {{optional_inline}} - : A string representing the URL associated with the app. This is usually where you can read information about it and install it. - `version` {{optional_inline}} - : A string representing the related app's version. The related app information must have been previously specified in the [`related_applications`](/en-US/docs/Web/Manifest/related_applications) member of the invoking web app's [manifest file](/en-US/docs/Web/Manifest). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : The method was not invoked in a top-level browsing context. ## Examples ```js const relatedApps = await navigator.getInstalledRelatedApps(); // Dump all the returned related apps into a table in the console console.table(relatedApps); // Search for a specific installed platform-specific app const psApp = relatedApps.find((app) => app.id === "com.example.myapp"); if (psApp && doesVersionSendPushMessages(psApp.version)) { // There’s an installed platform-specific app that handles sending push messages // No need to handle this via the web app return; } ``` > **Note:** In this example, `doesVersionSendPushMessages()` is a theoretical developer-defined function; it is not provided by the browser. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Is your app installed? getInstalledRelatedApps() will tell you!](https://web.dev/articles/get-installed-related-apps)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/taintenabled/index.md
--- title: "Navigator: taintEnabled() method" short-title: taintEnabled() slug: Web/API/Navigator/taintEnabled page-type: web-api-instance-method status: - deprecated browser-compat: api.Navigator.taintEnabled --- {{APIRef("HTML DOM")}} {{deprecated_header}} The **`Navigator.taintEnabled()`** method always returns `false`. Tainting was a security method used by JavaScript 1.2. It has long been removed; this method only stays for maintaining compatibility with very old scripts. ## Syntax ```js-nolint taintEnabled() ``` ### Parameters None. ### Return value Always returns `false`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Navigator")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/cookieenabled/index.md
--- title: "Navigator: cookieEnabled property" short-title: cookieEnabled slug: Web/API/Navigator/cookieEnabled page-type: web-api-instance-property browser-compat: api.Navigator.cookieEnabled --- {{ApiRef("HTML DOM")}} `navigator.cookieEnabled` returns a Boolean value that indicates whether cookies are enabled or not. The property is read-only. ## Value A boolean. > **Note:** When the browser is configured to block third-party cookies, and `navigator.cookieEnabled` is invoked inside a third-party iframe, it returns `true` in Safari, Edge Spartan and IE (while trying to set a cookie in such scenario would fail). It returns `false` in Firefox and Chromium-based browsers. > **Note:** Web browsers may prevent writing certain cookies in certain scenarios. For example, Chrome-based browsers, as well as some experimental version of Firefox, does not allow creating cookies with [`SameSite=None`](/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value) attribute, unless they are created over HTTPS and with `Secure` attribute. ## Examples ```js if (!navigator.cookieEnabled) { // The browser does not support or is blocking cookies from being set. } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/language/index.md
--- title: "Navigator: language property" short-title: language slug: Web/API/Navigator/language page-type: web-api-instance-property browser-compat: api.Navigator.language --- {{APIRef("HTML DOM")}} The **`Navigator.language`** read-only property returns a string representing the preferred language of the user, usually the language of the browser UI. ## Value A string representing the language version as defined in {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}. Examples of valid language codes include "en", "en-US", "fr", "fr-FR", "es-ES", etc. Note that in Safari on iOS prior to 10.2, the country code returned is lowercase: "en-us", "fr-fr" etc. ## Examples ### Using Intl constructors to do language-specific formatting The {{jsxref("Intl")}} constructors allow formatting content to match the rules of a given locale. You can pass `navigator.language` to them to format content in the locale corresponding to the user's preferred language: ```js const date = new Date("2012-05-24"); const formattedDate = new Intl.DateTimeFormat(navigator.language).format(date); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("navigator.languages")}} - {{domxref("navigator")}} - {{jsxref("Intl")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/oscpu/index.md
--- title: "Navigator: oscpu property" short-title: oscpu slug: Web/API/Navigator/oscpu page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.oscpu --- {{ ApiRef("HTML DOM") }} {{Deprecated_Header}} The **`Navigator.oscpu`** property returns a string that identifies the current operating system. ## Value A string providing a string which identifies the operating system on which the browser is running. | Operating system | `oscpuInfo` string format | | ----------------------------- | ------------------------------------------------- | | OS/2 | `OS/2 Warp x (either 3, 4 or 4.5)` | | Windows CE | `WindowsCE x.y` | | Windows 64-bit (64-bit build) | `Windows NT x.y; Win64; x64` | | Windows 64-bit (32-bit build) | `Windows NT x.y; WOW64` | | Windows 32-bit | `Windows NT x.y` | | Mac OS X (PPC build) | `PowerPC Mac OS X version x.y` | | Mac OS X (i386/x64 build) | `Intel Mac OS X` or `macOS version x.y` | | Linux 64-bit (32-bit build) | Output of `uname -s` followed by `i686 on x86_64` | | Linux | Output of `uname -sm` | In this table `x.y` refers to the version of the operating system ## Examples ```js function osInfo() { alert(navigator.oscpu); } osInfo(); // alerts "Windows NT 6.0" for example ``` ## Usage notes Unless your code is privileged (chrome or at least has the UniversalBrowserRead privilege), it may get the value of the `general.oscpu.override` preference instead of the true platform. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/bluetooth/index.md
--- title: "Navigator: bluetooth property" short-title: bluetooth slug: Web/API/Navigator/bluetooth page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.bluetooth --- {{APIRef("Bluetooth API")}}{{SeeCompatTable}}{{secureContext_header}} The **`bluetooth`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("Bluetooth")}} object for the current document, providing access to [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API) functionality. ## Value A {{domxref("Bluetooth")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Bluetooth API](/en-US/docs/Web/API/Web_Bluetooth_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/mediadevices/index.md
--- title: "Navigator: mediaDevices property" short-title: mediaDevices slug: Web/API/Navigator/mediaDevices page-type: web-api-instance-property browser-compat: api.Navigator.mediaDevices --- {{securecontext_header}}{{APIRef("Media Capture and Streams")}} The **`mediaDevices`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("MediaDevices")}} object, which provides access to connected media input devices like cameras and microphones, as well as screen sharing. ## Value The {{domxref("MediaDevices")}} singleton object. Usually, you just use this object's members directly, such as by calling {{domxref("MediaDevices.getUserMedia", "navigator.mediaDevices.getUserMedia()")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API): The entry point to the documentation about the entire Media Capture and Streams API. - [WebRTC API](/en-US/docs/Web/API/WebRTC_API): Documentation about the WebRTC API, which is closely related.
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/appversion/index.md
--- title: "Navigator: appVersion property" short-title: appVersion slug: Web/API/Navigator/appVersion page-type: web-api-instance-property status: - deprecated browser-compat: api.Navigator.appVersion --- {{APIRef("HTML DOM")}} {{Deprecated_Header}} Returns either "`4.0`" or a string representing version information about the browser. > **Note:** Do not rely on this property to return the correct browser version. ## Value Either "`4.0`" or a string representing version information about the browser. ## Examples ```js alert(`Your browser version is reported as ${navigator.appVersion}`); ``` ## Notes The `window.navigator.userAgent` property may also contain the version number (for example "`Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape 6/6.1`"), but you should be aware of how easy it is to change the user agent string and "spoof" other browsers, platforms, or user agents, and also how cavalier the browser vendor themselves are with these properties. The `window.navigator.appVersion`, `window.navigator.appName` and `window.navigator.userAgent` properties have been used in "browser sniffing" code: scripts that attempt to find out what kind of browser you are using and adjust pages accordingly. This lead to the current situation, where browsers had to return fake values from these properties in order not to be locked out of some websites. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/useragentdata/index.md
--- title: "Navigator: userAgentData property" short-title: userAgentData slug: Web/API/Navigator/userAgentData page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.userAgentData --- {{securecontext_header}}{{APIRef("User-Agent Client Hints API")}}{{SeeCompatTable}} The **`userAgentData`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("NavigatorUAData")}} object which can be used to access the {{domxref("User-Agent Client Hints API")}}. ## Value A {{domxref("NavigatorUAData")}} object. ## Examples The following example prints the value of {{domxref("NavigatorUAData.brands")}} to the console. ```js console.log(navigator.userAgentData.brands); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Improving user privacy and developer experience with User-Agent Client Hints](https://developer.chrome.com/docs/privacy-security/user-agent-client-hints)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/mediacapabilities/index.md
--- title: "Navigator: mediaCapabilities property" short-title: mediaCapabilities slug: Web/API/Navigator/mediaCapabilities page-type: web-api-instance-property browser-compat: api.Navigator.mediaCapabilities --- {{APIRef("HTML DOM")}} The **`Navigator.mediaCapabilities`** read-only property returns a {{domxref("MediaCapabilities")}} object that can expose information about the decoding and encoding capabilities for a given format and output capabilities as defined by the [Media Capabilities API](/en-US/docs/Web/API/Media_Capabilities_API). ## Value A {{domxref("MediaCapabilities")}} object. ## Examples ```js navigator.mediaCapabilities .decodingInfo({ type: "file", audio: { contentType: "audio/mp3", channels: 2, bitrate: 132700, samplerate: 5200, }, }) .then((result) => { console.log( `This configuration is ${result.supported ? "" : "not "}supported,`, ); console.log(`${result.smooth ? "" : "not "}smooth, and`); console.log(`${result.powerEfficient ? "" : "not "}power efficient.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media Capabilities API](/en-US/docs/Web/API/Media_Capabilities_API) - {{domxref("Navigator")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/unregisterprotocolhandler/index.md
--- title: "Navigator: unregisterProtocolHandler() method" short-title: unregisterProtocolHandler() slug: Web/API/Navigator/unregisterProtocolHandler page-type: web-api-instance-method browser-compat: api.Navigator.unregisterProtocolHandler --- {{APIRef("HTML DOM")}}{{securecontext_header}} The **{{domxref("Navigator")}}** method **`unregisterProtocolHandler()`** removes a protocol handler for a given URL [scheme](#permitted_schemes). This method is the inverse of **`registerProtocolHandler()`**. ## Syntax ```js-nolint unregisterProtocolHandler(scheme, url) ``` ### Parameters - `scheme` - : A string containing the [permitted scheme](#permitted_schemes) in the protocol handler that will be unregistered. For example, you can unregister the handler for SMS text message links by passing the `"sms"` scheme. - `url` - : A string containing the URL of the handler. **This URL should match the one that was used to register the handler (e.g. it must include `%s`)**. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : The user agent blocked unregistration. This might happen if: - The scheme (protocol) is invalid, such as a scheme the browser handles itself (`https:`, `about:`, etc.) - The handler URL's {{Glossary("origin")}} does not match the origin of the page calling this API. - The browser requires that this function is called from a secure context. - The browser requires that the handler's URL be over HTTPS. - `SyntaxError` {{domxref("DOMException")}} - : The `%s` placeholder is missing from the handler URL. ## Permitted schemes For security reasons, `unregisterProtocolHandler()` restricts which schemes can be unregistered. A **custom scheme** may be unregistered as long as: - The custom scheme's name begins with `web+` - The custom scheme's name includes at least 1 letter after the `web+` prefix - The custom scheme has only lowercase ASCII letters in its name. For example, `web+burger`, as shown in the [Example](#examples) below. Otherwise, the scheme must be one of the following: - `bitcoin` - `ftp` - `ftps` - `geo` - `im` - `irc` - `ircs` - `magnet` - `mailto` - `matrix` - `mms` - `news` - `nntp` - `openpgp4fpr` - `sftp` - `sip` - `sms` - `smsto` - `ssh` - `tel` - `urn` - `webcal` - `wtai` - `xmpp` ## Examples If your site is `burgers.example.com`, and you have a `web+burger:` scheme, you can unregister the handler for it like so: ```js navigator.unregisterProtocolHandler( "web+burger", "https://burgers.example.com/?burger=%s", ); ``` This script must be run from the same origin as the handler URL (so any page at `https://burgers.example.com`), and the handler URL must be `http` or `https`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/contacts/index.md
--- title: "Navigator: contacts property" short-title: contacts slug: Web/API/Navigator/contacts page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.contacts --- {{APIRef("Contact Picker API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`contacts`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref('ContactsManager')}} interface which allows users to select entries from their contact list and share limited details of the selected entries with a website or application. ## Value A {{domxref('ContactsManager')}} object. Two successive calls return the same object. ## Examples The following code checks whether the Contact Picker API is supported. ```js const supported = "contacts" in navigator && "ContactsManager" in window; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [A Contact Picker for the Web](https://developer.chrome.com/docs/capabilities/web-apis/contact-picker) - [A Contact Picker demo on glitch](https://contact-picker.glitch.me/)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/requestmidiaccess/index.md
--- title: "Navigator: requestMIDIAccess() method" short-title: requestMIDIAccess() slug: Web/API/Navigator/requestMIDIAccess page-type: web-api-instance-method browser-compat: api.Navigator.requestMIDIAccess --- {{DefaultAPISidebar("Web MIDI API")}}{{SecureContext_Header}} The **`requestMIDIAccess()`** method of the {{domxref('Navigator')}} interface returns a {{jsxref('Promise')}} representing a request for access to MIDI devices on a user's system. This method is part of the [Web MIDI API](/en-US/docs/Web/API/Web_MIDI_API), which provides a means for accessing, enumerating, and manipulating MIDI devices. This method may prompt the user for access to MIDI devices available to their system, or it may use a previously established preference to grant or deny access. If permission is granted then the {{jsxref('Promise')}} resolves and a [`MIDIAccess`](/en-US/docs/Web/API/MIDIAccess) object is returned. ## Syntax ```js-nolint requestMIDIAccess() requestMIDIAccess(MIDIOptions) ``` ### Parameters - `MIDIOptions` {{optional_inline}} - : An {{jsxref('Object')}} representing options to pass into the method. These options are: - `sysex` - : A {{jsxref('Boolean')}} value that, if set to `true`, allows the ability to send and receive system exclusive (sysex) messages. The default value is `false`. - `software` - : A {{jsxref('Boolean')}} value that, if set to `true`, allows the system to utilize any installed software synthesizers. The default value is `false`. ### Return value A {{jsxref('Promise')}} that resolves with a [`MIDIAccess`](/en-US/docs/Web/API/MIDIAccess) object. ### Exceptions - `AbortError` {{domxref("DOMException")}} - : Thrown if the document or page is closed due to user navigation. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the underlying system raises any errors. - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the feature or options are not supported by the system. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the user or system denies the application from creating a [MIDIAccess](/en-US/docs/Web/API/MIDIAccess) object with the requested options, or if the document is not allowed to use the feature (for example, because of a [Permission Policy](/en-US/docs/Web/HTTP/Permissions_Policy), or because the user previously denied a permission request). ## Security requirements Access to the API is subject to the following constraints: - The method must be called in a [secure context](/en-US/docs/Web/Security/Secure_Contexts). - Access may be gated by the [`midi`](/en-US/docs/Web/HTTP/Headers/Permissions-Policy/midi) HTTP [Permission Policy](/en-US/docs/Web/HTTP/Permissions_Policy). - The user must explicitly grant permission to use the API though a user-agent specific mechanism, or have previously granted permission. Note that if access is denied by a permission policy it cannot be granted by a user permission. The permission status can be queried using the [Permissions API](/en-US/docs/Web/API/Permissions_API) method [`navigator.permissions.query()`](/en-US/docs/Web/API/Permissions/query), passing a permission descriptor with the `midi` permission and (optional) `sysex` property: ```js navigator.permissions.query({ name: "midi", sysex: true }).then((result) => { if (result.state === "granted") { // Access granted. } else if (result.state === "prompt") { // Using API will prompt for permission } // Permission was denied by user prompt or permission policy }); ``` ## Examples ### Request MIDI access In the following example, the {{domxref("Navigator.requestMIDIAccess()")}} method returns the {{domxref("MIDIAccess")}} object, which gives access to information about the input and output MIDI ports. ```js navigator.requestMIDIAccess().then((access) => { // Get lists of available MIDI controllers const inputs = access.inputs.values(); const outputs = access.outputs.values(); // … }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web MIDI API](/en-US/docs/Web/API/Web_MIDI_API) - [Introduction to Web MIDI](https://code.tutsplus.com/tutorials/introduction-to-web-midi--cms-25220)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/keyboard/index.md
--- title: "Navigator: keyboard property" short-title: keyboard slug: Web/API/Navigator/keyboard page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.keyboard --- {{SeeCompatTable}}{{APIRef("Keyboard API")}}{{SecureContext_Header}} The **`keyboard`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref('Keyboard')}} object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. ## Value A {{domxref('Keyboard')}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/getvrdisplays/index.md
--- title: "Navigator: getVRDisplays() method" short-title: getVRDisplays() slug: Web/API/Navigator/getVRDisplays page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Navigator.getVRDisplays --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`getVRDisplays()`** method of the {{domxref("Navigator")}} interface returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR displays connected to the computer. ## Syntax ```js-nolint getVRDisplays() ``` ### Parameters None. ### Return value A promise that resolves to an array of {{domxref("VRDisplay")}} objects. ## Examples See [`VRDisplay`](/en-US/docs/Web/API/VRDisplay#examples) for example code. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebVR API homepage](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/getautoplaypolicy/index.md
--- title: "Navigator: getAutoplayPolicy() method" short-title: getAutoplayPolicy() slug: Web/API/Navigator/getAutoplayPolicy page-type: web-api-instance-method status: - experimental browser-compat: api.Navigator.getAutoplayPolicy --- {{APIRef("HTML DOM")}}{{SeeCompatTable}} The **`getAutoplayPolicy()`** method of the _Autoplay Policy Detection API_ provides information about whether [autoplay](/en-US/docs/Web/Media/Autoplay_guide) of media elements and audio contexts is allowed, disallowed, or only allowed if the audio is muted. Applications can use this information to provide an appropriate user experience. For example, if the user agent policy only allows autoplay of inaudible content, the application might mute videos so that they can still autoplay. The method can be used to get either the broad autoplay policy for all items of a particular type in the document, or for specific media elements or audio contexts. ## Syntax ```js-nolint // Test autoplay policy for a particular media playing feature getAutoplayPolicy(type) // Test autoplay support for a specific element or context getAutoplayPolicy(element) getAutoplayPolicy(context) ``` ### Parameters The method must be called with one (and only one) of the following three parameters: - `type` {{optional_inline}} - : A string indicating the media playing _feature_ for which the broad autoplay policy is required. The supported values are: - `mediaelement` - : Get the broad autoplay policy for media elements in the document. Media elements are [`HTMLMediaElement`](/en-US/docs/Web/API/HTMLMediaElement) derived objects such as [`HTMLAudioElement`](/en-US/docs/Web/API/HTMLAudioElement) and [`HTMLVideoElement`](/en-US/docs/Web/API/HTMLVideoElement), and their corresponding tags {{HTMLElement("audio")}} and {{HTMLElement("video")}}. - `audiocontext` - : Get the broad autoplay policy for [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) players in the document. - `element` {{optional_inline}} - : A specific media element. This must be an [`HTMLMediaElement`](/en-US/docs/Web/API/HTMLMediaElement), including derived elements such as [`HTMLVideoElement`](/en-US/docs/Web/API/HTMLVideoElement) and [`HTMLAudioElement`](/en-US/docs/Web/API/HTMLAudioElement). - `context` {{optional_inline}} - : A specific [`AudioContext`](/en-US/docs/Web/API/AudioContext). ### Return value A string indicating the autoplay policy for the specified media feature type, element, or context. This will be a string containing one of the following values: - `allowed` - : Autoplay is allowed. - `allowed-muted` - : Autoplay is allowed only for inaudible media. This includes media that has no audio track, or for which the audio has been muted. - `disallowed` - : Autoplay is not allowed. Note that the autoplay policy returned for a `type` parameter is the _broad_ policy for items of the indicated type. On page load, all items of a type will have the same policy as the type. Once the user has interacted with the page/site, on some browsers individual items _may_ have a different policy to the corresponding type. ### Exceptions - `TypeError` - : The object passed to the method is not an allowed type. The allowed types include [`HTMLMediaElement`](/en-US/docs/Web/API/HTMLMediaElement) (or a derived element such as [`HTMLVideoElement`](/en-US/docs/Web/API/HTMLVideoElement) and [`HTMLAudioElement`](/en-US/docs/Web/API/HTMLAudioElement)), or [`AudioContext`](/en-US/docs/Web/API/AudioContext). ## Description "Autoplay" refers to any feature that causes content to begin to play without the user specifically requesting that playback begin. This includes the `autoplay` attribute in the HTML [`<video>`](/en-US/docs/Web/HTML/Element/video#autoplay) and [`<audio>`](/en-US/docs/Web/HTML/Element/audio#autoplay) elements, and using JavaScript code to start playback without any user interaction. User agents commonly block autoplay, or only allow inaudible content to autoplay, because unexpected sounds when a page first loads can result in a jarring and unpleasant user experience. The mechanisms used to determine whether content can autoplay or not, or only play for inaudible content, differ between user agents. The **`getAutoplayPolicy()`** method provides a standard mechanism to determine the policy for a particular user agent to autoplay a particular type or item of content. This enables application customization such as automatic muting of video on sites where autoplay of audible content is not allowed, or modifying the application to behave without autoplay. The recommended use of the method is to call it _on page load_ (or before the content playing elements are created) specifying the type of feature to check, and then configuring autoplay of media elements based on the result. For example, if the application wants to autoplay video elements that have an audio track, you might use the following code to mute the video if only inaudible content is allowed to play. ```js if (navigator.getAutoplayPolicy("mediaelement") === "allowed") { // Do nothing. The content can autoplay. } else if (navigator.getAutoplayPolicy("mediaelement") === "allowed-muted") { // Mute the video so it can autoplay. } else { // Autoplay disallowed. // Add a play button to the video element. } ``` The method can also be called to check the autoplay policy for a specific media element or audio context. As shown below, the code looks exactly the same except you pass in the specify item rather than the `type` string. ```js const video = document.getElementById("video_element_id"); if (navigator.getAutoplayPolicy(video) === "allowed") { // Do nothing. The content can autoplay. } else if (navigator.getAutoplayPolicy(video) === "allowed-muted") { // Mute the video so it can autoplay. } else { // Autoplay disallowed. // Add a play button to the video element. } ``` On page load, before the user has interacted with the page or site, the autoplay policy for the type and the individual items will be the same. After the user interacts with the site, page, or specific elements, the autoplay policy may change for the whole `type`. It is also possible that the policy for a specific item will change, even if the overall policy for the `type` does not. There is no way to be notified that the autoplay policy has changed. For this reason, while you can check the policy for a type or item at any time, usually you will only do so on page load or before attempting to play content. ## Examples ### Checking if the feature is supported The code below shows how to check if `navigator.getAutoplayPolicy()` is supported: ```html hidden <div id="reportResult"></div> ``` ```js hidden const log = document.getElementById("reportResult"); ``` ```js if (!navigator.getAutoplayPolicy) { log.textContent = "navigator.getAutoplayPolicy() not supported."; } else { log.textContent = "navigator.getAutoplayPolicy() is supported."; } ``` The result of running the code on this page is: {{EmbedLiveSample('Checking if the feature is supported', '', '50')}} ### Test autoplay policy for media element type This example demonstrates how you can check the autoplay policy for the media elements type. The code creates a video element that has the [`autoplay`](/en-US/docs/Web/API/HTMLMediaElement/autoplay) attribute and is not muted by default. If the autoplay policy is "allowed-muted", the video will be muted to allow it to play. #### HTML The HTML below has a `div` element that is used as a reporting log, and also displays a [`<video>`](/en-US/docs/Web/HTML/Element/video) that has the [`autoplay`](/en-US/docs/Web/API/HTMLMediaElement/autoplay) attribute. This should not be muted by default, and should play automatically if autoplay is not blocked. ```html <div id="reportResult"></div> <!-- Simple video example --> <!-- 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org --> <!-- Poster from peach.blender.org --> <video id="bunny_vid" autoplay controls src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4" poster="https://peach.blender.org/wp-content/uploads/title_anouncement.jpg?x11217" width="620"> Sorry, your browser doesn't support embedded videos, but don't worry, you can <a href="https://archive.org/details/BigBuckBunny_124">download it</a> and watch it with your favorite video player! </video> ``` #### JavaScript The code reports whether or not the `getAutoplayPolicy()` method is supported, and if it is, the policy for media elements. If the policy is `allowed-muted`, only muted videos can be played. In this case we add some text explaining what is happening and mute the video. ```js const log = document.getElementById("reportResult"); const video = document.getElementById("bunny_vid"); if (!navigator.getAutoplayPolicy) { log.textContent = "navigator.getAutoplayPolicy() not supported. It may or may not autoplay, depending on the browser!"; } else { log.textContent = `Autoplay policy for media elements is: ${navigator.getAutoplayPolicy( "mediaelement", )}. `; if (navigator.getAutoplayPolicy("mediaelement") === "allowed-muted") { // Mute the video so it can autoplay video.muted = true; log.textContent += "Video has been muted to allow it to autoplay."; } } ``` Note that you might similarly check for `allowed` and `disallowed`. #### Result The video is displayed below along with information about whether the `getAutoplayPolicy()` method is supported, and if so, the policy. If `getAutoplayPolicy()` is supported and the policy is `allowed`, the video will play automatically with sound. If the policy is `allowed-muted`, the video will play without sound. {{EmbedLiveSample('Test autoplay policy for media elements', '', '400')}} Note that if `getAutoplayPolicy()` is not supported, the video will either autoplay with audio or not play. The code has no control over this behavior: you're at the mercy of the browser implementation! ### Test autoplay policy for a specific media element This example shows how you can check whether a specific media element will autoplay. It is almost exactly the same as the previous example (an `AudioContext` check would also be similar). Note that it is possible for specific elements to autoplay even if a check on the `mediaelement` type indicates that autoplay is `disallowed`; in other words, a check on a specific element is more reliable (though it doesn't matter on page load). The code creates a video element that has the [`autoplay`](/en-US/docs/Web/API/HTMLMediaElement/autoplay) attribute. If the autoplay policy is "allowed-muted", the video will be muted to allow it to play. #### HTML The HTML below has a `div` element that is used as a reporting log, and also displays a [`<video>`](/en-US/docs/Web/HTML/Element/video) that has the [`autoplay`](/en-US/docs/Web/API/HTMLMediaElement/autoplay) attribute. This should not be muted by default, and should play automatically if autoplay is not blocked. ```html <div id="reportResult"></div> <!-- Simple video example --> <!-- 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org --> <!-- Poster from peach.blender.org --> <video id="bunny_vid" autoplay controls src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4" poster="https://peach.blender.org/wp-content/uploads/title_anouncement.jpg?x11217" width="620"> Sorry, your browser doesn't support embedded videos, but don't worry, you can <a href="https://archive.org/details/BigBuckBunny_124">download it</a> and watch it with your favorite video player! </video> ``` #### JavaScript The code reports whether or not the `getAutoplayPolicy()` method is supported, and if it is, the policy for media elements. If the policy is `allowed-muted`, only muted videos can be played, so the code mutes the video. ```js const log = document.getElementById("reportResult"); const video = document.getElementById("bunny_vid"); if (!navigator.getAutoplayPolicy) { log.textContent = "navigator.getAutoplayPolicy() not supported. It may or may not autoplay, depending on the browser!"; } else { // Here we pass in the HTMLVideoElement to check log.textContent = `navigator.getAutoplayPolicy(video) == ${navigator.getAutoplayPolicy( "mediaelement", )}`; if (navigator.getAutoplayPolicy(video) === "allowed-muted") { // Mute the video so it can autoplay video.muted = true; log.textContent += "Video has been muted to allow it to autoplay."; } } ``` #### Result The result is the same as in the previous example: - The video should autoplay with sound if `allowed` is returned, and no sound if `allowed-muted` is returned. - If `getAutoplayPolicy()` is not supported, the video autoplay behavior depends only on the browser. {{EmbedLiveSample('Test autoplay policy for a specific media element', '', '400')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Autoplay guide for media and Web Audio APIs](/en-US/docs/Web/Media/Autoplay_guide)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/gpu/index.md
--- title: "Navigator: gpu property" short-title: gpu slug: Web/API/Navigator/gpu page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.gpu --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`Navigator.gpu`** read-only property returns the {{domxref("GPU")}} object for the current browsing context, which is the entry point for the {{domxref("WebGPU_API", "WebGPU API", "", "nocode")}}. ## Value An {{domxref("GPU")}} object. ## Examples ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const device = await adapter.requestDevice(); //... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WebGPU_API", "WebGPU API", "", "nocode")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/maxtouchpoints/index.md
--- title: "Navigator: maxTouchPoints property" short-title: maxTouchPoints slug: Web/API/Navigator/maxTouchPoints page-type: web-api-instance-property browser-compat: api.Navigator.maxTouchPoints --- {{APIRef("HTML DOM")}} The **`maxTouchPoints`** read-only property of the {{domxref("Navigator")}} interface returns the maximum number of simultaneous touch contact points are supported by the current device. ## Value A number. ## Examples ```js if (navigator.maxTouchPoints > 1) { // browser supports multi-touch } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/setappbadge/index.md
--- title: "Navigator: setAppBadge() method" short-title: setAppBadge() slug: Web/API/Navigator/setAppBadge page-type: web-api-instance-method browser-compat: api.Navigator.setAppBadge --- {{APIRef("Badging API")}}{{securecontext_header}} The **`setAppBadge()`** method of the {{domxref("Navigator")}} interface sets a badge on the icon associated with this app. If a value is passed to the method, this will be set as the value of the badge. Otherwise the badge will display as a dot, or other indicator as defined by the platform. ## Syntax ```js-nolint setAppBadge() setAppBadge(contents) ``` ### Parameters - `contents` {{optional_inline}} - : A {{jsxref("number")}} which will be used as the value of the badge. If `contents` is `0` then the badge will be set to `nothing`, indicating a cleared badge. ### Return value A {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the document is not fully active. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the call was blocked by the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy). - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if {{domxref('PermissionStatus.state')}} is not `granted`. ## Examples In the example below an unread count is passed to `setAppBadge()`. The badge should then display `30`. ```js const unread = 30; navigator.setAppBadge(unread); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Badging for app icons](https://developer.chrome.com/docs/capabilities/web-apis/badging-api/)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/xr/index.md
--- title: "Navigator: xr property" short-title: xr slug: Web/API/Navigator/xr page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.xr --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}}{{SeeCompatTable}} The read-only **`xr`** property provided by the {{domxref("Navigator")}} interface returns an {{domxref("XRSystem")}} object which can be used to access the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API). ## Value The {{domxref("XRSystem")}} object used to interface with the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) in the current context. This can be used to present augmented and/or virtual reality imagery to the user. ## Examples Each {{domxref("Window")}} has its own instance of {{domxref("Navigator")}}, which can be accessed as {{domxref("Window.navigator","window.navigator")}} or as {{domxref("Window.navigator", "navigator")}}. At the same time, a new {{domxref("XRSystem")}} instance is also created and attached to the `navigator` instance as {{domxref("Navigator.xr", "navigator.xr")}}. If the `xr` property exists, you can use it to access the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API). To determine if WebXR is available, you can do something like this: ```js if ("xr" in window.navigator) { /* WebXR can be used! */ } else { /* WebXR isn't available */ } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebGL API](/en-US/docs/Web/API/WebGL_API): 2D and 3D accelerated graphics for the web - [Canvas API](/en-US/docs/Web/API/Canvas_API): 2D graphics API
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/connection/index.md
--- title: "Navigator: connection property" short-title: connection slug: Web/API/Navigator/connection page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.connection --- {{APIRef("Network Information API")}}{{SeeCompatTable}} The **`Navigator.connection`** read-only property returns a {{domxref("NetworkInformation")}} object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered. This could be used to select high definition content or low definition content based on the user's connection. ## Value A {{domxref("NetworkInformation")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Online and offline events](/en-US/docs/Web/API/Navigator/onLine)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/javaenabled/index.md
--- title: "Navigator: javaEnabled() method" short-title: javaEnabled() slug: Web/API/Navigator/javaEnabled page-type: web-api-instance-method status: - deprecated browser-compat: api.Navigator.javaEnabled --- {{APIRef("HTML DOM")}}{{Deprecated_Header}} This method always returns false. ## Syntax ```js-nolint javaEnabled() ``` ### Parameters None. ### Return value The boolean value `false`. ## Examples ```js if (window.navigator.javaEnabled()) { // code will never be executed; the condition is always false } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/locks/index.md
--- title: "Navigator: locks property" short-title: locks slug: Web/API/Navigator/locks page-type: web-api-instance-property browser-compat: api.Navigator.locks --- {{APIRef("Web Locks API")}}{{securecontext_header}} The **`locks`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("LockManager")}} object which provides methods for requesting a new {{domxref('Lock')}} object and querying for an existing `Lock` object. ## Value A {{domxref("LockManager")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/webdriver/index.md
--- title: "Navigator: webdriver property" short-title: webdriver slug: Web/API/Navigator/webdriver page-type: web-api-instance-property browser-compat: api.Navigator.webdriver --- {{APIRef("WebDriver")}} The **`webdriver`** read-only property of the {{domxref("navigator")}} interface indicates whether the user agent is controlled by automation. It defines a standard way for co-operating user agents to inform the document that it is controlled by [WebDriver](/en-US/docs/Web/WebDriver), for example, so that alternate code paths can be triggered during automation. The `navigator.webdriver` property is true when in: - Chrome - : The `--enable-automation` or the `--headless` flag or the `--remote-debugging-port` is used. - Firefox - : The `marionette.enabled` preference or `--marionette` flag is passed. ## Value A {{JSxRef("Boolean")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/permissions/index.md
--- title: "Navigator: permissions property" short-title: permissions slug: Web/API/Navigator/permissions page-type: web-api-instance-property browser-compat: api.Navigator.permissions --- {{APIRef("HTML DOM")}} The **`Navigator.permissions`** read-only property returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the [Permissions API](/en-US/docs/Web/API/Permissions_API). ## Value A {{domxref("Permissions")}} object. ## Examples ```js navigator.permissions.query({ name: "geolocation" }).then((result) => { if (result.state === "granted") { showMap(); } else if (result.state === "prompt") { showButtonToEnableMap(); } // Don't do anything if the permission was denied. }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Permissions API](/en-US/docs/Web/API/Permissions_API) - {{domxref("Navigator")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/storage/index.md
--- title: "Navigator: storage property" short-title: storage slug: Web/API/Navigator/storage page-type: web-api-instance-property browser-compat: api.Navigator.storage --- {{securecontext_header}}{{APIRef("Storage")}} The **`Navigator.storage`** read-only property returns the singleton {{domxref("StorageManager")}} object used to access the overall storage capabilities of the browser for the current site or app. The returned object lets you examine and configure persistence of data stores and learn approximately how much more space your browser has available for local storage use. ## Value A {{domxref("StorageManager")}} object you can use to maintain persistence for stored data, as well as to determine roughly how much room there is for data to be stored. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("StorageManager")}} - {{domxref("Navigator")}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/scheduling/index.md
--- title: "Navigator: scheduling property" short-title: scheduling slug: Web/API/Navigator/scheduling page-type: web-api-instance-property status: - experimental browser-compat: api.Navigator.scheduling --- {{SeeCompatTable}}{{APIRef("Prioritized Task Scheduling API")}} The **`scheduling`** read-only property of the {{domxref("Navigator")}} interface returns a {{domxref("Scheduling")}} object for the current document, which provides methods and properties to control scheduling tasks. ## Value A {{domxref("Scheduling")}} object. ## Example See the {{domxref("Scheduling.isInputPending()")}} page for a full example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Faster input events with Facebook's first browser API contribution](https://engineering.fb.com/2019/04/22/developer-tools/isinputpending-api/) on engineering.fb.com (2019) - [Better JS scheduling with isInputPending()](https://developer.chrome.com/docs/capabilities/web-apis/isinputpending) on developer.chrome.com (2020) - [Optimizing long tasks](https://web.dev/articles/optimize-long-tasks#yield_only_when_necessary) on web.dev (2022)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/credentials/index.md
--- title: "Navigator: credentials property" short-title: credentials slug: Web/API/Navigator/credentials page-type: web-api-instance-property browser-compat: api.Navigator.credentials --- {{securecontext_header}}{{APIRef("Credential Management API")}} The **`credentials`** read-only property of the {{domxref("Navigator")}} interface returns the {{domxref("CredentialsContainer")}} object associated with the current document, which exposes methods to request credentials. The {{domxref("CredentialsContainer")}} interface also notifies the user agent when an interesting event occurs, such as a successful sign-in or sign-out. This interface can be used for feature detection. ## Value A {{domxref("CredentialsContainer")}} object. ## Examples ```js if ("credentials" in navigator) { navigator.credentials.get({ password: true }).then((creds) => { //Do something with the credentials. }); } else { //Handle sign-in the way you did before. } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/globalprivacycontrol/index.md
--- title: "Navigator: globalPrivacyControl property" short-title: globalPrivacyControl slug: Web/API/Navigator/globalPrivacyControl page-type: web-api-instance-property status: - experimental - non-standard browser-compat: api.Navigator.globalPrivacyControl --- {{APIRef("DOM")}}{{SeeCompatTable}}{{non-standard_header}} The **`Navigator.globalPrivacyControl`** read-only property returns the user's [Global Privacy Control](https://globalprivacycontrol.org/) setting for the current website. This setting indicates whether the user consents to the website or service selling or sharing their personal information with third parties. The value of the property reflects that of the {{httpheader("Sec-GPC")}} HTTP header. ## Value `true` if the user explicitly _does not_ provide consent to sell or share their data. `false` if the user either grants consent, or has not indicated a preference. ## Example ```js console.log(navigator.globalPrivacyControl); // "true" if the user has specifically indicated they do not want their data shared or sold, otherwise "false". ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("Sec-GPC")}} header - [globalprivacycontrol.org](https://globalprivacycontrol.org/) - [Global Privacy Control Spec](https://privacycg.github.io/gpc-spec/) - [Do Not Track on Wikipedia](https://en.wikipedia.org/wiki/Do_Not_Track)
0
data/mdn-content/files/en-us/web/api/navigator
data/mdn-content/files/en-us/web/api/navigator/requestmediakeysystemaccess/index.md
--- title: "Navigator: requestMediaKeySystemAccess() method" short-title: requestMediaKeySystemAccess() slug: Web/API/Navigator/requestMediaKeySystemAccess page-type: web-api-instance-method browser-compat: api.Navigator.requestMediaKeySystemAccess --- {{DefaultAPISidebar("Encrypted Media Extensions")}}{{SecureContext_Header}} The **`Navigator.requestMediaKeySystemAccess()`** method returns a {{jsxref('Promise')}} which delivers a {{domxref('MediaKeySystemAccess')}} object that can be used to access a particular media key system, which can in turn be used to create keys for decrypting a media stream. This method is part of the [Encrypted Media Extensions API](/en-US/docs/Web/API/Encrypted_Media_Extensions_API), which brings support for encrypted media and DRM-protected video to the web. This method may have user-visible effects such as asking for permission to access one or more system resources. Consider that when deciding when to call `requestMediaKeySystemAccess()`; you don't want those requests to happen at inconvenient times. As a general rule, this function should be called only when it's about time to create and use a {{domxref("MediaKeys")}} object by calling the returned {{domxref("MediaKeySystemAccess")}} object's {{domxref("MediaKeySystemAccess.createMediaKeys", "createMediaKeys()")}} method. ## Syntax ```js-nolint requestMediaKeySystemAccess(keySystem, supportedConfigurations) ``` ### Parameters - `keySystem` - : A string identifying the key system. For example `com.example.somesystem` or `org.w3.clearkey`. - `supportedConfigurations` - : A non-empty {{jsxref('Array')}} of objects conforming to the object returned by {{domxref("MediaKeySystemAccess.getConfiguration")}}. The first element with a satisfiable configuration will be used. ### Return value A {{jsxref('Promise')}} that, when resolved, delivers a {{domxref('MediaKeySystemAccess')}} object to your fulfillment handler function. The fulfillment handler receives as input just one parameter: - `mediaKeySystemAccess` - : A {{domxref("MediaKeySystemAccess")}} object representing the media key system configuration described by `keySystem` and `supportedConfigurations` ### Exceptions In case of an error, the returned {{jsxref('Promise')}} is rejected with a {{domxref('DOMException')}} whose name indicates what kind of error occurred. - `NotSupportedError` {{domxref("DOMException")}} - : Either the specified `keySystem` isn't supported by the platform or the browser, or none of the configurations specified by `supportedConfigurations` can be satisfied (if, for example, none of the `codecs` specified in `contentType` are available). - `SecurityError` {{domxref("DOMException")}} - : Use of this feature was blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). - {{jsxref("TypeError")}}` - : Either `keySystem` is an empty string or the `supportedConfigurations` array is empty. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### Firefox compatibility notes Firefox 55 outputs a warning to the console if a candidate `MediaKeySystemConfiguration` included in `supportedConfigurations` includes an `audioCapabilities` or `videoCapabilities` object whose value of `contentType` doesn't specify a `"codecs"` substring defining which codecs within the media wrapper format should be allowed. For example: ```js example-bad const clearKeyOptions = [ { initDataTypes: ["keyids", "webm"], audioCapabilities: [{ contentType: "audio/webm" }], videoCapabilities: [{ contentType: "video/webm" }], }, ]; navigator .requestMediaKeySystemAccess("org.w3.clearkey", clearKeyOptions) .then((keySystemAccess) => { /* use the access to get create keys */ }); ``` The code above works in Firefox up to version 55, but version 55 onwards will output a warning to console, because `"codecs"` is not included in the `contentType` strings. This could be corrected as follows: ```js example-good const clearKeyOptions = [ { initDataTypes: ["keyids", "webm"], audioCapabilities: [ { contentType: 'audio/webm; codecs="opus"' }, { contentType: 'audio/webm; codecs="vorbis"' }, ], videoCapabilities: [ { contentType: 'video/webm; codecs="vp9"' }, { contentType: 'video/webm; codecs="vp8"' }, ], }, ]; navigator .requestMediaKeySystemAccess("org.w3.clearkey", clearKeyOptions) .then((keySystemAccess) => { /* use the access to get create keys */ }); ``` In this revised example, the audio and video capabilities include possible codecs which should be permitted, and therefore are valid requests. ## See also - [Encrypted Media Extensions API](/en-US/docs/Web/API/Encrypted_Media_Extensions_API) - [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API) - [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
0