InputEvent: InputEvent() constructor - Web APIs

InputEvent: InputEvent() constructor
====================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`InputEvent()`** constructor creates a new `InputEvent` object.

Syntax
------

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

### Parameters

`type`

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

`options` Optional

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

`inputType` Optional

 A string specifying the type of change for editable content
 such as, for example, inserting, deleting, or formatting text.

`data` Optional

 A string containing characters to insert.
 This may be an empty string if the change doesn't insert text
 (such as when deleting characters, for example).

`isComposing` Optional

 A boolean indicating that the event is part of a composition session,
 meaning it is after a `compositionstart` event but before a `compositionend` event. The default is `false`.

Return value
------------

A new `InputEvent` object.

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

| Specification |
| --- |
| UI Events # dom-inputevent-inputevent |

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

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

See also
--------

* `InputEvent`, the interface of the objects it constructs.


InputEvent: dataTransfer property - Web APIs

InputEvent: dataTransfer property
=================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback

 The **`dataTransfer`** read-only property of the
 `InputEvent` interface returns a `DataTransfer` object
 containing information about richtext or plaintext data being added to or removed from
 editable content.

Value
-----

A `DataTransfer` object.

Examples
--------

 In the following simple example we've set up an event listener on the input event so that when any
 content is pasted into the contenteditable `<p>` element, its HTML source
 is retrieved via the
 `InputEvent.dataTransfer.getData()`
 method and reported in the paragraph below the input.

Try copying and pasting some of the content provided to see the effects.

```html
<p><span style="font-weight: bold; color: blue">Whoa, bold blue text!</span></p>
<p>
  <span style="font-style: italic; color: red">Exciting: italic red text!</span>
</p>
<p>Boring normal text ;-(</p>

<hr />

<p contenteditable="true">
  Go on, try pasting some content into this editable paragraph and see what
  happens!
</p>

<p class="result"></p>
```

```js
const editable = document.querySelector("p[contenteditable]");
const result = document.querySelector(".result");

editable.addEventListener("input", (e) => {
  result.textContent = e.dataTransfer.getData("text/html");
});
```

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

| Specification |
| --- |
| Input Events Level 2 # dom-inputevent-datatransfer |

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

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


InputEvent: getTargetRanges() method - Web APIs

InputEvent: getTargetRanges() method
====================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`getTargetRanges()`** method of the `InputEvent` interface returns an array of static ranges that will be affected by a change to the DOM if the input event is not canceled.

This allows web apps to override text edit behavior before the browser modifies the DOM tree, and provides more control over input events to improve performance.

Depending on the value of `inputType` and the current editing host, the expected return value of this method varies:

| inputType | Editing host | Response of `getTargetRanges()` |
| --- | --- | --- |
| `"historyUndo"` or `"historyRedo"` | Any | empty Array |
| All remaining | `contenteditable` |
 an Array of
 `StaticRange`
 objects associated with event
  |
| All remaining | `input`
 or `textarea` | an empty Array |

Syntax
------

```js
getTargetRanges()
```

### Parameters

None.

### Return value

An array of `StaticRange` objects.

Examples
--------

### Feature Detection

 The following function returns true if `beforeinput`, and thus
 `getTargetRanges`, is supported.

```js
function isBeforeInputEventAvailable() {
  return (
    window.InputEvent &&
    typeof InputEvent.prototype.getTargetRanges === "function"
  );
}
```

### Basic usage

 The following example selects a `contenteditable` element and utilizes the
 `beforeinput`
 event to log the result of `getTargetRanges()`.

```js
const editableElem = document.querySelector('[contenteditable="true"]');

editableElem.addEventListener("beforeinput", (e) => {
  const targetRanges = e.getTargetRanges();
  console.log(targetRanges);
});
```

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

| Specification |
| --- |
| Input Events Level 2 # dom-inputevent-gettargetranges |

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

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


Using the Media Capabilities API - Web APIs

Using the Media Capabilities API
================================

The Media Capabilities API provides several key features to help you better decide how to handle media, but also to determine how well media is being handled, in real time.

These features include:

* The ability to query the browser to determine its ability to encode or decode media given a specified set of encoding parameters. These parameters may include the codecs, resolutions, bit rates, frame rates, and other such details. With the Media Capabilities API, you can determine not just if the browser can support a given format, but whether or not it can do so efficiently and smoothly. In short, this API replaces—and improves upon—the `MediaSource` method `isTypeSupported()` or the `HTMLMediaElement` method `canPlayType()`.
* More and more finely-detailed information about the display's properties, so that informed decisions can be made when choosing the best format to play on the user's device. For example, you can use the API to ensure that you don't try to play High Dynamic Range (HDR) content on a Standard Dynamic Range (SDR) screen.
* Support for getting real-time feedback about the playback of media, so your code can make informed decisions about adapting the stream's quality or other settings to manage the user's perceived media performance and quality. One feature of this is the ability to detect when the device switches GPUs, so you can make appropriate adjustments based on the new GPU's capabilities.

**Note:** The display capabilities functionality mentioned in the third point above have not yet appeared in any browser. They will be a useful feature of the API once available, but there is a high probability of the display capabilities functionality changing a great deal before browser implementations arrive.

The MediaCapabilities interface
-------------------------------

The `MediaCapabilities` is available using the `mediaCapabilities` property which is provided by both the `navigator` object and the `WorkerNavigator` object; in other words, the Media Capabilities API is available both on the main thread and from workers.

If the object exists, Media Capabilities API is available. You can, therefore, test for the presence of the API like so:

```js
if ("mediaCapabilities" in navigator) {
  // mediaCapabilities is available
} else {
  // mediaCapabilities IS NOT available
}
```

Taking video as an example, to obtain information about video decoding abilities, you create a video decoding configuration which you pass as a parameter to `MediaCapabilities.decodingInfo()` method. This returns a promise that fulfills with information about the media capabilities as to whether the video can be decoded, and whether decoding will be smooth and power efficient. You can also test audio decoding as well as video and audio encoding.

### Creating a video decoding configuration

The `MediaCapabilities.decodingInfo()` method takes as a parameter a media decoding configuration.

In our example, we are testing the decoding capabilities of a video configuration. The configuration requires the type of media being tested — e.g. a plain `file` or `MediaSource` — and a video configuration object that includes values for the `contentType`, `width`, `height`, `bitrate`, and `framerate`:

* The `contentType` must be a string specifying a valid video MIME type.
* The `width` and `height` are the horizontal and vertical dimensions of the video; these are also used to determine the aspect ratio.
* The `bitrate` is the number of bits used to encode one second of video.
* The `framerate` is the number of frames which are played per second of time when playing the video.

```js
const videoConfiguration = {
  type: "file",
  video: {
    contentType: "video/webm;codecs=vp8",
    width: 800,
    height: 600,
    bitrate: 10000,
    framerate: 15,
  },
};
```

Had we been querying the decodability of an audio file, we would create an audio configuration including the number of channels and sample rate, leaving out the properties that apply only to video—namely, the dimensions and the frame rate:

```js
const audioConfiguration = {
  type: "file",
  audio: {
    contentType: "audio/ogg",
    channels: 2,
    bitrate: 132700,
    samplerate: 5200,
  },
};
```

 Had we been testing encoding capabilities, we would have created a slightly different configuration.
 In this case the type of media being tested is either `record` (for recording media, i.e. a `MediaRecorder` object) or `transmission` (for media transmitted over electronic means like `RTCPeerConnection`) — plus either an audio or video configuration as described above.

### Querying the browser about decoding abilities

Now that we've created a video decoding configuration we can pass it as a parameter of the `decodingInfo()` method to determine if a video matching this configuration would be decodable and if the playback would be smooth and power efficient.

```js
let promise = navigator.mediaCapabilities.decodingInfo(videoConfiguration);
```

The `decodingInfo()` and `encodingInfo()` methods both return promises. Once the promises state is fulfilled, you can access the `supported`, `smooth`, and `powerEfficient` properties from the returned object.

### Handling the response

Instead of the assigning the promise to a variable, we can output the values returned by the promise to the console:

```js
navigator.mediaCapabilities.decodingInfo(videoConfiguration).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.`);
});
```

Handling errors
---------------

In our video decoding example, a `TypeError` would be raised if the media configuration passed to the `decodingInfo()` method was invalid. There are a few reasons why an error might occur, including:

* The specified `type` isn't one of the two permitted values: `file` or `media-source`
* The `contentType` given is

The error can be due to the `type` not being one of the two possible values, the `contentType` not being a valid codec MIME type, or invalid or omitted definitions being omitted from the video configuration object.

```js
navigator.mediaCapabilities
  .decodingInfo(videoConfiguration)
  .then(console.log("It worked"))
  .catch((error) => console.error(`It failed: ${error}`));
