Using files from web applications - Web APIs

Using files from web applications
=================================

**Note:** This feature is available in Web Workers

Using the File API, web content can ask the user to select local files and then read the contents of those files. This selection can be done by either using an HTML `<input type="file">` element or by drag and drop.

Accessing selected file(s)
--------------------------

Consider this HTML:

```html
<input type="file" id="input" multiple />
```

The File API makes it possible to access a `FileList` containing `File` objects representing the files selected by the user.

The `multiple` attribute on the `input` element allows the user to select multiple files.

Accessing the first selected file using a classical DOM selector:

```js
const selectedFile = document.getElementById("input").files[0];
```

### Accessing selected file(s) on a change event

It is also possible (but not mandatory) to access the `FileList` through the `change` event. You need to use `EventTarget.addEventListener()` to add the `change` event listener, like this:

```js
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  const fileList = this.files; /\* now you can work with the file list \*/
}
```

Getting information about selected file(s)
------------------------------------------

The `FileList` object provided by the DOM lists all of the files selected by the user, each specified as a `File` object. You can determine how many files the user selected by checking the value of the file list's `length` attribute:

```js
const numFiles = fileList.length;
```

Individual `File` objects can be retrieved by accessing the list as an array.

There are three attributes provided by the `File` object that contain useful information about the file.

`name`

The file's name as a read-only string. This is just the file name, and does not include any path information.

`size`

The size of the file in bytes as a read-only 64-bit integer.

`type`

The MIME type of the file as a read-only string or `""` if the type couldn't be determined.

### Example: Showing file(s) size

The following example shows a possible use of the `size` property:

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>File(s) size</title>
  </head>

  <body>
    <form name="uploadForm">
      <div>
        <input id="uploadInput" type="file" multiple />
        <label for="fileNum">Selected files:</label>
        <output id="fileNum">0</output>;
        <label for="fileSize">Total size:</label>
        <output id="fileSize">0</output>
      </div>
      <div><input type="submit" value="Send file" /></div>
    </form>

    <script>
 const uploadInput = document.getElementById("uploadInput");
 uploadInput.addEventListener(
 "change",
 () => {
 // Calculate total size
 let numberOfBytes = 0;
 for (const file of uploadInput.files) {
 numberOfBytes += file.size;
 }

 // Approximate to the closest prefixed unit
 const units = [
 "B",
 "KiB",
 "MiB",
 "GiB",
 "TiB",
 "PiB",
 "EiB",
 "ZiB",
 "YiB",
 ];
 const exponent = Math.min(
 Math.floor(Math.log(numberOfBytes) / Math.log(1024)),
 units.length - 1,
 );
 const approx = numberOfBytes / 1024 \*\* exponent;
 const output =
 exponent === 0
 ? `${numberOfBytes} bytes`
 : `${approx.toFixed(3)} ${
 units[exponent]
 } (${numberOfBytes} bytes)`;

 document.getElementById("fileNum").textContent =
 uploadInput.files.length;
 document.getElementById("fileSize").textContent = output;
 },
 false,
 );
 </script>
  </body>
</html>
```

Using hidden file input elements using the click() method
---------------------------------------------------------

You can hide the admittedly ugly file `<input>` element and present your own interface for opening the file picker and displaying which file or files the user has selected. You can do this by styling the input element with `display:none` and calling the `click()` method on the `<input>` element.

Consider this HTML:

```html
<input
 type="file"
 id="fileElem"
 multiple
 accept="image/\*"
 style="display:none" />
<button id="fileSelect" type="button">Select some files</button>
```

The code that handles the `click` event can look like this:

```js
const fileSelect = document.getElementById("fileSelect");
const fileElem = document.getElementById("fileElem");

fileSelect.addEventListener(
  "click",
  (e) => {
    if (fileElem) {
      fileElem.click();
    }
  },
  false,
);
```

You can style the `<button>` however you wish.

Using a label element to trigger a hidden file input element
------------------------------------------------------------

To allow opening the file picker without using JavaScript (the click() method), a `<label>` element can be used. Note that in this case the input element must not be hidden using `display: none` (nor `visibility: hidden`), otherwise the label would not be keyboard-accessible. Use the visually-hidden technique instead.

Consider this HTML:

```html
<input
 type="file"
 id="fileElem"
 multiple
 accept="image/\*"
 class="visually-hidden" />
<label for="fileElem">Select some files</label>
```

and this CSS:

```css
.visually-hidden {
  position: absolute !important;
  height: 1px;
  width: 1px;
  overflow: hidden;
  clip: rect(1px, 1px, 1px, 1px);
}

input.visually-hidden:is(:focus, :focus-within) + label {
  outline: thin dotted;
}
```

There is no need to add JavaScript code to call `fileElem.click()`. Also in this case you can style the label element as you wish. You need to provide a visual cue for the focus status of the hidden input field on its label, be it an outline as shown above, or background-color or box-shadow. (As of time of writing, Firefox doesn't show this visual cue for `<input type="file">` elements.)

Selecting files using drag and drop
-----------------------------------

You can also let the user drag and drop files into your web application.

The first step is to establish a drop zone. Exactly what part of your content will accept drops may vary depending on the design of your application, but making an element receive drop events is easy:

```js
let dropbox;

dropbox = document.getElementById("dropbox");
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
```

In this example, we're turning the element with the ID `dropbox` into our drop zone. This is done by adding listeners for the `dragenter`, `dragover`, and `drop` events.

We don't actually need to do anything with the `dragenter` and `dragover` events in our case, so these functions are both simple. They just stop propagation of the event and prevent the default action from occurring:

```js
function dragenter(e) {
  e.stopPropagation();
  e.preventDefault();
}