```

Media Capabilities live example
-------------------------------

### CSS

```css
li {
  margin: 1em;
}
```

### HTML

```html
<form>
  <p>
    Select your video configuration and find out if this browser supports the
    codec, and whether decoding will be smooth and power efficient:
  </p>
  <ul>
    <li>
      <label for="codec">Select a codec</label>
      <select id="codec">
        <option>video/webm; codecs=vp8</option>
        <option>video/webm; codecs=vp9</option>
        <option>video/mp4; codecs=avc1</option>
        <option>video/mp4; codecs=avc1.420034</option>
        <option>video/ogg; codecs=theora</option>
        <option>invalid</option>
      </select>
    </li>
    <li>
      <label for="size">Select a size</label>
      <select id="size">
        <option>7680x4320</option>
        <option>3840x2160</option>
        <option>2560x1440</option>
        <option>1920x1080</option>
        <option>1280x720</option>
        <option selected>800x600</option>
        <option>640x480</option>
        <option>320x240</option>
        <option value=" x ">none</option>
      </select>
    </li>
    <li>
      <label for="framerate">Select a framerate</label>
      <select id="framerate">
        <option>60</option>
        <option>50</option>
        <option>30</option>
        <option>24</option>
        <option selected>15</option>
      </select>
    </li>
    <li>
      <label for="bitrate">Select a bitrate</label>
      <select id="bitrate">
        <option>4000</option>
        <option>2500</option>
        <option>800</option>
      </select>
    </li>
  </ul>
  <p>
    <input type="button" value="Test this Video Configuration" id="try-it" />
  </p>
</form>

<ul id="results"></ul>
```

### JavaScript

```js
let mc = {
  videoConfiguration: new Object(),

  tryIt() {
    mc.createConfiguration();
    mc.testIt();
  },

  createConfiguration() {
    const size = document.getElementById("size").value.split("x");
    mc.videoConfiguration = {
      type: "file",
      video: {
        contentType: document.getElementById("codec").value,
        width: size[0],
        height: size[1],
        bitrate: document.getElementById("bitrate").value,
        framerate: document.getElementById("framerate").value,
      },
    };
  },

  testIt() {
    let content = "";
    navigator.mediaCapabilities
      .decodingInfo(mc.videoConfiguration)
      .then((result) => {
        const li = document.createElement("li"),
          mcv = mc.videoConfiguration.video;
        content = `A ${mcv.width}x${mcv.height}, ${mcv.contentType} at ${
 mcv.framerate
 }fps and ${mcv.bitrate} bps video ${
 result.supported ? " IS " : "IS NOT "
 } supported,`;
        content += `${result.smooth ? " IS " : " is NOT "} smooth, and`;
        content += `${
 result.powerEfficient ? " IS " : " IS NOT "
 }power efficient.`;
        const ul = document.getElementById("results");
        li.innerHTML = content;
        ul.appendChild(li);
      })
      .catch((error) => {
        const li = document.createElement("li"),
          ul = document.getElementById("results");
        li.textContent = `Codec ${mc.videoConfiguration.video.contentType} threw an error: ${error}`;
        ul.appendChild(li);
      });
  },
};

document.getElementById("try-it").addEventListener("click", mc.tryIt);
```

### Live Result

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

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

See also
--------

* `navigator.mediaCapabilities`


XMLHttpRequest: setRequestHeader() method - Web APIs

XMLHttpRequest: setRequestHeader() method
=========================================

 The `XMLHttpRequest` method **`setRequestHeader()`** sets the value of an HTTP request header.
 When using `setRequestHeader()`, you must call it after calling `open()`, but before calling `send()`.
 If this method is called several times with the same header, the values are merged into one single request header.

Each time you call `setRequestHeader()` after the first time you call it, the specified text is appended to the end of the existing header's content.

If no `Accept` header has been set using this, an `Accept` header with the type `"*/*"` is sent with the request when `send()` is called.

For security reasons, there are several forbidden header names whose values are controlled by the user agent. Any attempt to set a value for one of those headers from frontend JavaScript code will be ignored without warning or error.

In addition, the `Authorization` HTTP header may be added to a request, but will be removed if the request is redirected cross-origin.

**Note:** For your custom fields, you may encounter a "**not allowed by Access-Control-Allow-Headers in preflight response**" exception when you send requests across domains.
 In this situation, you need to set up the `Access-Control-Allow-Headers` in your response header at server side.

Syntax
------

```js
setRequestHeader(header, value)
```

### Parameters

`header`

The name of the header whose value is to be set.

`value`

The value to set as the body of the header.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-setrequestheader()-method |

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

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

See also
--------

* Using XMLHttpRequest
* HTML in XMLHttpRequest


XMLHttpRequest: timeout event - Web APIs

XMLHttpRequest: timeout event
=============================

The **`timeout`** event is fired when progression is terminated due to preset time expiring.

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

```js
const client = new XMLHttpRequest();
client.open("GET", "http://www.example.org/example.txt");
client.ontimeout = () => {
  console.error("Timeout!!");
};

client.send();
```

You could also set up the event handler using the `addEventListener()` method:

```js
client.addEventListener("timeout", () => {
  console.error("Timeout!!");
});
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-timeout |
| XMLHttpRequest Standard # handler-xhr-ontimeout |

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

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

See also
--------

* `XMLHttpRequest`


XMLHttpRequest: getAllResponseHeaders() method - Web APIs

XMLHttpRequest: getAllResponseHeaders() method
==============================================

 The `XMLHttpRequest` method
 **`getAllResponseHeaders()`** returns all the response
 headers, separated by CRLF, as a string, or returns `null`
 if no response has been received.

 If a network error happened, an empty string
 is returned.

**Note:** For multipart requests, this returns the headers from the
 *current* part of the request, not from the original channel.

Syntax
------

```js
getAllResponseHeaders()
```

### Parameters

None.

### Return value

 A string representing all of the response's headers (except those
 whose field name is `Set-Cookie`) separated by CRLF,
 or `null` if no response has been received. If a network error
 happened, an empty string is returned.

An example of what a raw header string looks like:

```http
date: Fri, 08 Dec 2017 21:04:30 GMT\r\n
content-encoding: gzip\r\n
x-content-type-options: nosniff\r\n
server: meinheld/0.6.1\r\n
x-frame-options: DENY\r\n
content-type: text/html; charset=utf-8\r\n
connection: keep-alive\r\n
strict-transport-security: max-age=63072000\r\n
vary: Cookie, Accept-Encoding\r\n
content-length: 6502\r\n
x-xss-protection: 1; mode=block\r\n
```

 Each line is terminated by both carriage return and line feed characters
 (`\r\n`). These are essentially delimiters separating each of the headers.

**Note:** In modern browsers, the header names are returned in all lower
 case, as per the latest spec.

Examples
--------

 This example examines the headers in the request's `readystatechange` event. The code shows how to obtain
 the raw header string, as well as how to convert it into an array of individual headers
 and then how to take that array and create a mapping of header names to their values.

```js
const request = new XMLHttpRequest();
request.open("GET", "foo.txt", true);
request.send();

request.onreadystatechange = () => {
  if (request.readyState === this.HEADERS\_RECEIVED) {
    // Get the raw header string
    const headers = request.getAllResponseHeaders();

    // Convert the header string into an array
    // of individual headers
    const arr = headers.trim().split(/[\r\n]+/);

    // Create a map of header names to values
    const headerMap = {};
    arr.forEach((line) => {
      const parts = line.split(": ");
      const header = parts.shift();
      const value = parts.join(": ");
      headerMap[header] = value;
    });
  }
};
```

Once this is done, you can, for example:

```js
const contentType = headerMap["content-type"];
```

 This obtains the value of the `Content-Type` header into the variable
 `contentType`.

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-getallresponseheaders()-method |

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

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

See also
--------

* Using XMLHttpRequest
* Setting request headers: `setRequestHeader()`


XMLHttpRequest: XMLHttpRequest() constructor - Web APIs

XMLHttpRequest: XMLHttpRequest() constructor
============================================

 The **`XMLHttpRequest()`** constructor
 creates a new `XMLHttpRequest`.

Syntax
------

```js
new XMLHttpRequest()
```

### Parameters

None.

### Return value

 A new `XMLHttpRequest` object. The object must be prepared by at least
 calling `open()` to initialize it before calling
 `send()` to send the request to the server.

Non-standard Firefox syntax
---------------------------

 Firefox 16 added a non-standard parameter to the constructor that can enable anonymous
 mode (see Firefox bug 692677). Setting the `mozAnon` flag to `true`
 effectively resembles the `AnonXMLHttpRequest()`
 constructor described in older versions of the XMLHttpRequest specification.

```js
const request = new XMLHttpRequest(paramsDictionary);
```

### Parameters (non-standard)

`objParameters`

One flag you can set:

`mozAnon`

 Boolean: Setting this flag to `true` will cause the browser not to
 expose the origin and user credentials when fetching resources. Most important, this means that
 cookies will not be sent unless explicitly added using
 setRequestHeader.

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

| Specification |
| --- |
| XMLHttpRequest Standard # dom-xmlhttprequest |

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

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

See also
--------

* Using XMLHttpRequest
* HTML in XMLHttpRequest


XMLHttpRequest: loadend event - Web APIs

XMLHttpRequest: loadend event
=============================

The **`loadend`** event is fired when a request has completed, whether successfully (after `load`) or unsuccessfully (after `abort` or `error`).

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Live example

#### HTML

```html
<div class="controls">
  <input
 class="xhr success"
 type="button"
 name="xhr"
 value="Click to start XHR (success)" />
  <input
 class="xhr error"
 type="button"
 name="xhr"
 value="Click to start XHR (error)" />
  <input
 class="xhr abort"
 type="button"
 name="xhr"
 value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
```

```
.event-log {
  width: 25rem;
  height: 4rem;
  border: 1px solid black;
  margin: 0.5rem;
  padding: 0.2rem;
}

input {
  width: 11rem;
  margin: 0.5rem;
}
```

#### JavaScript

```js
const xhrButtonSuccess = document.querySelector(".xhr.success");
const xhrButtonError = document.querySelector(".xhr.error");
const xhrButtonAbort = document.querySelector(".xhr.abort");
const log = document.querySelector(".event-log");

function handleEvent(e) {
  log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}

function addListeners(xhr) {
  xhr.addEventListener("loadstart", handleEvent);
  xhr.addEventListener("load", handleEvent);
  xhr.addEventListener("loadend", handleEvent);
  xhr.addEventListener("progress", handleEvent);
  xhr.addEventListener("error", handleEvent);
  xhr.addEventListener("abort", handleEvent);
}

function runXHR(url) {
  log.textContent = "";

  const xhr = new XMLHttpRequest();
  addListeners(xhr);
  xhr.open("GET", url);
  xhr.send();
  return xhr;
}

xhrButtonSuccess.addEventListener("click", () => {
  runXHR(
    "https://raw.githubusercontent.com/mdn/content/main/files/en-us/\_wikihistory.json",
  );
});

xhrButtonError.addEventListener("click", () => {
  runXHR("http://i-dont-exist");
});

xhrButtonAbort.addEventListener("click", () => {
  runXHR(
    "https://raw.githubusercontent.com/mdn/content/main/files/en-us/\_wikihistory.json",
  ).abort();
});
```

#### Result

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-loadend |
| XMLHttpRequest Standard # handler-xhr-onloadend |

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

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

See also
--------

* Related events: `loadstart`, `load`, `progress`, `error`, `abort`
* Monitoring progress


XMLHttpRequest: error event - Web APIs

XMLHttpRequest: error event
===========================

The `error` event is fired when the request encountered an error.

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Live example

#### HTML

```html
<div class="controls">
  <input
 class="xhr success"
 type="button"
 name="xhr"
 value="Click to start XHR (success)" />
  <input
 class="xhr error"
 type="button"
 name="xhr"
 value="Click to start XHR (error)" />
  <input
 class="xhr abort"
 type="button"
 name="xhr"
 value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
```

```
.event-log {
  width: 25rem;
  height: 4rem;
  border: 1px solid black;
  margin: 0.5rem;
  padding: 0.2rem;
}

input {
  width: 11rem;
  margin: 0.5rem;
}
```

#### JavaScript

```js
const xhrButtonSuccess = document.querySelector(".xhr.success");
const xhrButtonError = document.querySelector(".xhr.error");
const xhrButtonAbort = document.querySelector(".xhr.abort");
const log = document.querySelector(".event-log");

function handleEvent(e) {
  log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}

function addListeners(xhr) {
  xhr.addEventListener("loadstart", handleEvent);
  xhr.addEventListener("load", handleEvent);
  xhr.addEventListener("loadend", handleEvent);
  xhr.addEventListener("progress", handleEvent);
  xhr.addEventListener("error", handleEvent);
  xhr.addEventListener("abort", handleEvent);
}

function runXHR(url) {
  log.textContent = "";

  const xhr = new XMLHttpRequest();
  addListeners(xhr);
  xhr.open("GET", url);
  xhr.send();
  return xhr;
}

xhrButtonSuccess.addEventListener("click", () => {
  runXHR("example-image.jpg");
});

xhrButtonError.addEventListener("click", () => {
  runXHR("https://example.com/notfound.jpg");
});

xhrButtonAbort.addEventListener("click", () => {
  runXHR("example-image.jpg").abort();
});
```

#### Result

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-error |
| XMLHttpRequest Standard # handler-xhr-onerror |

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

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

See also
--------

* Related events: `loadstart`, `load`, `progress`, `loadend`, `abort`
* Monitoring progress


XMLHttpRequest: load event - Web APIs

XMLHttpRequest: load event
==========================

The `load` event is fired when an `XMLHttpRequest` transaction completes successfully.

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Live example

#### HTML

```html
<div class="controls">
  <input
 class="xhr success"
 type="button"
 name="xhr"
 value="Click to start XHR (success)" />
  <input
 class="xhr error"
 type="button"
 name="xhr"
 value="Click to start XHR (error)" />
  <input
 class="xhr abort"
 type="button"
 name="xhr"
 value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
```

```
.event-log {
  width: 25rem;
  height: 4rem;
  border: 1px solid black;
  margin: 0.5rem;
  padding: 0.2rem;
}

input {
  width: 11rem;
  margin: 0.5rem;
}
```

#### JavaScript

```js
const xhrButtonSuccess = document.querySelector(".xhr.success");
const xhrButtonError = document.querySelector(".xhr.error");
const xhrButtonAbort = document.querySelector(".xhr.abort");
const log = document.querySelector(".event-log");

function handleEvent(e) {
  log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}

function addListeners(xhr) {
  xhr.addEventListener("loadstart", handleEvent);
  xhr.addEventListener("load", handleEvent);
  xhr.addEventListener("loadend", handleEvent);
  xhr.addEventListener("progress", handleEvent);
  xhr.addEventListener("error", handleEvent);
  xhr.addEventListener("abort", handleEvent);
}

function runXHR(url) {
  log.textContent = "";

  const xhr = new XMLHttpRequest();
  addListeners(xhr);
  xhr.open("GET", url);
  xhr.send();
  return xhr;
}

xhrButtonSuccess.addEventListener("click", () => {
  runXHR("image.jpg");
});

xhrButtonError.addEventListener("click", () => {
  runXHR("https://somewhere.org/i-dont-exist");
});

xhrButtonAbort.addEventListener("click", () => {
  runXHR("image.jpg").abort();
});
```

#### Result

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-load |
| XMLHttpRequest Standard # handler-xhr-onload |

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

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

See also
--------

* Related events: `loadstart`, `loadend`, `progress`, `error`, `abort`
* Monitoring progress


XMLHttpRequest: timeout property - Web APIs

XMLHttpRequest: timeout property
================================

The **`XMLHttpRequest.timeout`** property is an `unsigned long` representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout. Timeout shouldn't be used for synchronous XMLHttpRequests requests used in a document environment or it will throw an `InvalidAccessError` exception. When a timeout happens, a timeout event is fired.

**Note:** You may not use a timeout for synchronous requests with an owning window.

Using a timeout with an asynchronous request.

Example
-------

```js
const xhr = new XMLHttpRequest();
xhr.open("GET", "/server", true);

xhr.timeout = 2000; // time in milliseconds

xhr.onload = () => {
  // Request finished. Do processing here.
};

xhr.ontimeout = (e) => {
  // XMLHttpRequest timed out. Do something here.
};

xhr.send(null);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-timeout-attribute |

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

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


XMLHttpRequest: progress event - Web APIs

XMLHttpRequest: progress event
==============================

The **`progress`** event is fired periodically when a request receives more data.

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Live example

#### HTML

```html
<div class="controls">
  <input
 class="xhr success"
 type="button"
 name="xhr"
 value="Click to start XHR (success)" />
  <input
 class="xhr error"
 type="button"
 name="xhr"
 value="Click to start XHR (error)" />
  <input
 class="xhr abort"
 type="button"
 name="xhr"
 value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