function dragover(e) {
  e.stopPropagation();
  e.preventDefault();
}
```

The real magic happens in the `drop()` function:

```js
function drop(e) {
  e.stopPropagation();
  e.preventDefault();

  const dt = e.dataTransfer;
  const files = dt.files;

  handleFiles(files);
}
```

Here, we retrieve the `dataTransfer` field from the event, pull the file list out of it, and then pass that to `handleFiles()`. From this point on, handling the files is the same whether the user used the `input` element or drag and drop.

Example: Showing thumbnails of user-selected images
---------------------------------------------------

Let's say you're developing the next great photo-sharing website and want to use HTML to display thumbnail previews of images before the user actually uploads them. You can establish your input element or drop zone as discussed previously and have them call a function such as the `handleFiles()` function below.

```js
function handleFiles(files) {
  for (let i = 0; i < files.length; i++) {
    const file = files[i];

    if (!file.type.startsWith("image/")) {
      continue;
    }

    const img = document.createElement("img");
    img.classList.add("obj");
    img.file = file;
    preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed.

    const reader = new FileReader();
    reader.onload = (e) => {
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
  }
}
```

Here our loop handling the user-selected files looks at each file's `type` attribute to see if its MIME type begins with the string "`image/`"). For each file that is an image, we create a new `img` element. CSS can be used to establish any pretty borders or shadows and to specify the size of the image, so that doesn't need to be done here.

Each image has the CSS class `obj` added to it, making it easy to find in the DOM tree. We also add a `file` attribute to each image specifying the `File` for the image; this will let us fetch the images for actual upload later. We use `Node.appendChild()` to add the new thumbnail to the preview area of our document.

Next, we establish the `FileReader` to handle asynchronously loading the image and attaching it to the `img` element. After creating the new `FileReader` object, we set up its `onload` function and then call `readAsDataURL()` to start the read operation in the background. When the entire contents of the image file are loaded, they are converted into a `data:` URL which is passed to the `onload` callback. Our implementation of this routine sets the `img` element's `src` attribute to the loaded image which results in the image appearing in the thumbnail on the user's screen.

Using object URLs
-----------------

The DOM `URL.createObjectURL()` and `URL.revokeObjectURL()` methods let you create simple URL strings that can be used to reference any data that can be referred to using a DOM `File` object, including local files on the user's computer.

When you have a `File` object you'd like to reference by URL from HTML, you can create an object URL for it like this:

```js
const objectURL = window.URL.createObjectURL(fileObj);
```

The object URL is a string identifying the `File` object. Each time you call `URL.createObjectURL()`, a unique object URL is created even if you've created an object URL for that file already. Each of these must be released. While they are released automatically when the document is unloaded, if your page uses them dynamically you should release them explicitly by calling `URL.revokeObjectURL()`:

```js
URL.revokeObjectURL(objectURL);
```

Example: Using object URLs to display images
--------------------------------------------

This example uses object URLs to display image thumbnails. In addition, it displays other file information including their names and sizes.

The HTML that presents the interface looks like this:

```html
<input
 type="file"
 id="fileElem"
 multiple
 accept="image/\*"
 style="display:none" />
<a href="#" id="fileSelect">Select some files</a>
<div id="fileList">
  <p>No files selected!</p>
</div>
```

This establishes our file `<input>` element as well as a link that invokes the file picker (since we keep the file input hidden to prevent that less-than-attractive user interface from being displayed). This is explained in the section Using hidden file input elements using the click() method, as is the method that invokes the file picker.

The `handleFiles()` method follows:

```js
const fileSelect = document.getElementById("fileSelect"),
  fileElem = document.getElementById("fileElem"),
  fileList = document.getElementById("fileList");

fileSelect.addEventListener(
  "click",
  (e) => {
    if (fileElem) {
      fileElem.click();
    }
    e.preventDefault(); // prevent navigation to "#"
  },
  false,
);

fileElem.addEventListener("change", handleFiles, false);

function handleFiles() {
  if (!this.files.length) {
    fileList.innerHTML = "<p>No files selected!</p>";
  } else {
    fileList.innerHTML = "";
    const list = document.createElement("ul");
    fileList.appendChild(list);
    for (let i = 0; i < this.files.length; i++) {
      const li = document.createElement("li");
      list.appendChild(li);

      const img = document.createElement("img");
      img.src = URL.createObjectURL(this.files[i]);
      img.height = 60;
      img.onload = () => {
        URL.revokeObjectURL(img.src);
      };
      li.appendChild(img);
      const info = document.createElement("span");
      info.innerHTML = `${this.files[i].name}: ${this.files[i].size} bytes`;
      li.appendChild(info);
    }
  }
}
```

This starts by fetching the URL of the `<div>` with the ID `fileList`. This is the block into which we'll insert our file list, including thumbnails.

If the `FileList` object passed to `handleFiles()` is `null`, we set the inner HTML of the block to display "No files selected!". Otherwise, we start building our file list, as follows:

1. A new unordered list (`<ul>`) element is created.
2. The new list element is inserted into the `<div>` block by calling its `Node.appendChild()` method.
3. For each `File` in the `FileList` represented by `files`:
    1. Create a new list item (`<li>`) element and insert it into the list.
    2. Create a new image (`<img>`) element.
    3. Set the image's source to a new object URL representing the file, using `URL.createObjectURL()` to create the blob URL.
    4. Set the image's height to 60 pixels.
    5. Set up the image's load event handler to release the object URL since it's no longer needed once the image has been loaded. This is done by calling the `URL.revokeObjectURL()` method and passing in the object URL string as specified by `img.src`.
    6. Append the new list item to the list.

Here is a live demo of the code above:

Example: Uploading a user-selected file
---------------------------------------

This example shows how to let the user upload files (such as the images selected using the previous example) to a server.

**Note:** It's usually preferable to make HTTP requests using the Fetch API instead of `XMLHttpRequest`. However, in this case we want to show the user the upload progress, and this feature is still not supported by the Fetch API, so the example uses `XMLHttpRequest`.

Work to track standardization of progress notifications using the Fetch API is at https://github.com/whatwg/fetch/issues/607.

### Creating the upload tasks

Continuing with the code that built the thumbnails in the previous example, recall that every thumbnail image is in the CSS class `obj` with the corresponding `File` attached in a `file` attribute. This allows us to select all of the images the user has chosen for uploading using `Document.querySelectorAll()`, like this:

```js
function sendFiles() {
  const imgs = document.querySelectorAll(".obj");

  for (let i = 0; i < imgs.length; i++) {
    new FileUpload(imgs[i], imgs[i].file);
  }
}
```

Line 2 fetches a `NodeList`, called `imgs`, of all the elements in the document with the CSS class `obj`. In our case, these will be all of the image thumbnails. Once we have that list, it's trivial to go through it and create a new `FileUpload` instance for each. Each of these handles uploading the corresponding file.

### Handling the upload process for a file

The `FileUpload` function accepts two inputs: an image element and a file from which to read the image data.

```js
function FileUpload(img, file) {
  const reader = new FileReader();
  this.ctrl = createThrobber(img);
  const xhr = new XMLHttpRequest();
  this.xhr = xhr;

  const self = this;
  this.xhr.upload.addEventListener(
    "progress",
    (e) => {
      if (e.lengthComputable) {
        const percentage = Math.round((e.loaded \* 100) / e.total);
        self.ctrl.update(percentage);
      }
    },
    false,
  );

  xhr.upload.addEventListener(
    "load",
    (e) => {
      self.ctrl.update(100);
      const canvas = self.ctrl.ctx.canvas;
      canvas.parentNode.removeChild(canvas);
    },
    false,
  );
  xhr.open(
    "POST",
    "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php",
  );
  xhr.overrideMimeType("text/plain; charset=x-user-defined-binary");
  reader.onload = (evt) => {
    xhr.send(evt.target.result);
  };
  reader.readAsBinaryString(file);
}

function createThrobber(img) {
  const throbberWidth = 64;
  const throbberHeight = 6;
  const throbber = document.createElement("canvas");
  throbber.classList.add("upload-progress");
  throbber.setAttribute("width", throbberWidth);
  throbber.setAttribute("height", throbberHeight);
  img.parentNode.appendChild(throbber);
  throbber.ctx = throbber.getContext("2d");
  throbber.ctx.fillStyle = "orange";
  throbber.update = (percent) => {
    throbber.ctx.fillRect(
      0,
      0,
      (throbberWidth \* percent) / 100,
      throbberHeight,
    );
    if (percent === 100) {
      throbber.ctx.fillStyle = "green";
    }
  };
  throbber.update(0);
  return throbber;
}
```

The `FileUpload()` function shown above creates a throbber, which is used to display progress information, and then creates an `XMLHttpRequest` to handle uploading the data.

Before actually transferring the data, several preparatory steps are taken:

1. The `XMLHttpRequest`'s upload `progress` listener is set to update the throbber with new percentage information so that as the upload progresses the throbber will be updated based on the latest information.
2. The `XMLHttpRequest`'s upload `load` event handler is set to update the throbber progress information to 100% to ensure the progress indicator actually reaches 100% (in case of granularity quirks during the process). It then removes the throbber since it's no longer needed. This causes the throbber to disappear once the upload is complete.
3. The request to upload the image file is opened by calling `XMLHttpRequest`'s `open()` method to start generating a POST request.
4. The MIME type for the upload is set by calling the `XMLHttpRequest` function `overrideMimeType()`. In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all depending on your use case.
5. The `FileReader` object is used to convert the file to a binary string.
6. Finally, when the content is loaded the `XMLHttpRequest` function `send()` is called to upload the file's content.
### Asynchronously handling the file upload process

This example, which uses PHP on the server side and JavaScript on the client side, demonstrates asynchronous uploading of a file.

```php
<?php
if (isset($\_FILES['myFile'])) {
 // Example:
 move\_uploaded\_file($\_FILES['myFile']['tmp\_name'], "uploads/" . $\_FILES['myFile']['name']);
 exit;
}
?><!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="UTF-8">
  <title>dnd binary upload</title>
    <script type="application/javascript">
 function sendFile(file) {
 const uri = "/index.php";
 const xhr = new XMLHttpRequest();
 const fd = new FormData();

 xhr.open("POST", uri, true);
 xhr.onreadystatechange = () => {
 if (xhr.readyState === 4 && xhr.status === 200) {
 alert(xhr.responseText); // handle response.
 }
 };
 fd.append('myFile', file);
 // Initiate a multipart/form-data upload
 xhr.send(fd);
 }

 window.onload = () => {
 const dropzone = document.getElementById("dropzone");
 dropzone.ondragover = dropzone.ondragenter = (event) => {
 event.stopPropagation();
 event.preventDefault();
 }

 dropzone.ondrop = (event) => {
 event.stopPropagation();
 event.preventDefault();

 const filesArray = event.dataTransfer.files;
 for (let i=0; i<filesArray.length; i++) {
 sendFile(filesArray[i]);
 }
 }
 }
 </script>
</head>
<body>
    <div>
        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here</div>
    </div>
</body>
</html>
```

Example: Using object URLs to display PDF
-----------------------------------------

Object URLs can be used for other things than just images! They can be used to display embedded PDF files or any other resources that can be displayed by the browser.

In Firefox, to have the PDF appear embedded in the iframe (rather than proposed as a downloaded file), the preference `pdfjs.disabled` must be set to `false`
Non-standard
.

```html
<iframe id="viewer"></iframe>
```

And here is the change of the `src` attribute:

```js
const obj_url = URL.createObjectURL(blob);
const iframe = document.getElementById("viewer");
iframe.setAttribute("src", obj_url);
URL.revokeObjectURL(obj_url);
```

Example: Using object URLs with other file types
------------------------------------------------

You can manipulate files of other formats the same way. Here is how to preview uploaded video:

```js
const video = document.getElementById("video");
const obj_url = URL.createObjectURL(blob);
video.src = obj_url;
video.play();
URL.revokeObjectURL(obj_url);
```

See also
--------

* `File`
* `FileList`
* `FileReader`
* `URL`
* `XMLHttpRequest`
* Using XMLHttpRequest


Screen: orientationchange event - Web APIs

Screen: orientationchange event
===============================

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

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

The `orientationchange` event fires when the device's orientation has changed.

Syntax
------

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

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

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

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

A generic `Event`.

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

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

Use the `ScreenOrientation change event` instead.

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

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

See also
--------

* Managing screen orientation


Screen: mozBrightness property - Web APIs

Screen: mozBrightness property
==============================

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

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

 Indicates how bright the screen's backlight is, on a scale from 0 (very dim) to 1 (full
 brightness); this value is a double-precision float.

 You can read and write this attribute even when the screen is disabled, but the
 backlight is off while the screen is disabled. If you write a value of X into this
 attribute, the attribute may not have the same value X when you later read it. Most
 screens don't support as many different brightness levels as there are doubles between 0
 and 1. The value's precision might be reduced before storing it.

Value
-----

A number.

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

Not part of specification.

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

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


Screen: lockOrientation() method - Web APIs

Screen: lockOrientation() method
================================

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

 The **`lockOrientation()`** method of the `Screen`
 interface locks the screen into a specified orientation.

**Warning:** This feature is deprecated and should be avoided. Use the `ScreenOrientation.lock()` method instead.

**Note:** This method only works for installed Web apps or for Web pages
 in fullscreen mode.

Syntax
------

```js
lockOrientation(orientation)
```

### Parameters

`orientation`

 The orientation into which to lock the screen. This is either a string or an array
 of strings. Passing several strings lets the screen rotate only in the selected
 orientations.

The following strings represent the possible orientation requirements you may specify:

`portrait-primary`

 It represents the orientation of the screen when it is in its primary portrait mode.
 A screen is considered in its primary portrait mode if the device is held in its
 normal position and that position is in portrait, or if the normal position of the
 device is in landscape and the device held turned by 90° clockwise. The normal
 position is device dependent.

`portrait-secondary`

 It represents the orientation of the screen when it is in its secondary portrait
 mode. A screen is considered in its secondary portrait mode if the device is held 180°
 from its normal position and that position is in portrait, or if the normal position
 of the device is in landscape and the device held is turned by 90° counterclockwise. The
 normal position is device dependent.

`landscape-primary`

 It represents the orientation of the screen when it is in its primary landscape
 mode. A screen is considered in its primary landscape mode if the device is held in
 its normal position and that position is in landscape, or if the normal position of
 the device is in portrait and the device held is turned by 90° clockwise. The normal
 position is device dependent.

`landscape-secondary`

 It represents the orientation of the screen when it is in its secondary landscape
 mode. A screen is considered in its secondary landscape mode if the device held is
 180° from its normal position and that position is in landscape, or if the normal
 position of the device is in portrait and the device held is turned by 90°
 counterclockwise. The normal position is device dependent.

`portrait`

 It represents both `portrait-primary` and
 `portrait-secondary`.

`landscape`

 It represents both `landscape-primary` and
 `landscape-secondary`.

`default`

 It represents either `portrait-primary` and
 `landscape-primary` depends on natural orientation of devices. For example,
 if the panel resolution is 1280\*800, `default` will make it landscape, if
 the resolution is 800\*1280, `default` will make it to portrait.

**Note:** It's possible to set several locks at the same time. So, if
 the lock is set for only one orientation, the screen orientation will never change
 until the screen orientation is unlocked. Otherwise, the screen orientation will
 change from an orientation to another as long as the orientations are amongst the
 orientations the device has been locked to.

### Return value

 Returns `true` if the orientation was authorized to be locked or
 `false` if the orientation locking was denied. Note that the return value
 doesn't indicate that the screen orientation is indeed locked: there may be a delay.

Examples
--------

### Usage with a string argument

```js
screen.lockOrientationUniversal =
  screen.lockOrientation ||
  screen.mozLockOrientation ||
  screen.msLockOrientation;

if (screen.lockOrientationUniversal("landscape-primary")) {
  // Orientation was locked
} else {
  // Orientation lock failed
}
```

### Usage with an `Array` argument

```js
screen.lockOrientationUniversal =
  screen.lockOrientation ||
  screen.mozLockOrientation ||
  screen.msLockOrientation;

if (
  screen.lockOrientationUniversal(["landscape-primary", "landscape-secondary"])
) {
  // Orientation was locked
} else {
  // Orientation lock failed
}
```

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

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

Use `ScreenOrientation.lock()` instead.

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

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

See also
--------

* `Screen.orientation`
* `Screen.unlockOrientation()`
* `orientationchange` event
* Managing screen orientation


Screen: availWidth property - Web APIs

Screen: availWidth property
===========================

 The **`Screen.availWidth`** property returns the amount of
 horizontal space (in pixels) available to the window.

Value
-----

A number.

Examples
--------

```js
const screenAvailWidth = window.screen.availWidth;

console.log(screenAvailWidth);
```

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

| Specification |
| --- |
| CSSOM View Module # dom-screen-availwidth |

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

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


Screen: pixelDepth property - Web APIs

Screen: pixelDepth property
===========================

 Returns the bit depth of the screen. Per the CSSOM, some implementations
 return `24` for compatibility reasons. See the browser compatibility section for those that don't.

Value
-----

A number.

Examples
--------

```js
// if there is not adequate bit depth
// choose a simpler color
document.style.color = window.screen.pixelDepth > 8 ? "#FAEBD7" : "#FFFFFF";
```

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

| Specification |
| --- |
| CSSOM View Module # dom-screen-pixeldepth |

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

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

See also
--------

* `Screen.colorDepth`


Screen: change event - Web APIs

Screen: change event
====================

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

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

The **`change`** event of the `Screen` interface is fired on a specific screen when one or more of the following properties change on it:

* `width`
* `height`
* `availWidth`
* `availHeight`
* `colorDepth`
* `orientation`
Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
const firstScreen = (await window.getScreenDetails()).screens[0];
firstScreen.addEventListener("change", (event) => {
  console.log("The first screen has changed.", event, firstScreen);
});
```

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

| Specification |
| --- |
| Window Management # api-screen-onchange-attribute |

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

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

See also
--------

* Window Management API


Screen: availHeight property - Web APIs

Screen: availHeight property
============================

 The read-only `Screen` interface's
 **`availHeight`** property returns the height, in CSS pixels, of
 the space available for Web content on the screen. Since `Screen` is
 exposed on the `Window` interface's `window.screen` property, you access `availHeight` using
 `window.screen.availHeight`.

 You can similarly use `Screen.availWidth` to get the number of pixels
 which are horizontally available to the browser for its use.

Value
-----

 A numeric value indicating the number of CSS pixels tall the screen's available space
 is. This can be no larger than the value of `window.screen.height`, and will be less if the device or user agent reserves any
 vertical space for itself.

 For instance, on a Mac whose Dock is located at the bottom of screen (which is the
 default), the value of `availHeight` is approximately the value of
 `height` (the total height of the screen in CSS pixels) minus the heights of
 the Dock and menu bar, as seen in the diagram below.

![Diagram showing how Screen.availHeight relates to Screen.height and the screen's contents](/en-US/docs/Web/API/Screen/availHeight/availheight-diagram.svg)

Examples
--------

 If your web application needs to open a new window, such as a tool palette which can
 contain multiple panels, and wants to position it so that it occupies the entire
 vertical space available, you can do so using code similar to what's seen here.

In the main window, when it's time to open the panels, code like the following is used.

```js
const paletteWindow = window.open(
  "panels.html",
  "Panels",
  "left=0, top=0, width=200",
);
```

 The Panels window's HTML, in `panels.html`, has JavaScript code of its own,
 which is executed as soon as the window is created. It doesn't even need to wait for any
 particular event (or any event at all). That code handles resizing the window based on
 the available space:

```js
window.outerHeight = window.screen.availHeight;
```

 The result is something similar to the below. Note the Panels window filling all
 available vertical space at the left of the screen.

![Screenshot of the example for Screen.availHeight](/en-US/docs/Web/API/Screen/availHeight/screen-availheight.png)

 On a Windows system, this would function similarly, by opening the window and sizing it
 vertically so it uses all available vertical space, leaving room for the taskbar and any
 other interface elements that reserve space.

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

| Specification |
| --- |
| CSSOM View Module # dom-screen-availheight |

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

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

See also
--------

* `Window`
* `Screen`
* `Screen.availWidth`
* `Window.innerHeight`


Screen: height property - Web APIs

Screen: height property
=======================

 The **`Screen.height`** read-only property returns the height
 of the screen in pixels.

Value
-----

A number.

Examples
--------

```js
if (window.screen.availHeight !== window.screen.height) {
  // Something is occupying some screen real estate!
}
```

Notes
-----

 Note that not all of the height given by this property may be available to the window
 itself. Widgets such as taskbars or other special application windows that integrate
 with the OS (e.g., the Spinner player minimized to act like an additional toolbar on
 windows) may reduce the amount of space available to browser windows and other
 applications.

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

| Specification |
| --- |
| CSSOM View Module # dom-screen-height |

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

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


Screen: mozEnabled property - Web APIs

Screen: mozEnabled property
===========================

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

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

 This Boolean attribute controls the device's screen. Setting it to `false`
 will turn off the screen.

Value
-----

A boolean.

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

Not part of specification.

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

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


Screen: unlockOrientation() method - Web APIs

Screen: unlockOrientation() method
==================================

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

 The **`Screen.unlockOrientation()`** method removes all the
 previous screen locks set by the page/app. The `ScreenOrientation.unlock()`
 method should be used instead.

**Warning:** This feature is deprecated and should be avoided. Use the `ScreenOrientation.unlock()` method instead.

**Note:** This method only works for installed Web apps or for Web pages
 in fullscreen mode.

Syntax
------

```js
unlockOrientation()
```

### Parameters

None.

### Return value

 Returns `true` if the orientation was successfully unlocked or
 `false` if the orientation couldn't be unlocked.

Examples
--------

```js
const unlockOrientation =
  screen.unlockOrientation ||
  screen.mozUnlockOrientation ||
  screen.msUnlockOrientation ||
  (screen.orientation && screen.orientation.unlock);

if (unlockOrientation()) {
  // orientation was unlocked
} else {
  // orientation unlock failed
}
```

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

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

Use `ScreenOrientation.unlock()` instead.

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

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

See also
--------

* `Screen.orientation`
* `Screen.lockOrientation()`
* `orientationchange` event
* Managing screen orientation


Screen: isExtended property - Web APIs

Screen: isExtended property
===========================

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

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

 The **`isExtended`** read-only property of the
 `Screen` interface returns `true` if the user's device has multiple screens, and `false` if not.

This property is typically accessed via `window.screen.isExtended`, and can be used to test whether multiple screens are available before attempting to create a multi-window, multi-screen layout using the Window Management API.

Value
-----

A boolean value — `true` if the device has multiple screens, and `false` if not.

**Note:** If a `window-management` Permissions-Policy is set that blocks use the Window Management API, `isExtended` will always return `false`.

Examples
--------

```js
if (window.screen.isExtended) {
  // Create multi-screen window layout
} else {
  // Create single-screen window layout
}
```

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

| Specification |
| --- |
| Window Management # api-screen-isExtended-attribute |

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

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

See also
--------

* Window Management API


Screen: width property - Web APIs

Screen: width property
======================

 The **`Screen.width`** read-only property returns the width of
 the screen in CSS pixels.

Value
-----

A number.

Examples
--------

```js
// Crude way to check that the screen is at least 1024x768
if (window.screen.width >= 1024 && window.screen.height >= 768) {
  // Resolution is 1024x768 or above
}
```

Notes
-----

 Note that not all of the width given by this property may be available to the window
 itself. When other widgets occupy space that cannot be used by the `window`
 object, there is a difference in `window.screen.width` and
 `window.screen.availWidth`. See also `screen.height`.

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

| Specification |
| --- |
| CSSOM View Module # dom-screen-width |

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

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


Screen: colorDepth property - Web APIs

Screen: colorDepth property
===========================

 The **`Screen.colorDepth`** read-only property returns the
 color depth of the screen. Per the CSSOM, some implementations return `24`
 for compatibility reasons. See the browser compatibility section for those that don't.

Value
-----

A number.

Examples
--------

```js
// Check the color depth of the screen
if (window.screen.colorDepth < 8) {
  // Use low-color version of page
} else {
  // Use regular, colorful page
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-screen-colordepth |

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

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

See also
--------

* `Screen.pixelDepth`


Screen: orientation property - Web APIs

Screen: orientation property
============================

 The **`orientation`** read-only property of the
 `Screen` interface returns the current orientation of the screen.

Value
-----

 An instance of `ScreenOrientation` representing the orientation of the
 screen.

 Note that older, prefixed versions returned a string equivalent to
 `ScreenOrientation.type`.

Examples
--------

```js
switch (screen.orientation.type) {
  case "landscape-primary":
    console.log("That looks good.");
    break;
  case "landscape-secondary":
    console.log("Mmmh… the screen is upside down!");
    break;
  case "portrait-secondary":
  case "portrait-primary":
    console.log("Mmmh… you should rotate your device to landscape");
    break;
  default:
    console.log("The orientation API isn't supported in this browser :(");
}
```

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

| Specification |
| --- |
| Screen Orientation # dom-screen-orientation |

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

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

See also
--------

* `ScreenOrientation`
* `orientationchange` event
* Managing screen orientation


VRPose: angularVelocity property - Web APIs

VRPose: angularVelocity property
================================

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

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

The **`angularVelocity`** read-only property of the `VRPose` interface returns an array representing the angular velocity vector of the `VRDisplay` at the current timestamp, in radians per second.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

In other words, the current velocity at which the sensor is rotating around the `x`, `y`, and `z` axes.

Value
-----

A `Float32Array`, or `null` if the VR sensor is not able to provide angular velocity information.

Examples
--------

```js
// rendering loop for a VR scene
function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // Populate frameData with the data of the next frame to display
  vrDisplay.getFrameData(frameData);

  // Retrieve the angular velocity values for use in rendering
  // curFramePose is a VRPose object
  const curFramePose = frameData.pose;
  const angVel = curFramePose.angularVelocity;
  const avx = angVel[0];
  const avy = angVel[1];
  const avz = angVel[2];

  // render the scene
  // …

  // WebVR: submit the rendered frame to the VR display
  vrDisplay.submitFrame();
}
```

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRPose: angularAcceleration property - Web APIs

VRPose: angularAcceleration property
====================================

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

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

The **`angularAcceleration`** read-only property of the `VRPose` interface returns an array representing the angular acceleration vector of the `VRDisplay` at the current timestamp, in meters per second per second.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

In other words, the current acceleration of the sensor's rotation around the `x`, `y`, and `z` axes.

Value
-----

A `Float32Array`, or `null` if the VR sensor is not able to provide angular acceleration information.

Examples
--------

```js
// rendering loop for a VR scene
function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // Populate frameData with the data of the next frame to display
  vrDisplay.getFrameData(frameData);

  // Retrieve the angular acceleration values for use in rendering
  // curFramePose is a VRPose object
  const curFramePose = frameData.pose;
  const angAcc = curFramePose.angularAcceleration;
  const aax = angAcc[0];
  const aay = angAcc[1];
  const aaz = angAcc[2];

  // render the scene
  // …

  // WebVR: submit the rendered frame to the VR display
  vrDisplay.submitFrame();
}
```

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRPose: position property - Web APIs

VRPose: position property
=========================

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

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

The **`position`** read-only property of the `VRPose` interface returns the position of the `VRDisplay` at the current timestamp as a 3D vector.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

The coordinate system is as follows:

* Positive X is to the user's right.
* Positive Y is up.
* Positive Z is behind the user.

Positions are measured in meters from an origin point — this point is either the position the sensor was first read at, or the position of the sensor at the point that `VRDisplay.resetPose()` was last called.

**Note:** By default, all positions are given as a sitting space position. Transforming this point with `VRStageParameters.sittingToStandingTransform` — when you are working with a room display for example — converts this to a standing space position.

Value
-----

A `Float32Array`, or null if the VR sensor is not able to provide position data.

**Note:** User agents may provide emulated position values through techniques such as neck modeling; when doing so they should still report `VRDisplayCapabilities.hasPosition` as false.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRPose: linearAcceleration property - Web APIs

VRPose: linearAcceleration property
===================================

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

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

The **`linearAcceleration`** read-only property of the `VRPose` interface returns an array representing the linear acceleration vector of the `VRDisplay` at the current timestamp, in meters per second per second.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

In other words, the current acceleration of the sensor, along the `x`, `y`, and `z` axes.

Value
-----

A `Float32Array`, or `null` if the VR sensor is not able to provide linear acceleration data.

Examples
--------

```js
// rendering loop for a VR scene
function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // Populate frameData with the data of the next frame to display
  vrDisplay.getFrameData(frameData);

  // Retrieve the linear acceleration values for use in rendering
  // curFramePose is a VRPose object
  const curFramePose = frameData.pose;
  const linAcc = curFramePose.linearAcceleration;
  const lax = linAcc[0];
  const lay = linAcc[1];
  const laz = linAcc[2];

  // render the scene
  // …

  // WebVR: submit the rendered frame to the VR display
  vrDisplay.submitFrame();
}
```

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRPose: orientation property - Web APIs

VRPose: orientation property
============================

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

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

The **`orientation`** read-only property of the `VRPose` interface returns the orientation of the sensor at the current timestamp, as a quarternion value.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

The value is a `Float32Array`, made up of the following values:

* pitch — rotation around the X axis.
* yaw — rotation around the Y axis.
* roll — rotation around the Z axis.
* w — the fourth dimension (usually 1).

The orientation yaw (rotation around the y axis) is relative to the initial yaw of the sensor when it was first read or the yaw of the sensor at the point that `VRDisplay.resetPose()` was last called.

Value
-----

A `Float32Array`, or `null` if the VR sensor is not able to provide orientation data.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

**Note:** An orientation of `{ x: 0, y: 0, z: 0, w: 1 }` is considered to be "forward".

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRPose: linearVelocity property - Web APIs

VRPose: linearVelocity property
===============================

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

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

The **`linearVelocity`** read-only property of the `VRPose` interface returns an array representing the linear velocity vector of the `VRDisplay` at the current timestamp, in meters per second.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

In other words, the current velocity at which the sensor is moving along the `x`, `y`, and `z` axes.

Value
-----

A `Float32Array`, or `null` if the VR sensor is not able to provide linear velocity data.

Examples
--------

```js
// rendering loop for a VR scene
function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // Populate frameData with the data of the next frame to display
  vrDisplay.getFrameData(frameData);

  // Retrieve the linear velocity values for use in rendering
  // curFramePose is a VRPose object
  const curFramePose = frameData.pose;
  const linVel = curFramePose.linearVelocity;
  const lvx = linVel[0];
  const lvy = linVel[1];
  const lvz = linVel[2];

  // render the scene
  // …

  // WebVR: submit the rendered frame to the VR display
  vrDisplay.submitFrame();
}
```

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


ReportBody: toJSON() method - Web APIs

ReportBody: toJSON() method
===========================

The **`toJSON()`** method of the `ReportBody` interface is a *serializer*, and returns a JSON representation of the `ReportBody` object.

Syntax
------

```js
toJSON()
```

### Parameters

None.

### Return value

A JSON object that is the serialization of the `ReportBody` object.

Examples
--------

In this example we create a new `ReportingObserver` to observe intervention reports, then return a JSON representation of the first entry. The report, and therefore the JSON object returned will be an instance of `InterventionReportBody` which inherits from `ReportBody`.

```js
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver(([firstReport], observer) => {
  console.log(firstReport.toJSON());
}, options);
```

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

| Specification |
| --- |
| Reporting API # dom-reportbody-tojson |

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

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


InputDeviceCapabilities: firesTouchEvents property - Web APIs

InputDeviceCapabilities: firesTouchEvents property
==================================================

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

The **`firesTouchEvents`** read-only property of the `InputDeviceCapabilities` interface returns a boolean value that indicates whether the device dispatches touch events.

 You can use this property to detect mouse events that represent an action that may
 already have been handled by touch event handlers. This doesn't necessarily mean the
 device is a touch screen. For example, stylus and mouse devices typically generate
 touch events on mobile browsers.

Syntax
------

```js
const boolean = InputDeviceCapabilities.firesTouchEvents
```

### Returns

A `Boolean`

Example
-------

```js
myButton.addEventListener("mousedown", (e) => {
  if (!e.sourceCapabilities.firesTouchEvents) myButton.classList.add("pressed");
});
```

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

| Specification |
| --- |
| Input Device Capabilities # dom-inputdevicecapabilities-firestouchevents |

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

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


InputDeviceCapabilities: InputDeviceCapabilities() constructor - Web APIs

InputDeviceCapabilities: InputDeviceCapabilities() constructor
==============================================================

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

 The `InputDeviceCapabilities()` constructor creates a new
 `InputDeviceCapabilities` object provides information about the physical
 device responsible for generating a touch event.

Syntax
------

```js
new InputDeviceCapabilities()
new InputDeviceCapabilities(InputDeviceCapabilitiesInit)
```

### Returns

An instance of the `InputDeviceCapabilities` interface.

### Parameters

`InputDeviceCapabilitiesInit` Optional

 A dictionary object containing a set of device capabilities. It contains the
 following property.

* `fireTouchEvents`: A boolean value that indicates
 whether the device dispatches touch events.

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

| Specification |
| --- |
| Input Device Capabilities # dom-inputdevicecapabilities-constructor |

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

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


XPathNSResolver: lookupNamespaceURI() method - Web APIs

XPathNSResolver: lookupNamespaceURI() method
============================================

 The `lookupNamespaceURI` method looks up the namespace URI associated to the
 given namespace prefix within an XPath expression evaluated by the
 `XPathEvaluator` interface.

Syntax
------

```js
lookupNamespaceURI(prefix)
```

### Parameters

`prefix`

A string representing the prefix to look for.

### Return value

 A string representing the associated namespace URI or
 `null` if none is found.

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

#### No specification found

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

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

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

See also
--------

* `XPathEvaluator`
* `Node.lookupNamespaceURI()`


OES_vertex_array_object: isVertexArrayOES() method - Web APIs

OES\_vertex\_array\_object: isVertexArrayOES() method
=====================================================

 The **`OES_vertex_array_object.isVertexArrayOES()`** method of
 the WebGL API returns `true` if
 the passed object is a `WebGLVertexArrayObject` object.

Syntax
------

```js
isVertexArrayOES(arrayObject)
```

### Parameters

`arrayObject`

A `WebGLVertexArrayObject` (VAO) object to test.

### Return value

 A `WebGL_API.Types` indicating whether the given object is a
 `WebGLVertexArrayObject` object (`true`) or not
 (`false`).

Examples
--------

```js
const ext = gl.getExtension("OES\_vertex\_array\_object");
const vao = ext.createVertexArrayOES();
ext.bindVertexArrayOES(vao);