```

```
.event-log {
  width: 25rem;
  height: 4rem;
  border: 1px solid black;
  margin: 0.5rem;
  padding: 0.2rem;
}

input {
  width: 11rem;
  margin: 0.5rem;
}
```

#### JavaScript

```js
const xhrButtonSuccess = document.querySelector(".xhr.success");
const xhrButtonError = document.querySelector(".xhr.error");
const xhrButtonAbort = document.querySelector(".xhr.abort");
const log = document.querySelector(".event-log");

function handleEvent(e) {
  log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}

function addListeners(xhr) {
  xhr.addEventListener("loadstart", handleEvent);
  xhr.addEventListener("load", handleEvent);
  xhr.addEventListener("loadend", handleEvent);
  xhr.addEventListener("progress", handleEvent);
  xhr.addEventListener("error", handleEvent);
  xhr.addEventListener("abort", handleEvent);
}

function runXHR(url) {
  log.textContent = "";

  const xhr = new XMLHttpRequest();
  addListeners(xhr);
  xhr.open("GET", url);
  xhr.send();
  return xhr;
}

xhrButtonSuccess.addEventListener("click", () => {
  runXHR(
    "https://raw.githubusercontent.com/mdn/content/main/files/en-us/\_wikihistory.json",
  );
});

xhrButtonError.addEventListener("click", () => {
  runXHR("http://i-dont-exist");
});

xhrButtonAbort.addEventListener("click", () => {
  runXHR(
    "https://raw.githubusercontent.com/mdn/content/main/files/en-us/\_wikihistory.json",
  ).abort();
});
```

#### Result

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-progress |
| XMLHttpRequest Standard # handler-xhr-onprogress |

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

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

See also
--------

* Related events: `loadstart`, `load`, `loadend`, `error`, `abort`
* Monitoring progress


XMLHttpRequest: responseURL property - Web APIs

XMLHttpRequest: responseURL property
====================================

The read-only **`XMLHttpRequest.responseURL`** property returns the serialized URL of the response or the empty string if the URL is `null`. If the URL is returned, any URL fragment present in the URL will be stripped away. The value of `responseURL` will be the final URL obtained after any redirects.

Example
-------

```js
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/test", true);
xhr.onload = () => {
  console.log(xhr.responseURL); // http://example.com/test
};
xhr.send(null);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-responseurl-attribute |

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

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


XMLHttpRequest: status property - Web APIs

XMLHttpRequest: status property
===============================

The read-only **`XMLHttpRequest.status`** property returns the numerical HTTP status code of the `XMLHttpRequest`'s response.

Before the request completes, the value of `status` is 0. Browsers also report a status of 0 in case of `XMLHttpRequest` errors.

Value
-----

A number.

Examples
--------

```js
const xhr = new XMLHttpRequest();
console.log("UNSENT: ", xhr.status);

xhr.open("GET", "/server");
console.log("OPENED: ", xhr.status);

xhr.onprogress = () => {
  console.log("LOADING: ", xhr.status);
};

xhr.onload = () => {
  console.log("DONE: ", xhr.status);
};

xhr.send();

/\*\*
 \* Outputs the following:
 \*
 \* UNSENT: 0
 \* OPENED: 0
 \* LOADING: 200
 \* DONE: 200
 \*/
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-status-attribute |

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

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

See also
--------

* List of HTTP status
* HTTP


XMLHttpRequest: responseType property - Web APIs

XMLHttpRequest: responseType property
=====================================

 The `XMLHttpRequest` property
 **`responseType`** is an enumerated string value specifying
 the type of data contained in the response.

 It also lets the author change the
 response type. If an empty string is set as the value of `responseType`, the
 default value of `text` is used.

Value
-----

 A string which specifies what type of data the response contains.
 It can take the following values:

`""`

An empty `responseType` string is the same as `"text"`, the default type.

`"arraybuffer"`

The `response` is a JavaScript `ArrayBuffer` containing binary data.

`"blob"`

The `response` is a `Blob` object containing the binary data.

`"document"`

The `response` is an HTML `Document` or XML `XMLDocument`, as appropriate based on the MIME type of the received data. See HTML in XMLHttpRequest to learn more about using XHR to fetch HTML content.

`"json"`

The `response` is a JavaScript object created by parsing the contents of received data as JSON.

`"text"`

The `response` is a text in a string.

**Note:** When setting `responseType` to a particular value, the author should make
 sure that the server is actually sending a response compatible with that format. If
 the server returns data that is not compatible with the `responseType` that
 was set, the value of `response` will be
 `null`.

### Exceptions

`InvalidAccessError` `DOMException`

 An attempt was made to change the value of `responseType` on
 an `XMLHttpRequest` which is in synchronous mode but not in a
 `Worker`. For additional details, see Synchronous XHR restrictions below.

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

### Synchronous XHR restrictions

 You cannot change the value of `responseType` in a synchronous
 `XMLHttpRequest` except when the request belongs to a `Worker`.
 This restriction is designed in part to help ensure that synchronous operations aren't
 used for large transactions that block the browser's main thread, thereby bogging down
 the user experience.

 XHR requests are asynchronous by default; they are only placed in
 synchronous mode by passing `false` as the value of the optional
 `async` parameter when calling `open()`.

### Restrictions in Workers

 Attempts to set the value of `responseType` to `document` are
 ignored in a `Worker`.

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-responsetype-attribute |

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

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

See also
--------

* Using XMLHttpRequest
* HTML in XMLHttpRequest
* The response data: `response`,
 `responseText`, and
 `responseXML`


XMLHttpRequest: mozBackgroundRequest property - Web APIs

XMLHttpRequest: mozBackgroundRequest property
=============================================

**Note:** This method is not available from Web content. It requires elevated privileges to access.

**`XMLHttpRequest.mozBackgroundRequest`** is a Boolean, indicating if the object represents a background service request. If `true`, no load group is associated with the request, with security dialogs prevented from being shown to the user.

In cases in where a security dialog (such as authentication or a bad certificate notification) would normally be shown, this request fails instead.

**Note:** This property must be set before calling `open()`.


XMLHttpRequest: getResponseHeader() method - Web APIs

XMLHttpRequest: getResponseHeader() method
==========================================

 The `XMLHttpRequest` method
 **`getResponseHeader()`** returns the string containing the
 text of a particular header's value.

 If there are multiple response headers
 with the same name, then their values are returned as a single concatenated string,
 where each value is separated from the previous one by a pair of comma and space. The
 `getResponseHeader()` method returns the value as a UTF byte sequence.

**Note:** The search for the header name is case-insensitive.

 If you need to get the raw string of all of the headers, use the
 `getAllResponseHeaders()` method,
 which returns the entire raw header string.

Syntax
------

```js
getResponseHeader(headerName)
```

### Parameters

`headerName`

 A string indicating the name of the header you want to return the
 text value of.

### Return value

 A string representing the header's text value, or `null`
 if either the response has not yet been received or the header doesn't exist in the
 response.

Examples
--------

 In this example, a request is created and sent, and a `readystatechange`
 handler is established to look for the `readyState` to indicate that the headers have been received; when that is the case,
 the value of the `Content-Type` header is fetched. If the
 `Content-Type` isn't the desired value, the `XMLHttpRequest` is
 canceled by calling `abort()`.

```js
const client = new XMLHttpRequest();
client.open("GET", "unicorns-are-awesome.txt", true);
client.send();

client.onreadystatechange = () => {
  if (client.readyState === client.HEADERS\_RECEIVED) {
    const contentType = client.getResponseHeader("Content-Type");
    if (contentType !== my_expected_type) {
      client.abort();
    }
  }
};
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # dom-xmlhttprequest-getresponseheader |

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

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

See also
--------

* Using XMLHttpRequest
* HTTP headers
* `getAllResponseHeaders()`
* `response`
* Setting request headers: `setRequestHeader()`


XMLHttpRequest: mozSystem property - Web APIs

XMLHttpRequest: mozSystem property
==================================

**`mozSystem`** is a boolean. If true, the same origin policy is not enforced on the request.


XMLHttpRequest: loadstart event - Web APIs

XMLHttpRequest: loadstart event
===============================

The **`loadstart`** event is fired when a request has started to load data.

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Live example

#### HTML

```html
<div class="controls">
  <input
 class="xhr success"
 type="button"
 name="xhr"
 value="Click to start XHR (success)" />
  <input
 class="xhr error"
 type="button"
 name="xhr"
 value="Click to start XHR (error)" />
  <input
 class="xhr abort"
 type="button"
 name="xhr"
 value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
```

```
.event-log {
  width: 25rem;
  height: 4rem;
  border: 1px solid black;
  margin: 0.5rem;
  padding: 0.2rem;
}

input {
  width: 11rem;
  margin: 0.5rem;
}
```

#### JavaScript

```js
const xhrButtonSuccess = document.querySelector(".xhr.success");
const xhrButtonError = document.querySelector(".xhr.error");
const xhrButtonAbort = document.querySelector(".xhr.abort");
const log = document.querySelector(".event-log");

function handleEvent(e) {
  log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}

function addListeners(xhr) {
  xhr.addEventListener("loadstart", handleEvent);
  xhr.addEventListener("load", handleEvent);
  xhr.addEventListener("loadend", handleEvent);
  xhr.addEventListener("progress", handleEvent);
  xhr.addEventListener("error", handleEvent);
  xhr.addEventListener("abort", handleEvent);
}

function runXHR(url) {
  log.textContent = "";

  const xhr = new XMLHttpRequest();
  addListeners(xhr);
  xhr.open("GET", url);
  xhr.send();
  return xhr;
}

xhrButtonSuccess.addEventListener("click", () => {
  runXHR("example-image.jpg");
});

xhrButtonError.addEventListener("click", () => {
  runXHR("https://example.com/notfound.jpg");
});

xhrButtonAbort.addEventListener("click", () => {
  runXHR("example-image.jpg").abort();
});
```

#### Result

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-loadstart |
| XMLHttpRequest Standard # handler-xhr-onloadstart |

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

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

See also
--------

* Related events: `loadend`, `load`, `progress`, `error`, `abort`
* Monitoring progress


XMLHttpRequest: send() method - Web APIs

XMLHttpRequest: send() method
=============================

 The `XMLHttpRequest` method
 **`send()`** sends the request to the server.

 If the
 request is asynchronous (which is the default), this method returns as soon as the
 request is sent and the result is delivered using events. If the request is synchronous,
 this method doesn't return until the response has arrived.

`send()` accepts an optional parameter which lets you specify the request's
 body; this is primarily used for requests such as `PUT`. If the request
 method is `GET` or `HEAD`, the `body`
 parameter is ignored and the request body is set to `null`.

 If no `Accept` header has been set using the
 `setRequestHeader()`, an
 `Accept` header with the type `"*/*"` (any type) is sent.

Syntax
------

```js
send()
send(body)
```

### Parameters

`body` Optional

A body of data to be sent in the XHR request. This can be:

* A `Document`, in which case it is serialized before being sent.
* An `XMLHttpRequestBodyInit`, which per the Fetch spec can be a `Blob`, an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `FormData`, a `URLSearchParams`, or a string literal or object.
* `null`

If no value is specified for the body, a default value of `null` is used.

 The best way to send binary content (e.g. in file uploads) is by using
 a `TypedArray`, a `DataView` or a `Blob` object
 in conjunction with the `send()` method.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `send()` has already been invoked for the request, and/or the request is complete.

`NetworkError` `DOMException`

Thrown if the resource type to be fetched is a Blob, and the method is not `GET`.

Example: GET
------------

```js
const xhr = new XMLHttpRequest();
xhr.open("GET", "/server", true);

xhr.onload = () => {
  // Request finished. Do processing here.
};

xhr.send(null);
// xhr.send('string');
// xhr.send(new Blob());
// xhr.send(new Int8Array());
// xhr.send(document);
```

Example: POST
-------------

```js
const xhr = new XMLHttpRequest();
xhr.open("POST", "/server", true);

// Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = () => {
  // Call a function when the state changes.
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    // Request finished. Do processing here.
  }
};
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-send()-method |

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

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

See also
--------

* Using XMLHttpRequest
* HTML in XMLHttpRequest


XMLHttpRequest: abort() method - Web APIs

XMLHttpRequest: abort() method
==============================

 The **`XMLHttpRequest.abort()`** method aborts the request if
 it has already been sent. When a request is aborted, its
 `readyState` is changed to
 `XMLHttpRequest.UNSENT` (0) and the request's
 `status` code is set to 0.

Syntax
------

```js
abort()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

 This example begins loading content from the MDN home page, then due to some condition,
 aborts the transfer by calling `abort()`.

```js
const xhr = new XMLHttpRequest();
const method = "GET";
const url = "https://developer.mozilla.org/";
xhr.open(method, url, true);

xhr.send();

if (OH\_NOES\_WE\_NEED\_TO\_CANCEL\_RIGHT\_NOW\_OR\_ELSE) {
  xhr.abort();
}
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-abort()-method |

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

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

See also
--------

* Using XMLHttpRequest


XMLHttpRequest: responseXML property - Web APIs

XMLHttpRequest: responseXML property
====================================

 The **`XMLHttpRequest.responseXML`** read-only property returns
 a `Document` containing the HTML or XML retrieved by the request; or
 `null` if the request was unsuccessful, has not yet been sent, or if the data
 can't be parsed as XML or HTML.

**Note:** The name `responseXML` is an artifact of this
 property's history; it works for both HTML and XML.

 Usually, the response is parsed as "`text/xml`". If the
 `responseType` is set to
 "`document`" and the request was made asynchronously, instead the response is
 parsed as "`text/html`". `responseXML` is `null` for
 any other types of data, as well as for `data:` URLs.

 If the server doesn't specify the `Content-Type` as
 "`text/xml`" or "`application/xml`", you can use
 `XMLHttpRequest.overrideMimeType()` to parse it as XML anyway.

This property isn't available to workers.

Value
-----

 A `Document` from parsing the XML or HTML received using
 `XMLHttpRequest`, or `null` if no data was received or if the
 data is not XML/HTML.

### Exceptions

`InvalidStateError` `DOMException`

 Thrown if the `responseType` isn't either
 `document` or an empty string.

Examples
--------

```js
const xhr = new XMLHttpRequest();
xhr.open("GET", "/server");

// If specified, responseType must be empty string or "document"
xhr.responseType = "document";

// Force the response to be parsed as XML
xhr.overrideMimeType("text/xml");

xhr.onload = () => {
  if (xhr.readyState === xhr.DONE && xhr.status === 200) {
    console.log(xhr.response, xhr.responseXML);
  }
};

xhr.send();
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-responsexml-attribute |

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

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

See also
--------

* `XMLHttpRequest`
* `XMLHttpRequest.response`
* `XMLHttpRequest.responseType`
* Parsing and serializing XML
* Parsing XML into a DOM tree: `DOMParser`
* Serializing a DOM tree into XML: `XMLSerializer` (specifically, the
 `serializeToString()` method)


XMLHttpRequest: response property - Web APIs

XMLHttpRequest: response property
=================================

 The `XMLHttpRequest`
**`response`** property returns the response's body content as
 an `ArrayBuffer`, a `Blob`, a `Document`,
 a JavaScript `Object`, or a string, depending on the value
 of the request's `responseType`
 property.

Value
-----

 An appropriate object based on the value of `responseType`. You may attempt to request the data be provided in a specific format
 by setting the value of `responseType` after calling
 `open()` to initialize the request but before
 calling `send()` to send the request to the server.

 The value is `null` if the request is not yet complete or was unsuccessful,
 with the exception that when reading text data using a `responseType` of
 `"text"` or the empty string (`""`), the response can contain the
 response so far while the request is still in the `LOADING`
`readyState` (3).

Examples
--------

 This example presents a function, `load()`, which loads and processes a page
 from the server. It works by creating an `XMLHttpRequest` object and
 creating a listener for `readystatechange` events such that when
 `readyState` changes to `DONE` (4), the `response` is
 obtained and passed into the callback function provided to `load()`.

 The content is handled as raw text data (since nothing here is overriding the default
 `responseType`).

```js
const url = "somePage.html"; //A local page

function load(url, callback) {
  const xhr = new XMLHttpRequest();

  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      callback(xhr.response);
    }
  };

  xhr.open("GET", url, true);
  xhr.send("");
}
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-response-attribute |

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

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

See also
--------

* Using XMLHttpRequest
* Getting text and HTML/XML data: `XMLHttpRequest.responseText` and
 `XMLHttpRequest.responseXML`


XMLHttpRequest: responseText property - Web APIs

XMLHttpRequest: responseText property
=====================================

 The read-only `XMLHttpRequest` property
 **`responseText`** returns the text received from a server
 following a request being sent.

Value
-----

 A string which contains either the textual data received using the
 `XMLHttpRequest` or `null` if the request failed or
 `""` if the request has not yet been sent by calling
 `send()`.

 While handling an asynchronous request, the value of `responseText` always
 has the current content received from the server, even if it's incomplete because the
 data has not been completely received yet.

 You know the entire content has been received when the value of
 `readyState` becomes
 `XMLHttpRequest.DONE` (`4`), and
 `status` becomes 200 (`"OK"`).

### Exceptions

`InvalidStateError` `DOMException`

 Thrown if the `XMLHttpRequest.responseType` is not set to either the empty
 string or `"text"`. Since the `responseText` property is
 only valid for text content, any other value is an error condition.

Examples
--------

```js
const xhr = new XMLHttpRequest();
xhr.open("GET", "/server", true);