// …

ext.isVertexArrayOES(vao);
```

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

| Specification |
| --- |
| WebGL OES\_vertex\_array\_object Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.vertexAttribPointer()`
* WebGL2 equivalent: `WebGL2RenderingContext.isVertexArray()`


OES_vertex_array_object: bindVertexArrayOES() method - Web APIs

OES\_vertex\_array\_object: bindVertexArrayOES() method
=======================================================

 The **`OES_vertex_array_object.bindVertexArrayOES()`** method
 of the WebGL API binds a
 passed `WebGLVertexArrayObject` object to the buffer.

Syntax
------

```js
bindVertexArrayOES(arrayObject)
```

### Parameters

`arrayObject`

A `WebGLVertexArrayObject` (VAO) object to bind.

### Return value

None (`undefined`).

Examples
--------

```js
const ext = gl.getExtension("OES\_vertex\_array\_object");
const vao = ext.createVertexArrayOES();
ext.bindVertexArrayOES(vao);

// …
// calls to bindBuffer or vertexAttribPointer
// which will be "recorded" in the VAO
// …
```

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

| Specification |
| --- |
| WebGL OES\_vertex\_array\_object Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.vertexAttribPointer()`
* WebGL2 equivalent: `WebGL2RenderingContext.bindVertexArray()`


OES_vertex_array_object: deleteVertexArrayOES() method - Web APIs

OES\_vertex\_array\_object: deleteVertexArrayOES() method
=========================================================

 The **`OES_vertex_array_object.deleteVertexArrayOES()`** method
 of the WebGL API deletes a given
 `WebGLVertexArrayObject` object.

Syntax
------

```js
deleteVertexArrayOES(arrayObject)
```

### Parameters

`arrayObject`

A `WebGLVertexArrayObject` (VAO) object to delete.

### Return value

None (`undefined`).

Examples
--------

```js
const ext = gl.getExtension("OES\_vertex\_array\_object");
const vao = ext.createVertexArrayOES();
ext.bindVertexArrayOES(vao);