// If specified, responseType must be empty string or "text"
xhr.responseType = "text";

xhr.onload = () => {
  if (xhr.readyState === xhr.DONE) {
    if (xhr.status === 200) {
      console.log(xhr.response);
      console.log(xhr.responseText);
    }
  }
};

xhr.send(null);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-responsetext-attribute |

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

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


XMLHttpRequest: readyState property - Web APIs

XMLHttpRequest: readyState property
===================================

The **XMLHttpRequest.readyState** property returns the state an XMLHttpRequest client is in. An XHR client exists in one of the following states:

| Value | State | Description |
| --- | --- | --- |
| `0` | `UNSENT` | Client has been created. `open()` not called yet. |
| `1` | `OPENED` | `open()` has been called. |
| `2` | `HEADERS_RECEIVED` | `send()` has been called, and headers and status are available. |
| `3` | `LOADING` | Downloading; `responseText` holds partial data. |
| `4` | `DONE` | The operation is complete. |

UNSENT

The XMLHttpRequest client has been created, but the open() method hasn't been called yet.

OPENED

open() method has been invoked. During this state, the request headers can be set using the setRequestHeader() method and the send() method can be called which will initiate the fetch.

HEADERS\_RECEIVED

send() has been called, all redirects (if any) have been followed and the response headers have been received.

LOADING

Response's body is being received. If `responseType` is "text" or empty string, `responseText` will have the partial text response as it loads.

DONE

The fetch operation is complete. This could mean that either the data transfer has been completed successfully or failed.

Example
-------

```js
const xhr = new XMLHttpRequest();
console.log("UNSENT", xhr.readyState); // readyState will be 0

xhr.open("GET", "/api", true);
console.log("OPENED", xhr.readyState); // readyState will be 1

xhr.onprogress = () => {
  console.log("LOADING", xhr.readyState); // readyState will be 3
};

xhr.onload = () => {
  console.log("DONE", xhr.readyState); // readyState will be 4
};

xhr.send(null);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # states |

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

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


XMLHttpRequest: withCredentials property - Web APIs

XMLHttpRequest: withCredentials property
========================================

The **`XMLHttpRequest.withCredentials`** property is a boolean value that indicates whether or not cross-site `Access-Control` requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting `withCredentials` has no effect on same-origin requests.

In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is `false`. `XMLHttpRequest` responses from a different domain cannot set cookie values for their own domain unless `withCredentials` is set to `true` before making the request. The third-party cookies obtained by setting `withCredentials` to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.

**Note:** This never affects same-origin requests.

**Note:** `XMLHttpRequest` responses from a different domain *cannot* set cookie values for their own domain unless `withCredentials` is set to `true` before making the request, regardless of `Access-Control-` header values.

Value
-----

A boolean.

Examples
--------

```js
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/", true);
xhr.withCredentials = true;
xhr.send(null);
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-withcredentials-attribute |

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

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


XMLHttpRequest: open() method - Web APIs

XMLHttpRequest: open() method
=============================

 The `XMLHttpRequest` method **`open()`**
 initializes a newly-created request, or re-initializes an existing one.

**Note:** Calling this method for an already active request
 (one for which `open()` has already been called) is the equivalent of calling
 `abort()`.

Syntax
------

```js
open(method, url)
open(method, url, async)
open(method, url, async, user)
open(method, url, async, user, password)
```

### Parameters

`method`

 The HTTP request method to use, such as
 `"GET"`, `"POST"`, `"PUT"`, `"DELETE"`,
 etc. Ignored for non-HTTP(S) URLs.

`url`

A string or any other object with a stringifier — including a `URL` object — that provides the URL of the resource to send the request to.

`async` Optional

 An optional Boolean parameter, defaulting to `true`, indicating whether
 or not to perform the operation asynchronously. If this value is `false`,
 the `send()` method does not return until the response is received. If
 `true`, notification of a completed transaction is provided using event
 listeners. This *must* be true if the `multipart` attribute is
 `true`, or an exception will be thrown.

**Note:** Synchronous requests on the main thread can
 be easily disruptive to the user experience and should be avoided; in fact, many
 browsers have deprecated synchronous XHR support on the main thread entirely.
 Synchronous requests are permitted in `Worker`s.

`user` Optional

 The optional user name to use for authentication purposes; by default, this is the
 `null` value.

`password` Optional

 The optional password to use for authentication purposes; by default, this is the
 `null` value.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-open()-method |

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

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

See also
--------

* Using XMLHttpRequest
* Related `XMLHttpRequest` methods:
 `setRequestHeader()`, `send()`, and
 `abort()`


XMLHttpRequest: mozAnon property - Web APIs

XMLHttpRequest: mozAnon property
================================

**`XMLHttpRequest.mozAnon`** is a boolean. If true, the request will be sent without cookies or authentication headers.


XMLHttpRequest: statusText property - Web APIs

XMLHttpRequest: statusText property
===================================

The read-only **`XMLHttpRequest.statusText`** property returns a string containing the response's status message as returned by the HTTP server. Unlike `XMLHTTPRequest.status` which indicates a numerical status code, this property contains the *text* of the response status, such as "OK" or "Not Found". If the request's `readyState` is in `UNSENT` or `OPENED` state, the value of `statusText` will be an empty string.

If the server response doesn't explicitly specify a status text, `statusText` will assume the default value "OK".

**Note:** Responses over an HTTP/2 connection will always have an empty string as status message as HTTP/2 does not support them.

Value
-----

A string.

Examples
--------

```js
const xhr = new XMLHttpRequest();
console.log("0 UNSENT", xhr.statusText);

xhr.open("GET", "/server", true);
console.log("1 OPENED", xhr.statusText);

xhr.onprogress = () => {
  console.log("3 LOADING", xhr.statusText);
};

xhr.onload = () => {
  console.log("4 DONE", xhr.statusText);
};

xhr.send(null);

/\*\*
 \* Outputs the following:
 \*
 \* 0 UNSENT
 \* 1 OPENED
 \* 3 LOADING OK
 \* 4 DONE OK
 \*/
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-statustext-attribute |

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

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

See also
--------

* List of HTTP status
* HTTP
* WHATWG Fetch Living Standard


XMLHttpRequest: overrideMimeType() method - Web APIs

XMLHttpRequest: overrideMimeType() method
=========================================

 The `XMLHttpRequest` method
 **`overrideMimeType()`** specifies a MIME type other than the
 one provided by the server to be used instead when interpreting the data being
 transferred in a request.

 This may be used, for example, to force a stream to
 be treated and parsed as `"text/xml"`, even if the server does not report it
 as such. This method must be called before calling `send()`.

Syntax
------

```js
overrideMimeType(mimeType)
```

### Parameters

`mimeType`

 A string specifying the MIME type to use instead of the one
 specified by the server. If the server doesn't specify a type,
 `XMLHttpRequest` assumes `"text/xml"`.

### Return value

None (`undefined`).

Examples
--------

 This example specifies a MIME type of `"text/plain"`, overriding the
 server's stated type for the data being received.

**Note:** If the server doesn't provide a
 `Content-Type`
 header, `XMLHttpRequest` assumes that the MIME type is
 `"text/xml"`. If the content isn't valid XML, an "XML Parsing Error: not
 well-formed" error occurs. You can avoid this by calling
 `overrideMimeType()` to specify a different type.

```js
// Interpret the received data as plain text

req = new XMLHttpRequest();
req.overrideMimeType("text/plain");
req.addEventListener("load", callback, false);
req.open("get", url);
req.send();
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-overridemimetype()-method |

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

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

See also
--------

* Using XMLHttpRequest
* `XMLHttpRequest.responseType`


XMLHttpRequest: channel property - Web APIs

XMLHttpRequest: channel property
================================

XMLHttpRequest.channel is an `nsIChannel` that used by the object when performing the request. This is `null` if the channel hasn't been created yet. In the case of a multi-part request, this is the initial channel, not the different parts in the multi-part request. **Requires elevated privileges to access.**