// …

ext.deleteVertexArrayOES(vao);
```

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

| Specification |
| --- |
| WebGL OES\_vertex\_array\_object Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.vertexAttribPointer()`
* WebGL2 equivalent: `WebGL2RenderingContext.deleteVertexArray()`


OES_vertex_array_object: createVertexArrayOES() method - Web APIs

OES\_vertex\_array\_object: createVertexArrayOES() method
=========================================================

 The **`OES_vertex_array_object.createVertexArrayOES()`** method
 of the WebGL API creates and initializes a
 `WebGLVertexArrayObject` object that represents a vertex array object (VAO)
 pointing to vertex array data and which provides names for different sets of vertex
 data.

Syntax
------

```js
createVertexArrayOES()
```

### Parameters

None.

### Return value

 A `WebGLVertexArrayObject` representing a vertex array object (VAO) which
 points to vertex array data.

Examples
--------

```js
const ext = gl.getExtension("OES\_vertex\_array\_object");
const vao = ext.createVertexArrayOES();
ext.bindVertexArrayOES(vao);

// …
// calls to bindBuffer or vertexAttribPointer
// which will be "recorded" in the VAO
// …
```

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

| Specification |
| --- |
| WebGL OES\_vertex\_array\_object Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.vertexAttribPointer()`
* WebGL2 equivalent: `WebGL2RenderingContext.createVertexArray()`


AbstractRange: startOffset property - Web APIs

AbstractRange: startOffset property
===================================

The read-only **`startOffset`** property of the `AbstractRange` interface returns the offset into the start node of the range's start position.

Value
-----

An integer value indicating the number of characters into the `Node` indicated by `startContainer` at which the first character of the range is located.

Example
-------

```js
let startOffset = range.startOffset;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-startoffset① |

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

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


AbstractRange: endContainer property - Web APIs

AbstractRange: endContainer property
====================================

The read-only **`endContainer`** property of the `AbstractRange` interface returns the `Node` in which the end of the range is located.

Value
-----

The `Node` which contains the last character of the range.

Example
-------

```js
let endNode = range.endContainer;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-endcontainer① |

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

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


AbstractRange: startContainer property - Web APIs

AbstractRange: startContainer property
======================================

The read-only **`startContainer`** property of the `AbstractRange` interface returns the start `Node` for the range.

Value
-----

The `Node` inside which the start position of the range is found.

Example
-------

```js
let startNode = range.startContainer;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-startcontainer① |

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

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


AbstractRange: collapsed property - Web APIs

AbstractRange: collapsed property
=================================

The read-only **`collapsed`** property of the `AbstractRange` interface returns `true` if the range's start position and end position are the same.

Value
-----

A boolean value which is `true` if the range is *collapsed*. A collapsed range is one in which the start and end positions are the same, resulting in a zero-character-long range.

Example
-------

```js
let isCollapsed = range.collapsed;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-collapsed① |

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

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


AbstractRange: endOffset property - Web APIs

AbstractRange: endOffset property
=================================

The **`endOffset`** property of the `AbstractRange` interface returns the offset into the end node of the range's end position.

Value
-----

An integer value indicating the number of characters into the `Node` indicated by `endContainer` at which the final character of the range is located.

Example
-------

```js
let endOffset = range.endOffset;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-endoffset① |

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

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