XMLHttpRequest: upload property - Web APIs

XMLHttpRequest: upload property
===============================

The `XMLHttpRequest` `upload` property returns an `XMLHttpRequestUpload` object that can be observed to monitor an upload's progress.

It is an opaque object, but because it's also an `XMLHttpRequestEventTarget`, event listeners can be attached to track its process.

**Note:** Attaching event listeners to this object prevents the request from being a "simple request" and will cause a preflight request to be issued if cross-origin; see CORS. Because of this, event listeners need to be registered before calling `send()` or upload events won't be dispatched.

**Note:** The spec also seems to indicate that event listeners should be attached after `open()`. However, browsers are buggy on this matter, and often need the listeners to be registered *before* `open()` to work.

The following events can be triggered on an upload object and used to monitor the upload:

| Event | Description |
| --- | --- |
| `loadstart` | The upload has begun. |
| `progress` | Periodically delivered to indicate the amount of progress made so far. |
| `abort` | The upload operation was aborted. |
| `error` | The upload failed due to an error. |
| `load` | The upload completed successfully. |
| `timeout` |
 The upload timed out because a reply did not arrive within the time
 interval specified by the
 `XMLHttpRequest.timeout`.
  |
| `loadend` |
 The upload finished. This event does not differentiate between success
 or failure, and is sent at the end of the upload regardless of the
 outcome. Prior to this event, one of `load`,
 `error`, `abort`, or `timeout` will
 already have been delivered to indicate why the upload ended.
  |

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

| Specification |
| --- |
| XMLHttpRequest Standard # the-upload-attribute |

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

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

See also
--------

* Using XMLHttpRequest
* `XMLHttpRequestUpload`


XMLHttpRequest: readystatechange event - Web APIs

XMLHttpRequest: readystatechange event
======================================

The `readystatechange` event is fired whenever the `readyState` property of the `XMLHttpRequest` changes.

**Warning:** This should not be used with synchronous requests and must
 not be used from native code.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

```js
const xhr = new XMLHttpRequest();
const method = "GET";
const url = "https://developer.mozilla.org/";

xhr.open(method, url, true);
xhr.onreadystatechange = () => {
  // In local files, status is 0 upon success in Mozilla Firefox
  if (xhr.readyState === XMLHttpRequest.DONE) {
    const status = xhr.status;
    if (status === 0 || (status >= 200 && status < 400)) {
      // The request has been completed successfully
      console.log(xhr.responseText);
    } else {
      // Oh no! There has been an error with the request!
    }
  }
};
xhr.send();
```

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-readystatechange |
| XMLHttpRequest Standard # handler-xhr-onreadystatechange |

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

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


XMLHttpRequest: abort event - Web APIs

XMLHttpRequest: abort event
===========================

The `abort` event is fired when a request has been aborted, for example because the program called `XMLHttpRequest.abort()`.

Syntax
------

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

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

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

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

A `ProgressEvent`. Inherits from `Event`.

Event

ProgressEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`lengthComputable` Read only

A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

`loaded` Read only

A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

`total` Read only

A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

Examples
--------

### Live example

#### HTML

```html
<div class="controls">
  <input
 class="xhr success"
 type="button"
 name="xhr"
 value="Click to start XHR (success)" />
  <input
 class="xhr error"
 type="button"
 name="xhr"
 value="Click to start XHR (error)" />
  <input
 class="xhr abort"
 type="button"
 name="xhr"
 value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
```

```
.event-log {
  width: 25rem;
  height: 4rem;
  border: 1px solid black;
  margin: 0.5rem;
  padding: 0.2rem;
}

input {
  width: 11rem;
  margin: 0.5rem;
}
```

#### JavaScript

```js
const xhrButtonSuccess = document.querySelector(".xhr.success");
const xhrButtonError = document.querySelector(".xhr.error");
const xhrButtonAbort = document.querySelector(".xhr.abort");
const log = document.querySelector(".event-log");

function handleEvent(e) {
  log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}

function addListeners(xhr) {
  xhr.addEventListener("loadstart", handleEvent);
  xhr.addEventListener("load", handleEvent);
  xhr.addEventListener("loadend", handleEvent);
  xhr.addEventListener("progress", handleEvent);
  xhr.addEventListener("error", handleEvent);
  xhr.addEventListener("abort", handleEvent);
}

function runXHR(url) {
  log.textContent = "";

  const xhr = new XMLHttpRequest();
  addListeners(xhr);
  xhr.open("GET", url);
  xhr.send();
  return xhr;
}

xhrButtonSuccess.addEventListener("click", () => {
  runXHR("my-picture.jpg");
});

xhrButtonError.addEventListener("click", () => {
  runXHR("https://example.com/some-path");
});

xhrButtonAbort.addEventListener("click", () => {
  runXHR("my-picture.jpg").abort();
});
```

#### Result

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

| Specification |
| --- |
| XMLHttpRequest Standard # event-xhr-abort |
| XMLHttpRequest Standard # handler-xhr-onabort |

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

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

See also
--------

* Related events: `loadstart`, `load`, `progress`, `error`, `loadend`
* Monitoring progress


RTCCertificateStats: fingerprintAlgorithm property - Web APIs

RTCCertificateStats: fingerprintAlgorithm property
==================================================

The **`fingerprintAlgorithm`** property of the `RTCCertificateStats` dictionary is a string containing the name of the hash function used to generate the `fingerprint` value in the associated `RTCCertificate`.

Value
-----

A string containing the name of the hash function used to create the fingerprint of the associated certificate.

Allowed values are: `"sha-1"`, `"sha-224"`, `"sha-256"`,`"sha-384"`, `"sha-512"`, `"md5"`, `"md2"`.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtccertificatestats-fingerprintalgorithm |

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

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


RTCCertificateStats: timestamp property - Web APIs

RTCCertificateStats: timestamp property
=======================================

The **`timestamp`** property of the `RTCCertificateStats` dictionary is a `DOMHighResTimeStamp` object specifying the time at which the data in the object was sampled.

Value
-----

A `DOMHighResTimeStamp` value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC.

The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of fingerprinting protection in the form of reduced clock precision or accuracy.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-timestamp |

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

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


RTCCertificateStats: fingerprint property - Web APIs

RTCCertificateStats: fingerprint property
=========================================

The **`fingerprint`** property of the `RTCCertificateStats` dictionary is a string containing the fingerprint value of the associated `RTCCertificate`.

Value
-----

A string containing the fingerprint of the associated certificate.

 This is a lowercase hex string, calculated using the hash function specified in the `fingerprintAlgorithm` property.
 The format is more precisely defined in RFC4572, Section 5.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtccertificatestats-fingerprint |

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

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


RTCCertificateStats: id property - Web APIs

RTCCertificateStats: id property
================================

The **`id`** property of the `RTCCertificateStats` dictionary is a string that uniquely identifies the object for which this object provides statistics.

Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an `RTCPeerConnection`, or an `RTCDataChannel`.

Value
-----

A string that uniquely identifies the object for which this `RTCCertificateStats` object provides statistics.

The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-id |

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

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


RTCCertificateStats: type property - Web APIs

RTCCertificateStats: type property
==================================

The **`type`** property of the `RTCCertificateStats` dictionary is a string with the value `"certificate"`.

 Different statistics are obtained by iterating the `RTCStatsReport` object returned by a call to `RTCPeerConnection.getStats()`.
 The type indicates the set of statistics available through the object in a particular iteration step.
 A value of `"certificate"` indicates that the statistics available in the current step are those defined in `RTCCertificateStats`.

Value
-----

A string with the value `"certificate"`.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-type |

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

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


RTCCertificateStats: base64Certificate property - Web APIs

RTCCertificateStats: base64Certificate property
===============================================

The **`base64Certificate`** property of the `RTCCertificateStats` dictionary is a string containing the base-64 representation of the DER-encoded certificate.

This is essentially an encoding of the original certificate as a string that can safely serialized and deserialized when sent over an IP network.

Value
-----

A Base64 representation of the DER-encoded certificate.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtccertificatestats-base64certificate |

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

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


RTCCertificate: expires property - Web APIs

RTCCertificate: expires property
================================

The read-only **`expires`** property of the `RTCCertificate` interface returns the expiration date of the certificate.

 By default a new certificate is configured with `expires` set to a value of 2592000000 milliseconds, or 30 days.
 The expiration time cannot exceed 31536000000 milliseconds, or 365 days.
 It's also useful to note that browsers may further restrict the expiration time of certificates if they choose.