WorkerNavigator: locks property - Web APIs

WorkerNavigator: locks property
===============================

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

 The **`locks`** read-only property of
 the `WorkerNavigator` interface returns a `LockManager`
 object which provides methods for requesting a new `Lock` object and
 querying for an existing `Lock` object.

Value
-----

A `LockManager` object.

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

| Specification |
| --- |
| Web Locks API # dom-navigatorlocks-locks |

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

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


WorkerNavigator: appCodeName property - Web APIs

WorkerNavigator: appCodeName property
=====================================

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

 The value of the **`WorkerNavigator.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
--------------

| Specification |
| --- |
| HTML Standard # dom-navigator-appcodename-dev |

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

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

See also
--------

* `WorkerNavigator.appName`
* `WorkerNavigator.product`


WorkerNavigator: setAppBadge() method - Web APIs

WorkerNavigator: setAppBadge() method
=====================================

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

The **`setAppBadge()`** method of the `WorkerNavigator` 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
setAppBadge()
setAppBadge(contents)
```

### Parameters

`contents` Optional

A `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 `Promise` that resolves with `undefined`.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the document is not fully active.

`SecurityError` `DOMException`

Thrown if the call was blocked by the same-origin policy.

`NotAllowedError` `DOMException`

Thrown if `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
--------------

#### No specification found

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

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

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

See also
--------

* Badging for app icons


WorkerNavigator: permissions property - Web APIs

WorkerNavigator: permissions property
=====================================

 The **`WorkerNavigator.permissions`** read-only property
 returns a `Permissions` object that can be used to query and update
 permission status of APIs covered by the Permissions API.

Value
-----

A `Permissions` object.

Examples
--------

```js
navigator.permissions.query({ name: "notifications" }).then((result) => {
  if (result.state === "granted") {
    showNotification();
  } else if (result.state === "prompt") {
    requestNotificationPermission();
  }
});
```

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

| Specification |
| --- |
| Permissions # dom-workernavigator-permissions |

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

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

See also
--------

* Permissions API
* Web Worker API


WorkerNavigator: serial property - Web APIs

WorkerNavigator: serial property
================================

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

The **`serial`** read-only property of the `WorkerNavigator` interface returns a `Serial` object which represents the entry point into the `Web Serial API`.

When getting, the same instance of the `Serial` object will always be returned.

Value
-----

A `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.
});
```

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

| Specification |
| --- |
| Web Serial API # dom-workernavigator-serial |

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

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

See also
--------

* Read from and write to a serial port
* Getting started with the web serial API


WorkerNavigator: deviceMemory property - Web APIs

WorkerNavigator: deviceMemory property
======================================

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

 The **`deviceMemory`** read-only
 property of the `WorkerNavigator` interface returns the approximate amount of
 device memory in gigabytes.

 The reported value is imprecise to curtail fingerprinting. It's approximated by
 rounding down to the nearest power of 2, then dividing that number by 1024. It is then
 clamped within lower and upper bounds to protect the privacy of owners of very low-memory or
 high-memory devices.

Value
-----

A floating point number; one of `0.25`, `0.5`, `1`, `2`, `4`, `8`.

Examples
--------

The following code can be run in a worker:

```js
const memory = navigator.deviceMemory;
console.log(`This device has at least ${memory}GiB of RAM.`);
```

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

| Specification |
| --- |
| Device Memory # sec-device-memory-js-api |

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

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

See also
--------

* `Device-Memory` HTTP header


WorkerNavigator: globalPrivacyControl property - Web APIs

WorkerNavigator: globalPrivacyControl property
==============================================

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

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

 The **`WorkerNavigator.globalPrivacyControl`** read-only property returns the user's Global Privacy Control 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 `Sec-GPC` HTTP header.

Value
-----

`true` if the user explicitly *does not* grant 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
--------------

#### No specification found

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

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

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

See also
--------

* `Sec-GPC` header
* globalprivacycontrol.org
* Global Privacy Control Spec
* Do Not Track on Wikipedia


WorkerNavigator: userAgentData property - Web APIs

WorkerNavigator: userAgentData property
=======================================

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

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

 The **`userAgentData`** read-only property of the `WorkerNavigator` interface returns an `NavigatorUAData` object
 which can be used to access the `User-Agent Client Hints API`.

Value
-----

A `NavigatorUAData` object.

Examples
--------

The following example prints the value of `NavigatorUAData.brands` to the console.

```js
console.log(navigator.userAgentData.brands);
```

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

| Specification |
| --- |
| User-Agent Client Hints # dom-navigatorua-useragentdata |

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

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

See also
--------

* Improving user privacy and developer experience with User-Agent Client Hints