Value
-----

A timestamp, given as Unix time in milliseconds, containing the expiration date of the certificate.

Examples
--------

```js
RTCPeerConnection.generateCertificate({
  name: "RSASSA-PKCS1-v1\_5",
  hash: "SHA-256",
  modulusLength: 2048,
  publicExponent: new Uint8Array([1, 0, 1]),
}).then((cert) => {
  const pc = new RTCPeerConnection({ certificates: [cert] });
  console.log(cert.expires); // 2592000000 (30 days, the default)
});
```

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

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

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

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

See also
--------

* `RTCPeerConnection.generateCertificate()`


RTCCertificate: getFingerprints() method - Web APIs

RTCCertificate: getFingerprints() method
========================================

The **`getFingerprints()`** method of the **`RTCCertificate`** interface is used to get an array of certificate fingerprints.

 An application can use this method to compare the client certificate fingerprints with the certificate fingerprints from the server.
 The server and client may support different sets of algorithms: all fingerprint values for the set of algorithms supported by both client and server should match.

Syntax
------

```js
getFingerprints()
```

### Parameters

None

### Return value

 An Array of fingerprint values.
 Each fingerprint is represented by an object with the following properties:

`algorithm`

 A string indicating the hash function algorithm used to create the fingerprint in `value`.
 Allowed values include: `"sha-1"`, `"sha-224"`, `"sha-256"`,`"sha-384"`, `"sha-512"`, `"md5"`, `"md2"`.

`value`

 A string containing the certificate fingerprint in lowercase hex string, as calculated with the `algorithm` hash function.
 The format is more precisely defined in RFC4572, Section 5.

Examples
--------

### Getting certificate fingerprints

This example shows how you might get certificate fingerprints and compare them to fingerprints from a server.

 First we create a connection and get the fingerprints.
 We also get the fingerprints from the server using "some mechanism".

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

// Get the certificate fingerprints from the client.
const fingerprintsFromClient = rtcPeerConnection.certificate.getFingerprints();

// Get the certificate fingerprints from the server (pseudo code)
const fingerprintsFromServer = ...;
```

 There are numerous ways to compare the fingerprint arrays.
 Here we convert the arrays to dictionary objects where the algorithm name is the property and then compare them.
 This works because only one fingerprint value can exist for each algorithm.
 (There are many other ways to sort and compare the two arrays).

```js
let clientFingerprintDict = Object.fromEntries(
  fingerprintsFromClient.map((x) => [x.algorithm, x.value]),
);
let serverFingerprintDict = Object.fromEntries(
  fingerprintsFromServer.map((x) => [x.algorithm, x.value]),
);

// Function to compare two objects and return true if there are common properties
// and all common properties match.
function compareObjects(obj1, obj2) {
  const commonProperties = Object.keys(obj1).filter((prop) =>
    obj2.hasOwnProperty(prop),
  );
  // Return false if there are no common properties
  if (Object.keys(commonProperties).length === 0) return false;

  // Return false if any common properties don't match
  for (const prop of commonProperties) {
    if (obj1[prop] !== obj2[prop]) {
      return false;
    }
  }

  return true;
}

const matchingFingerprints = compareObjects(
  clientFingerprintDict,
  serverFingerprintDict,
);
console.log(matchingFingerprints);
```

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

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

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

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


PositionSensorVRDevice: getState() method - Web APIs

PositionSensorVRDevice: getState() method
=========================================

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

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

The **`getState()`** method of the `PositionSensorVRDevice` interface returns the current state of the position sensor for the current frame (e.g. within the current `window.requestAnimationFrame` callback) or for the previous frame, contained with a `VRPose` object. This is the method you'd normally want to use, vs. `PositionSensorVRDevice.getImmediateState`.

Syntax
------

```js
getState()
```

### Parameters

None.

### Return value

A `VRPose` object.

Examples
--------

The following example uses the WebVR API to update the view of a simple `2D canvas` scene on each frame of a `requestAnimationFrame` loop.

```js
function setView() {
  const posState = gPositionSensor.getState();
  if (posState.hasPosition) {
    posPara.textContent = `Position: x${roundToTwo(
 posState.position.x,
 )} y${roundToTwo(posState.position.y)} z${roundToTwo(posState.position.z)}`;
    xPos = -posState.position.x \* WIDTH \* 2;
    yPos = posState.position.y \* HEIGHT \* 2;
    zPos = -posState.position.z > 0.01 ? -posState.position.z : 0.01;
  }

  if (posState.hasOrientation) {
    orientPara.textContent = `Orientation: x${roundToTwo(
 posState.orientation.x,
 )} y${roundToTwo(posState.orientation.y)} z${roundToTwo(
 posState.orientation.z,
 )}`;
    xOrient = posState.orientation.x \* WIDTH;
    yOrient = -posState.orientation.y \* HEIGHT \* 2;
    zOrient = posState.orientation.z \* 180;
  }
}
```

Here we are grabbing a `VRPose` object using `getState()` and storing it in `posState`. We then check to make sure that position and orientation info is present in the current frame using `VRPose.position` and `VRPose.orientation` (these return `null` if, for example the head mounted display is turned off or not pointing at the position sensor, which would cause an error.)

We then output the x, y and z position and orientation values for informational purposes, and use those values to update the `xPos`, `yPos`, `zPos`, `xOrient`, `yOrient`, and `zOrient` variables, which are used to update the scene rendering on each frame.

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

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

See also
--------

* WebVR API


PositionSensorVRDevice: resetSensor() method - Web APIs

PositionSensorVRDevice: resetSensor() method
============================================

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

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

The **`resetSensor()`** method of the `VRDisplay` interface *can be used to reset the sensor if desired, returning the* position and orientation values to zero.

Syntax
------

```js
resetSensor()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

The following demo uses the WebVR API to update the view of a simple `2D canvas` scene on each frame of a `requestAnimationFrame` loop. It features, among other things, a "Reset Sensor" button in the UI, which when pressed runs the `resetSensor()` function on the position sensor. The JavaScript looks like this:

```js
document.querySelector("button").onclick = () => {
  gPositionSensor.resetSensor();
};
```

When the button is pressed, the current position, orientation, etc. of the sensor/head mounted display is set to be 0 — this makes the method useful for calibration when an app is first loaded.

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

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

See also
--------

* WebVR API


PositionSensorVRDevice: getImmediateState() method - Web APIs

PositionSensorVRDevice: getImmediateState() method
==================================================

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

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

The **`getImmediateState()`** method of the `VRDisplay` interface returns the current instantaneous position sensor state. This is intended to only be used rarely, for certain special uses, for example sampling the immediate position of a hand orientation sensor — or at least it will be, in the future.

For most standard uses, you'll probably want to use `PositionSensorVRDevice.getState` instead.

Syntax
------

```js
getImmediateState()
```

### Parameters

None.

### Return value

A `VRPose` object.

Examples
--------

The following demo uses the WebVR API to update the view of a simple `2D canvas` scene on each frame of a `requestAnimationFrame` loop. The main function that updates the view data is as follows:

```js
function setView() {
  const posState = gPositionSensor.getImmediateState();
  if (posState.hasPosition) {
    posPara.textContent = `Position: x${roundToTwo(
 posState.position.x,
 )} y${roundToTwo(posState.position.y)} z${roundToTwo(posState.position.z)}`;
    xPos = -posState.position.x \* WIDTH \* 2;
    yPos = posState.position.y \* HEIGHT \* 2;
    zPos = -posState.position.z > 0.01 ? -posState.position.z : 0.01;
  }

  if (posState.hasOrientation) {
    orientPara.textContent = `Orientation: x${roundToTwo(
 posState.orientation.x,
 )} y${roundToTwo(posState.orientation.y)} z${roundToTwo(
 posState.orientation.z,
 )}`;
    xOrient = posState.orientation.x \* WIDTH;
    yOrient = -posState.orientation.y \* HEIGHT \* 2;
    zOrient = posState.orientation.z \* 180;
  }
}
```

Here we are grabbing a `VRPose` object using `getImmediateState()` and storing it in `posState` (the actual live demo uses `getState()`, but both seem to do the same thing currently.) We then check to make sure that position and orientation info is present in the current frame using `VRPose.position` and `VRPose.orientation` (these return `null` if, for example the head mounted display is turned off or not pointing at the position sensor, which would cause an error.)

We then output the x, y and z position and orientation values for informational purposes, and use those values to update the `xPos`, `yPos`, `zPos`, `xOrient`, `yOrient`, and `zOrient` variables, which are used to update the scene rendering on each frame.

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

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

See also
--------

* WebVR API