WorkerNavigator: usb property - Web APIs

WorkerNavigator: usb property
=============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`usb`** read-only property of the `WorkerNavigator` interface returns a `USB` object for the current document, providing access to WebUSB API functionality.

Value
-----

A `USB` object.

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

| Specification |
| --- |
| WebUSB API # dom-workernavigator-usb |

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

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

See also
--------

* WebUSB API


WorkerNavigator: gpu property - Web APIs

WorkerNavigator: gpu property
=============================

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

The **`gpu`** read-only property of the `WorkerNavigator` interface returns the `GPU` object for the current worker context, which is the entry point for the WebGPU API.

Value
-----

A `GPU` object.

Examples
--------

```js
// Can be run inside a web worker
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
--------------

| Specification |
| --- |
| WebGPU # navigator-gpu |

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

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

See also
--------

* WebGPU API


WorkerNavigator: onLine property - Web APIs

WorkerNavigator: onLine property
================================

Returns the online status of the browser. The property returns a boolean value, with `true` meaning online and `false` meaning offline. The property sends updates whenever the browser's ability to connect to the network changes. The update occurs when the user follows links or when a script requests a remote page.

For example, the property should return `false` when users click links soon after they lose internet connection.

Browsers implement this property differently.

 In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return `true`. So while you can assume that the browser is offline when it returns a `false` value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always
 "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. To learn more, see the 2011 article, Working Off the Grid.

In Firefox, switching the browser to offline mode sends a `false` value.

Value
-----

`online` is a boolean `true` or `false`.

Examples
--------

### Basic usage

To check if you are online in a worker, query `navigator.onLine`, as in the following example:

```js
if (navigator.onLine) {
  console.log("online");
} else {
  console.log("offline");
}
```

If the browser doesn't support `navigator.onLine` the above example will always come out as `false`/`undefined`.

### Listening for changes in network status

To see changes in the network state, use `addEventListener` to listen for the events on `online` and `offline`, as in the following example:

```js
addEventListener("offline", (e) => {
  console.log("offline");
});

addEventListener("online", (e) => {
  console.log("online");
});
```

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

| Specification |
| --- |
| HTML Standard # dom-navigator-online-dev |

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

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


WorkerNavigator: serviceWorker property - Web APIs

WorkerNavigator: serviceWorker property
=======================================

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

The **`serviceWorker`** read-only property of the `WorkerNavigator` interface returns the `ServiceWorkerContainer` object for the associated document, which provides access to registration, removal, upgrade, and communication with the `ServiceWorker`.

The feature may not be available in private mode.

Value
-----

`ServiceWorkerContainer`.

Examples
--------

This code checks if the browser supports using service worker in workers.

```js
if ("serviceWorker" in navigator) {
  // Supported!
}
```

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

| Specification |
| --- |
| Service Workers # navigator-serviceworker |

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

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

See also
--------

* Service Worker API
* Using Service Workers


WorkerNavigator: languages property - Web APIs

WorkerNavigator: languages property
===================================

 The **`WorkerNavigator.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 `navigator.language` is the
 first element of the returned array.

 When its value changes, as the user's preferred languages are changed a
 `languagechange` event is fired on the `WorkerGlobalScope` 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 or strings.

Examples
--------

You can run this insert a web worker:

```js
navigator.language; //"en-US"
navigator.languages; //["en-US", "zh-CN", "ja-JP"]
```

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

| Specification |
| --- |
| HTML Standard # dom-navigator-languages-dev |

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

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

See also
--------

* `WorkerNavigator.language`
* `WorkerNavigator`
* `languagechange` event


WorkerNavigator: appVersion property - Web APIs

WorkerNavigator: appVersion property
====================================

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

 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 `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 `navigator.appVersion`, `navigator.appName` and
 `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
--------------

| Specification |
| --- |
| HTML Standard # dom-navigator-appversion-dev |

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

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


WorkerNavigator: platform property - Web APIs

WorkerNavigator: platform property
==================================

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

 Returns a string representing the platform of the browser. The specification allows
 browsers to always return the empty string, so don't rely on this property to get a
 reliable answer.

Value
-----

 A string identifying the platform on which the browser is running, or
 an empty string if the browser declines to (or is unable to) identify the platform.
 `platform` is a string that must be an empty string or a string representing
 the platform on which the browser is executing.

For example: "`MacIntel`", "`Win32`", "`FreeBSD i386`", "`WebTV OS`".

Examples
--------

```js
console.log(navigator.platform);
```

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

On Windows, modern browsers return `"Win32"` even if running on a 64-bit version of Windows

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

| Specification |
| --- |
| HTML Standard # dom-navigator-platform-dev |

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

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


WorkerNavigator: userAgent property - Web APIs

WorkerNavigator: userAgent property
===================================

 The **`WorkerNavigator.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 doesn't affect browser detection performed by
 JavaScript code.
* 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 HTTP headers and in response to this and other related
 methods on the `WorkerNavigator` 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:
```

userAgent = appCodeName/appVersion number (Platform; Security; OS-or-CPU;
Localization; rv: revision-version-number) product/productSub
Application-Name Application-Name-version
```

Examples
--------

```js
alert(navigator.userAgent);
// alerts "Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape6/6.1"
```

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

| Specification |
| --- |
| HTML Standard # dom-navigator-useragent-dev |

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

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

See also
--------

* `User-Agent` HTTP header


WorkerNavigator: language property - Web APIs

WorkerNavigator: language property
==================================

 The **`WorkerNavigator.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
--------

You can run this insert a web worker:

```js
if (/^en\b/.test(navigator.language)) {
  doLangSelect(window.navigator.language);
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigator-language-dev |

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

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

See also
--------

* `WorkerNavigator.languages`
* `WorkerNavigator`


WorkerNavigator: hardwareConcurrency property - Web APIs

WorkerNavigator: hardwareConcurrency property
=============================================

 The **`navigator.hardwareConcurrency`** read-only property
 returns the number of logical processors available to run threads on the user's
 computer.

Value
-----

A `Number` indicating the number of logical processor cores.

 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 `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 `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.

The following code can be run in a worker:

```js
let workerList = [];

for (let i = 0; i < navigator.hardwareConcurrency; i++) {
  let newWorker = {
    worker: new Worker("cpuworker.js"),
    inUse: false,
  };
  workerList.push(newWorker);
}
```

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

| Specification |
| --- |
| HTML Standard # dom-navigator-hardwareconcurrency-dev |

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

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

See also
--------

* `WorkerNavigator`


WorkerNavigator: storage property - Web APIs

WorkerNavigator: storage property
=================================

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

 The **`storage`** read-only property of the `WorkerNavigator` interface
 returns the singleton `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 `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
--------------

| Specification |
| --- |
| Storage Standard # dom-navigatorstorage-storage |

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

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

See also
--------

* `StorageManager`
* `WorkerNavigator`


WorkerNavigator: mediaCapabilities property - Web APIs

WorkerNavigator: mediaCapabilities property
===========================================

 The read-only **`WorkerNavigator.mediaCapabilities`** property
 returns a `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.

Value
-----

A `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
--------------

| Specification |
| --- |
| Media Capabilities # dom-workernavigator-mediacapabilities |

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

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

See also
--------

* Media Capabilities API
* `WorkerNavigator`