Notification: timestamp property - Web APIs

Notification: timestamp property
================================

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

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

 The **`timestamp`** read-only property of the
 `Notification` interface returns a number, as
 specified in the `timestamp` option of the
 `Notification()` constructor.

 The notification's timestamp can represent the time, in milliseconds since 00:00:00 UTC
 on 1 January 1970, of the event for which the notification was created, or it can be an
 arbitrary timestamp that you want associated with the notification. For example, a
 timestamp for an upcoming meeting could be set in the future, whereas a timestamp for a
 missed message could be set in the past.

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

Value
-----

A number representing a timestamp, given as Unix time in milliseconds.

Examples
--------

 The following snippet fires a notification; a simple `options` object is
 created, then the notification is fired using the `Notification()`
 constructor.

```js
const dts = Math.floor(Date.now());

const options = {
  body: "Your code submission has received 3 new review comments.",
  timestamp: dts,
};

const n = new Notification("New review activity", options);

console.log(n.timestamp); // Logs the timestamp
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-timestamp |

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

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

See also
--------

* Using the Notifications API


Notification: show event - Web APIs

Notification: show event
========================

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

The **`show`** event of the `Notification` interface fires when a `Notification` is displayed.

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

Syntax
------

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

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

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

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

A generic `Event`.

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

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

See also
--------

* `Notification`
* Using the Notifications API


Notification: lang property - Web APIs

Notification: lang property
===========================

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

 The **`lang`** read-only property of the
 `Notification` interface indicates the language used in the notification,
 as specified in the `lang` option of the
 `Notification()` constructor.

 The language itself is specified using a string representing a language tag according to RFC 5646: Tags for Identifying Languages (also known as BCP 47).
 See the Sitepoint ISO 2 letter language codes page for a simple reference.

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

Value
-----

A string specifying the language tag.

Examples
--------

 The following snippet fires a notification; a simple `options` object is
 created, then the notification is fired using the `Notification()`
 constructor.

```js
const options = {
  body: "Your code submission has received 3 new review comments.",
  lang: "en-US",
};

const n = new Notification("New review activity", options);

console.log(n.lang); // "en-US"
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-lang |

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

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

See also
--------

* Using the Notifications API


Cross-global fetch usage - Web APIs

Cross-global fetch usage
========================

This article explains an edge case that occurs with fetch (and potentially other APIs exhibiting the same kind of resource retrieval behavior). When a cross-origin fetch involving a relative URL is initiated from an `<iframe>`, the relative URL used to be resolved against the current global location, rather than the iframe's location.

The edge case
-------------

Many sites will never come up against this edge case. To see it:

* You need a same-origin iframe
* That same-origin iframe needs to have a location with a different base URL
* You have to use the fetch function cross-global, e.g. `frame.contentWindow.fetch()`
* The URL passed to fetch needs to be relative
The problem
-----------

In the past we would resolve the relative URL against the current global, for example:

```js
let absolute = new URL(relative, window.location.href);
```

This is not a problem as such. It is just that different APIs that exhibit this kind of behavior were doing it inconsistently with the behavior defined in the spec, which could lead to problems further down the line.

The solution
------------

In Firefox 60 onwards, Mozilla resolves the relative URL against the global that owns the `fetch()` function being used (see Firefox bug 1432272). So in the case described above, it is resolved against the iframe's location:

```js
let absolute = new URL(relative, frame.contentWindow.location.href);
```

There is a lot of discussion in progress about getting new specs to align with this behavior change, to mitigate potential problems going forward.


Using the Fetch API - Web APIs

Using the Fetch API
===================

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global `fetch()` method that provides an easy, logical way to fetch resources asynchronously across the network.

Unlike `XMLHttpRequest` that is a callback-based API, Fetch is promise-based and provides a better alternative that can be easily used in service workers. Fetch also integrates advanced HTTP concepts such as CORS and other extensions to HTTP.

A basic fetch request looks like this:

```js
async function logMovies() {
  const response = await fetch("http://example.com/movies.json");
  const movies = await response.json();
  console.log(movies);
}
```

Here we are fetching a JSON file across the network, parsing it, and printing the data to the console. The simplest use of `fetch()` takes one argument — the path to the resource you want to fetch — and does not directly return the JSON response body but instead returns a promise that resolves with a `Response` object.

The `Response` object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the `Response` object, we use the `json()` method, which returns a second promise that resolves with the result of parsing the response body text as JSON.

**Note:** See the Body section for similar methods to extract other types of body content.

Fetch requests are controlled by the `connect-src` directive of Content Security Policy rather than the directive of the resources it's retrieving.

Supplying request options
-------------------------

The `fetch()` method can optionally accept a second parameter, an `init` object that allows you to control a number of different settings:

See `fetch()` for the full options available, and more details.

```js
// Example POST method implementation:
async function postData(url = "", data = {}) {
  // Default options are marked with \*
  const response = await fetch(url, {
    method: "POST", // \*GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, \*cors, same-origin
    cache: "no-cache", // \*default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, \*same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: "follow", // manual, \*follow, error
    referrerPolicy: "no-referrer", // no-referrer, \*no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData("https://example.com/answer", { answer: 42 }).then((data) => {
  console.log(data); // JSON data parsed by `data.json()` call
});
```

Note that `mode: "no-cors"` only allows a limited set of headers in the request:

* `Accept`
* `Accept-Language`
* `Content-Language`
* `Content-Type` with a value of `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain`
Aborting a fetch
----------------

To abort incomplete `fetch()` operations, use the `AbortController` and `AbortSignal` interfaces.

```js
const controller = new AbortController();
const signal = controller.signal;
const url = "video.mp4";

const downloadBtn = document.querySelector("#download");
const abortBtn = document.querySelector("#abort");

downloadBtn.addEventListener("click", async () => {
  try {
    const response = await fetch(url, { signal });
    console.log("Download complete", response);
  } catch (error) {
    console.error(`Download error: ${error.message}`);
  }
});

abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log("Download aborted");
});
```

Sending a request with credentials included
-------------------------------------------

To cause browsers to send a request with credentials included on both same-origin and cross-origin calls, add `credentials: 'include'` to the `init` object you pass to the `fetch()` method.

```js
fetch("https://example.com", {
  credentials: "include",
});
```

**Note:** `Access-Control-Allow-Origin` is prohibited from using a wildcard for requests with `credentials: 'include'`. In such cases, the exact origin must be provided; even if you are using a CORS unblocker extension, the requests will still fail.

**Note:** Browsers should not send credentials in *preflight requests* irrespective of this setting. For more information see: CORS Requests with credentials.

If you only want to send credentials if the request URL is on the same origin as the calling script, add `credentials: 'same-origin'`.

```js
// The calling script is on the origin 'https://example.com'

fetch("https://example.com", {
  credentials: "same-origin",
});
```

To instead ensure browsers don't include credentials in the request, use `credentials: 'omit'`.

```js
fetch("https://example.com", {
  credentials: "omit",
});
```

Uploading JSON data
-------------------

Use `fetch()` to POST JSON-encoded data.

```js
async function postJSON(data) {
  try {
    const response = await fetch("https://example.com/profile", {
      method: "POST", // or 'PUT'
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    const result = await response.json();
    console.log("Success:", result);
  } catch (error) {
    console.error("Error:", error);
  }
}

const data = { username: "example" };
postJSON(data);
```

Uploading a file
----------------

Files can be uploaded using an HTML `<input type="file" />` input element, `FormData()` and `fetch()`.

```js
async function upload(formData) {
  try {
    const response = await fetch("https://example.com/profile/avatar", {
      method: "PUT",
      body: formData,
    });
    const result = await response.json();
    console.log("Success:", result);
  } catch (error) {
    console.error("Error:", error);
  }
}

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append("username", "abc123");
formData.append("avatar", fileField.files[0]);

upload(formData);
```

Uploading multiple files
------------------------

Files can be uploaded using an HTML `<input type="file" multiple />` input element, `FormData()` and `fetch()`.

```js
async function uploadMultiple(formData) {
  try {
    const response = await fetch("https://example.com/posts", {
      method: "POST",
      body: formData,
    });
    const result = await response.json();
    console.log("Success:", result);
  } catch (error) {
    console.error("Error:", error);
  }
}

const photos = document.querySelector('input[type="file"][multiple]');
const formData = new FormData();

formData.append("title", "My Vegas Vacation");

for (const [i, photo] of Array.from(photos.files).entries()) {
  formData.append(`photos\_${i}`, photo);
}

uploadMultiple(formData);
```

Processing a text file line by line
-----------------------------------

The chunks that are read from a response are not broken neatly at line boundaries and are Uint8Arrays, not strings. If you want to fetch a text file and process it line by line, it is up to you to handle these complications. The following example shows one way to do this by creating a line iterator (for simplicity, it assumes the text is UTF-8, and doesn't handle fetch errors).

```js
async function\* makeTextFileLineIterator(fileURL) {
  const utf8Decoder = new TextDecoder("utf-8");
  const response = await fetch(fileURL);
  const reader = response.body.getReader();
  let { value: chunk, done: readerDone } = await reader.read();
  chunk = chunk ? utf8Decoder.decode(chunk) : "";

  const newline = /\r?\n/gm;
  let startIndex = 0;
  let result;

  while (true) {
    const result = newline.exec(chunk);
    if (!result) {
      if (readerDone) break;
      const remainder = chunk.substr(startIndex);
      ({ value: chunk, done: readerDone } = await reader.read());
      chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
      startIndex = newline.lastIndex = 0;
      continue;
    }
    yield chunk.substring(startIndex, result.index);
    startIndex = newline.lastIndex;
  }

  if (startIndex < chunk.length) {
    // Last line didn't end in a newline char
    yield chunk.substr(startIndex);
  }
}

async function run() {
  for await (const line of makeTextFileLineIterator(urlOfFile)) {
    processLine(line);
  }
}

run();
```

Checking that the fetch was successful
--------------------------------------

A `fetch()` promise will reject with a `TypeError` when a network error is encountered or CORS is misconfigured on the server-side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful `fetch()` would include checking that the promise resolved, then checking that the `Response.ok` property has a value of true. The code would look something like this:

```js
async function fetchImage() {
  try {
    const response = await fetch("flowers.jpg");
    if (!response.ok) {
      throw new Error("Network response was not OK");
    }
    const myBlob = await response.blob();
    myImage.src = URL.createObjectURL(myBlob);
  } catch (error) {
    console.error("There has been a problem with your fetch operation:", error);
  }
}
```

Supplying your own request object
---------------------------------

Instead of passing a path to the resource you want to request into the `fetch()` call, you can create a request object using the `Request()` constructor, and pass that in as a `fetch()` method argument:

```js
async function fetchImage(request) {
  try {
    const response = await fetch(request);
    if (!response.ok) {
      throw new Error("Network response was not OK");
    }
    const myBlob = await response.blob();
    myImage.src = URL.createObjectURL(myBlob);
  } catch (error) {
    console.error("Error:", error);
  }
}

const myHeaders = new Headers();

const myRequest = new Request("flowers.jpg", {
  method: "GET",
  headers: myHeaders,
  mode: "cors",
  cache: "default",
});

fetchImage(myRequest);
```

`Request()` accepts exactly the same parameters as the `fetch()` method. You can even pass in an existing request object to create a copy of it:

```js
const anotherRequest = new Request(myRequest, myInit);
```

 This is pretty useful, as request and response bodies can only be used once.
 Making a copy like this allows you to effectively use the request/response again while varying the `init` options if desired.
 The copy must be made before the body is read.

**Note:** There is also a `clone()` method that creates a copy. Both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.

Headers
-------

The `Headers` interface allows you to create your own headers object via the `Headers()` constructor. A headers object is a simple multi-map of names to values:

```js
const content = "Hello World";
const myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
```

The same can be achieved by passing an array of arrays or an object literal to the constructor:

```js
const myHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "ProcessThisImmediately",
});
```

The contents can be queried and retrieved:

```js
console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue");

console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.get("X-Custom-Header")); // ['ProcessThisImmediately', 'AnotherValue']

myHeaders.delete("X-Custom-Header");
console.log(myHeaders.get("X-Custom-Header")); // null
```

Some of these operations are only useful in `ServiceWorkers`, but they provide a much nicer API for manipulating headers.

All of the Headers methods throw a `TypeError` if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a `TypeError` if there is an immutable guard (see below). Otherwise, they fail silently. For example:

```js
const myResponse = Response.error();
try {
  myResponse.headers.set("Origin", "http://mybank.com");
} catch (e) {
  console.log("Cannot pretend to be a bank!");
}
```

A good use case for headers is checking whether the content type is correct before you process it further. For example:

```js
async function fetchJSON(request) {
  try {
    const response = await fetch(request);
    const contentType = response.headers.get("content-type");
    if (!contentType || !contentType.includes("application/json")) {
      throw new TypeError("Oops, we haven't got JSON!");
    }
    const jsonData = await response.json();
    // process your data further
  } catch (error) {
    console.error("Error:", error);
  }
}
```

### Guard

Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers' objects have a *guard* property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.

Possible guard values are:

* `none`: default.
* `request`: guard for a headers object obtained from a request (`Request.headers`).
* `request-no-cors`: guard for a headers object obtained from a request created with `Request.mode` `no-cors`.
* `response`: guard for a headers object obtained from a response (`Response.headers`).
* `immutable`: guard that renders a headers object read-only; mostly used for ServiceWorkers.

**Note:** You may not append or set the `Content-Length` header on a guarded headers object for a `response`. Similarly, inserting `Set-Cookie` into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.

Response objects
----------------

As you have seen above, `Response` instances are returned when `fetch()` promises are resolved.

The most common response properties you'll use are:

* `Response.status` — An integer (default value 200) containing the response status code.
* `Response.statusText` — A string (default value ""), which corresponds to the HTTP status code message. Note that HTTP/2 does not support status messages.
* `Response.ok` — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a boolean value.

They can also be created programmatically via JavaScript, but this is only really useful in `ServiceWorkers`, when you are providing a custom response to a received request using a `respondWith()` method:

```js
const myBody = new Blob();

addEventListener("fetch", (event) => {
  // ServiceWorker intercepting a fetch
  event.respondWith(
    new Response(myBody, {
      headers: { "Content-Type": "text/plain" },
    }),
  );
});
```

The `Response()` constructor takes two optional arguments — a body for the response, and an init object (similar to the one that `Request()` accepts.)

**Note:** The static method `error()` returns an error response. Similarly, `redirect()` returns a response resulting in a redirect to a specified URL. These are also only relevant to Service Workers.

Body
----

Both requests and responses may contain body data. A body is an instance of any of the following types:

* `ArrayBuffer`
* `TypedArray` (Uint8Array and friends)
* `DataView`
* `Blob`
* `File`
* `String`, or a string literal
* `URLSearchParams`
* `FormData`

The `Request` and `Response` interfaces share the following methods to extract a body. These all return a promise that is eventually resolved with the actual content.

* `Request.arrayBuffer()` / `Response.arrayBuffer()`
* `Request.blob()` / `Response.blob()`
* `Request.formData()` / `Response.formData()`
* `Request.json()` / `Response.json()`
* `Request.text()` / `Response.text()`

This makes usage of non-textual data much easier than it was with XHR.

Request bodies can be set by passing body parameters:

```js
const form = new FormData(document.getElementById("login-form"));
fetch("/login", {
  method: "POST",
  body: form,
});
```

Both request and response (and by extension the `fetch()` function), will try to intelligently determine the content type. A request will also automatically set a `Content-Type` header if none is set in the `options` parameter.

Feature detection
-----------------

Fetch API support can be detected by checking for the existence of `Headers`, `Request`, `Response` or `fetch()` on the `Window` or `Worker` scope. For example:

```js
if (window.fetch) {
  // run my fetch request here
} else {
  // do something with XMLHttpRequest?
}
```

Differences from `jQuery.ajax()`
--------------------------------

The `fetch` specification differs from `jQuery.ajax()` in the following significant ways:

* The promise returned from `fetch()` won't reject on HTTP errors even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the promise will resolve (with the `ok` property of the response set to `false` if the response isn't in the range 200–299). The promise will only reject on network failure or if anything prevented the request from completing.
* Unless `fetch()` is called with the `credentials` option set to `include`, `fetch()`:
    + won't send cookies in cross-origin requests
    + won't set any cookies sent back in cross-origin responses
    + As of August 2018, the default credentials policy changed to same-origin.
See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
* Fetch polyfill
* Fetch examples on GitHub


Fetch basic concepts - Web APIs

Fetch basic concepts
====================

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used `XMLHttpRequest`, but it provides a more powerful and flexible feature set. This article explains some of the basic concepts of the Fetch API.

**Note:** This article will be added to over time. If you find a Fetch concept that you feel needs explaining better, let someone know on the MDN Web Docs chat rooms.

In a nutshell
-------------

At the heart of Fetch are the Interface abstractions of HTTP `Request`s, `Response`s, and `Headers`, along with a `fetch()` method for initiating asynchronous resource requests. Because the main components of HTTP are abstracted as JavaScript objects, it is easy for other APIs to make use of such functionality.

Service Workers is an example of an API that makes heavy use of Fetch.

Fetch takes the asynchronous nature of such requests one step further. The API is completely `Promise`-based.

Guard
-----

Guard is a feature of `Headers` objects, with possible values of `immutable`, `request`, `request-no-cors`, `response`, or `none`, depending on where the header is used.

When a new `Headers` object is created using the `Headers()` constructor, its guard is set to `none` (the default). When a `Request` or `Response` object is created, it has an associated `Headers` object whose guard is set as summarized below:

| new object's type | creating constructor | guard setting of associated `Headers` object |
| --- | --- | --- |
| `Request` | `Request()` | `request` |
| `Request()` with
 `mode` of `no-cors` | `request-no-cors` |
| `Response` | `Response()` | `response` |
| `Response.error()` or
 `Response.redirect()` methods
  | `immutable` |

A header's guard affects the `set()`, `delete()`, and `append()` methods which change the header's contents. A `TypeError` is thrown if you try to modify a `Headers` object whose guard is `immutable`. However, the operation will work if

* guard is `request` and the header *name* isn't a forbidden header name .
* guard is `request-no-cors` and the header *name*/*value* is a simple header .
* guard is `response` and the header *name* isn't a forbidden response header name .


XRAnchor: anchorSpace property - Web APIs

XRAnchor: anchorSpace property
==============================

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

The read-only **`anchorSpace`** property of the `XRAnchor` interface returns an `XRSpace` object to locate the anchor relative to other `XRSpace` objects. It can be passed to `XRFrame.getPose()` subsequently.

Value
-----

An `XRSpace` object.

Examples
--------

### Updating anchors

```js
for (const anchor of frame.trackedAnchors) {
  const pose = frame.getPose(anchor.anchorSpace, referenceSpace);
}
```

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

| Specification |
| --- |
| WebXR Anchors Module # dom-xranchor-anchorspace |

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

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


XRAnchor: delete() method - Web APIs

XRAnchor: delete() method
=========================

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

The **`delete()`** method of the `XRAnchor` interface removes an anchor. This can be useful when an application is no longer interested in receiving updates to an anchor.

Syntax
------

```js
delete()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Removing all anchors

```js
let anchorsCollection = new Set();

// Upon creating anchors, add them to the Set
// anchorsCollection.add(anchor);

for (const anchor of anchorsCollection) {
  anchor.delete();
}

anchorsCollection.clear();
```

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

| Specification |
| --- |
| WebXR Anchors Module # dom-xranchor-delete |

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

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


GravitySensor: GravitySensor() constructor - Web APIs

GravitySensor: GravitySensor() constructor
==========================================

 The **`GravitySensor()`**
 constructor creates a new `GravitySensor` object which
 provides on each reading the gravity applied to the device along all three axes.

Syntax
------

```js
new GravitySensor()
new GravitySensor(options)
```

### Parameters

`options` Optional

Options are as follows:

`frequency`

 The desired number of times per second a sample should
 be taken, meaning the number of times per second that the
 `reading` event will be called. A whole number or decimal may be
 used, the latter for frequencies less than a second. The actual reading frequency
 depends on device hardware and consequently may be less than requested. The default
 frequency is the one defined by the underlying platform.

`referenceFrame`

 The local coordinate system representing
 the reference frame. It can be either `'device'` or
 `'screen'`. The default is `'device'`.

### Exceptions

`SecurityError` `DOMException`

Use of this feature was blocked by a Permissions Policy.

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

| Specification |
| --- |
| Accelerometer # dom-gravitysensor-gravitysensor |

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

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

See also
--------

* `reading` event


CSSFontFaceRule: style property - Web APIs

CSSFontFaceRule: style property
===============================

The read-only **`style`** property of the `CSSFontFaceRule` interface returns the style information from the `@font-face` at-rule. This will be in the form of a `CSSStyleDeclaration` object.

Value
-----

A `CSSStyleDeclaration`.

Examples
--------

This example uses the CSS found as an example on the `@font-face` page. The first `CSSRule` returned will be a `CSSFontFaceRule`. The `style` property returns a `CSSStyleDeclaration` with the properties `fontFamily`, `fontWeight`, and `src` populated with the information from the rule.

```css
@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"),
    url(MgOpenModernaBold.ttf);
  font-weight: bold;
}
```

```js
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0].style); //a CSSStyleDeclaration
```

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

| Specification |
| --- |
| CSS Fonts Module Level 4 # dom-cssfontfacerule-style |

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

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


FontFace: display property - Web APIs

FontFace: display property
==========================

 The **`display`** property of the `FontFace` interface determines how a font face is displayed based on whether and when it is downloaded and ready to use.
 This property is equivalent to the CSS `font-display` descriptor.

 When this property is used, font loading has a timeline with three periods.
 The lengths of the first two periods depend on the value of the property and the user agent.
 (See below.)

block period

The browser invisibly prepares a fallback font. If the font face loads during this time, it's used to display the text and display is complete.

swap period

 If the font face is still not loaded, the fallback font will be shown.
 When the font face loads, the fallback will be swapped for the downloaded font.

failure period

If the font face still is not loaded, the fallback font will be shown and no swap will occur.

Value
-----

A string with one of the following values.

`auto`

Use the font display strategy provided by the user agent.

`block`

 Gives the font face a short block period and an infinite swap period.
 The spec recommends 3 seconds for the block period, though this may vary from browser to browser.

`fallback`

 Gives the font face a short block period and a short swap period.
 The spec recommends 100 ms or less for the block period and 3 seconds for the swap period, though these values may vary from browser to browser.

`optional`

 Gives the font face a short block period and no swap period.
 The spec recommends 100 ms or less, though this may vary from browser to browser.

`swap`

Gives the font face a 0 second block period and an infinite swap period.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-display |

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

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


FontFace: load() method - Web APIs

FontFace: load() method
=======================

The **`load()`** method of the `FontFace` interface requests and loads a font whose `source` was specified as a URL. It returns a `Promise` that resolves with the current `FontFace` object.

If the `source` for the font face was specified as binary data, or the font `status` property of the font face is anything other than `unloaded`, then this method does nothing.

Syntax
------

```js
load()
```

### Parameters

None.

### Return value

A `Promise` that resolves with a reference to the current `FontFace` object when the font loads or rejects with a `NetworkError` `DOMException` if the loading process fails.

### Exceptions

`NetworkError` `DOMException`

Indicates that the attempt to load the font failed.

Examples
--------

This simple example loads a font and uses it to display some text in a canvas element (with an id of `js-canvas`).
```

<canvas id="js-canvas"></canvas>
```

```js
const canvas = document.getElementById("js-canvas");

// load the "Bitter" font from Google Fonts
const fontFile = new FontFace(
  "FontFamily Style Bitter",
  "url(https://fonts.gstatic.com/s/bitter/v7/HEpP8tJXlWaYHimsnXgfCOvvDin1pK8aKteLpeZ5c0A.woff2)",
);
document.fonts.add(fontFile);

fontFile.load().then(
  () => {
    // font loaded successfully!
    canvas.width = 650;
    canvas.height = 100;
    const ctx = canvas.getContext("2d");

    ctx.font = '36px "FontFamily Style Bitter"';
    ctx.fillText("Bitter font loaded", 20, 50);
  },
  (err) => {
    console.error(err);
  },
);
```

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # font-face-load |

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

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


FontFace: loaded property - Web APIs

FontFace: loaded property
=========================

The **`loaded`** read-only property of the `FontFace` interface returns a `Promise` that resolves with the current `FontFace` object when the font specified in the object's constructor is done loading or rejects with a `SyntaxError`.

Value
-----

A `Promise` that resolves with the current `FontFace` object.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-loaded |

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

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


FontFace: style property - Web APIs

FontFace: style property
========================

The **`style`** property of the `FontFace` interface retrieves or sets the font's style.

This property is equivalent to the `font-style` descriptor.

Value
-----

A string containing the descriptors defined in the style sheet's `@font-face` rule.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-style |

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

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


FontFace: featureSettings property - Web APIs

FontFace: featureSettings property
==================================

The **`featureSettings`** property of the `FontFace` interface retrieves or sets infrequently used font features that are not available from a font's variant properties.

This property is equivalent to the `font-feature-settings` descriptor.

Value
-----

A string containing a descriptor.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-featuresettings |

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

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


FontFace: stretch property - Web APIs

FontFace: stretch property
==========================

The **`stretch`** property of the `FontFace` interface retrieves or sets how the font stretches.

This property is equivalent to the `font-stretch` descriptor.

Value
-----

A string containing a descriptor as it would be defined in a style sheet's `@font-face` rule.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-stretch |

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

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


FontFace: FontFace() constructor - Web APIs

FontFace: FontFace() constructor
================================

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

Syntax
------

```js
new FontFace(family, source)
new FontFace(family, source, descriptors)
```

### Parameters

`family`

Specifies a font family name that can be used to match against this font face when styling elements.

 Takes the same type of values as the `font-family` descriptor of `@font-face`.
 This value may also be read and set using the `FontFace.family` property.

`source`

 The font source.
 This can be either:

* A URL to a font face file.
* Binary font face data in an `ArrayBuffer` or a `TypedArray`.

`descriptors` Optional

 A set of optional descriptors passed as an object.
 It can contain any of the descriptors available for `@font-face`:

`ascentOverride`

With an allowable value for `@font-face/ascent-override`.

`descentOverride`

With an allowable value for `@font-face/descent-override`.

`display`

With an allowable value for `@font-face/font-display`.

`featureSettings`

With an allowable value for `font-feature-settings`.

`lineGapOverride`

With an allowable value for `@font-face/line-gap-override`.

`stretch`

With an allowable value for `@font-face/font-stretch`.

`style`

With an allowable value for `@font-face/font-style`.

`unicodeRange`

With an allowable value for `@font-face/unicode-range`.

`variationSettings`

With an allowable value for `@font-face/font-variation-settings`.

`weight`

With an allowable value for `@font-face/font-weight`.

### Exceptions

`SyntaxError` `DOMException`

 Thrown when a descriptor string does not match the grammar of the corresponding `@font-face` descriptor, or the specified binary source cannot be loaded.
 This error results in `FontFace.status` being set to `error`.

Examples
--------

```js
async function loadFonts() {
  const font = new FontFace("myfont", "url(myfont.woff)", {
    style: "normal",
    weight: "400",
    stretch: "condensed",
  });
  // wait for font to be loaded
  await font.load();
  // add font to document
  document.fonts.add(font);
  // enable font with CSS class
  document.body.classList.add("fonts-loaded");
}
```

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # font-face-constructor |

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

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

See also
--------

* `@font-face`


FontFace: family property - Web APIs

FontFace: family property
=========================

The **`FontFace.family`** property allows the author to get or set the font family of a `FontFace` object.

 The value is used for name matching against a particular font face when styling elements using the `font-family` property.
 Any name may be used, and this overrides any name specified in the underlying font data.

This property is equivalent to the `font-family` descriptor of `@font-face`.

Value
-----

A string.

Examples
--------

```js
let fontFace = new FontFace(
  "Roboto",
  "url(https://fonts.example.com/roboto.woff2)",
);
console.log(fontFace.family); // 'Roboto'

fontFace.family = "newRoboto";
console.log(fontFace.family); // 'newRoboto'
```

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-family |

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

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


FontFace: lineGapOverride property - Web APIs

FontFace: lineGapOverride property
==================================

 The **`lineGapOverride`** property of the `FontFace` interface returns and sets the value of the `@font-face/line-gap-override` descriptor.
 The possible values are `normal`, indicating that the metric used should be obtained from the font file, or a percentage.

Value
-----

A string.

Examples
--------

```js
let fontFace = new FontFace(
  "Roboto",
  "url(https://fonts.example.com/roboto.woff2)",
  { lineGapOverride: "90%" },
);
console.log(fontFace.lineGapOverride); // 90%
fontFace.lineGapOverride = "normal";
console.log(fontFace.lineGapOverride); // 'normal'
```

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontfacedescriptors-linegapoverride |

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

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


FontFace: variationSettings property - Web APIs

FontFace: variationSettings property
====================================

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

The **`variationSettings`** property of the `FontFace` interface retrieves or sets low-level OpenType or TrueType font variations.

This property is equivalent to the `font-variation-settings` descriptor.

Value
-----

A string containing a descriptor.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontfacedescriptors-variationsettings |

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

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


FontFace: status property - Web APIs

FontFace: status property
=========================

The **`status`** read-only property of the `FontFace` interface returns an enumerated value indicating the status of the font, one of `"unloaded"`, `"loading"`, `"loaded"`, or `"error"`.

Value
-----

One of `"unloaded"`, `"loading"`, `"loaded"`, or `"error"`.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-status |

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

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


FontFace: descentOverride property - Web APIs

FontFace: descentOverride property
==================================

 The **`descentOverride`** property of the `FontFace` interface returns and sets the value of the `@font-face/descent-override` descriptor.
 The possible values are `normal`, indicating that the metric used should be obtained from the font file, or a percentage.

Value
-----

A string.

Examples
--------

```js
let fontFace = new FontFace(
  "Roboto",
  "url(https://fonts.example.com/roboto.woff2)",
  { descentOverride: "90%" },
);
console.log(fontFace.descentOverride); // 90%
fontFace.descentOverride = "normal";
console.log(fontFace.descentOverride); // 'normal'
```

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontfacedescriptors-descentoverride |

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

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


FontFace: weight property - Web APIs

FontFace: weight property
=========================

The **`weight`** property of the `FontFace` interface retrieves or sets the weight of the font.

This property is equivalent to the `font-weight` descriptor.

Value
-----

A string containing a descriptor as it would be defined in a style sheet's `@font-face` rule.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-weight |

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

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


FontFace: unicodeRange property - Web APIs

FontFace: unicodeRange property
===============================

The **`unicodeRange`** property of the `FontFace` interface retrieves or sets the range of unicode code points encompassing the font.

This property is equivalent to the `unicode-range` descriptor.

Value
-----

A string containing a descriptor as it would appear in a style sheet's `@font-face` rule.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-unicoderange |

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

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


FontFace: variant property - Web APIs

FontFace: variant property
==========================

 The **`variant`** property of the
 `FontFace` interface programmatically retrieves or sets font variant
 values.

Value
-----

 A string containing a descriptor as it would be defined in a style
 sheet's `@font-face` rule.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontface-variant |

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

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


FontFace: ascentOverride property - Web APIs

FontFace: ascentOverride property
=================================

The **`ascentOverride`** property of the `FontFace` interface returns and sets the ascent metric for the font, the height above the baseline that CSS uses to lay out line boxes in an inline formatting context.

This property is equivalent to the `@font-face/ascent-override` descriptor of `@font-face`.

Value
-----

A string. The possible values are `normal`, indicating that the metric used should be obtained from the font file, or a percentage.

This property accepts the same values as the `@font-face/ascent-override` descriptor.

Examples
--------

```js
let fontFace = new FontFace(
  "Roboto",
  "url(https://fonts.example.com/roboto.woff2)",
  { ascentOverride: "90%" },
);
console.log(fontFace.ascentOverride); // 90%
fontFace.ascentOverride = "normal";
console.log(fontFace.ascentOverride); // 'normal'
```

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # dom-fontfacedescriptors-ascentoverride |

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

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


Window: load event - Web APIs

Window: load event
==================

 The **`load`** event is fired when the whole page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images.
 This is in contrast to `DOMContentLoaded`, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

This event is not cancelable and does not bubble.

**Note:** *All events named `load` will not propagate to `Window`*, even with `bubbles` initialized to `true`. To catch `load` events on the `window`, that `load` event must be dispatched directly to the `window`.

**Note:** The `load` event that is dispatched when the main document has loaded *is* dispatched on the `window`, but has two mutated properties: `target` is `document`, and `path` is `undefined`. These two properties are mutated due to legacy conformance.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

Log a message when the page is fully loaded:

```js
window.addEventListener("load", (event) => {
  console.log("page is fully loaded");
});
```

The same, but using the `onload` event handler property:

```js
window.onload = (event) => {
  console.log("page is fully loaded");
};
```

### Live example

#### HTML

```html
<div class="controls">
  <button id="reload" type="button">Reload</button>
</div>

<div class="event-log">
  <label for="eventLog">Event log:</label>
  <textarea
 readonly
 class="event-log-contents"
 rows="8"
 cols="30"
 id="eventLog"></textarea>
</div>
```

```
body {
  display: grid;
  grid-template-areas: "control log";
}

.controls {
  grid-area: control;
  display: flex;
  align-items: center;
  justify-content: center;
}

.event-log {
  grid-area: log;
}

.event-log-contents {
  resize: none;
}

label,
button {
  display: block;
}

#reload {
  height: 2rem;
}
```

#### JavaScript

```js
const log = document.querySelector(".event-log-contents");
const reload = document.querySelector("#reload");

reload.addEventListener("click", () => {
  log.textContent = "";
  setTimeout(() => {
    window.location.reload(true);
  }, 200);
});

window.addEventListener("load", (event) => {
  log.textContent += "load\n";
});

document.addEventListener("readystatechange", (event) => {
  log.textContent += `readystate: ${document.readyState}\n`;
});

document.addEventListener("DOMContentLoaded", (event) => {
  log.textContent += `DOMContentLoaded\n`;
});
```

#### Result

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

| Specification |
| --- |
| UI Events # event-type-load |
| HTML Standard # delay-the-load-event |

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

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

See also
--------

* Document readyState API
* Related events:
    + `DOMContentLoaded`
    + `readystatechange`
    + `beforeunload`
    + `unload`


Window: location property - Web APIs

Window: location property
=========================

The **`Window.location`** read-only property returns a `Location` object with information about the current location of the document.

 Though `Window.location` is a *read-only* `Location` object, you can also assign a string to it.
 This means that you can work with `location` as if it were a string in most cases:
 `location = 'http://www.example.com'` is a synonym of `location.href = 'http://www.example.com'`.

See `Location` for all available properties.

Value
-----

A `Location` object.

Examples
--------

### Basic Example

```js
alert(location); // alerts "https://developer.mozilla.org/en-US/docs/Web/API/Window/location"
```

### Example 1: Navigate to a new page

Whenever a new value is assigned to the location object, a document will be loaded using the URL as if `location.assign()` had been called with the modified URL.

Note that navigation-related sandbox flags may result in an exception being thrown and the navigation failing.

```js
location.assign("https://www.mozilla.org"); // or
location = "https://www.mozilla.org";
```

### Example 2: Reloading the current page

```js
location.reload();
```

### Example 3

Consider the following example, which will reload the page by using the `replace()` method to insert the value of `location.pathname` into the hash:

```js
function reloadPageWithHash() {
  location.replace(`https://example.com/#${location.pathname}`);
}
```

### Example 4: Display the properties of the current URL in an alert dialog

```js
function showLoc() {
  const logLines = [
    "Property (Typeof): Value",
    `location (${typeof location}): ${location}`,
  ];
  for (const prop in location) {
    logLines.push(
      `${prop} (${typeof location[prop]}): ${location[prop] || "n/a"}`,
    );
  }
  alert(logLines.join("\n"));
}

// in html: <button onclick="showLoc();">Show location properties</button>
```

### Example 5: Send a string of data to the server by modifying the `search` property

```js
function sendData(data) {
  location.search = data;
}

// in html: <button onclick="sendData('Some data');">Send data</button>
```

The current URL with "?Some%20data" appended is sent to the server (if no action is taken by the server, the current document is reloaded with the modified search string).

### Example 6: Using bookmarks without changing the `hash` property

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>MDN Example</title>
    <script>
 function showNode(node) {
 document.documentElement.scrollTop = node.offsetTop;
 document.documentElement.scrollLeft = node.offsetLeft;
 }

 function showBookmark(bookmark, useHash) {
 if (arguments.length === 1 || useHash) {
 location.hash = bookmark;
 return;
 }
 const bookmarkElement = document.querySelector(bookmark);
 if (bookmarkElement) {
 showNode(bookmarkElement);
 }
 }
 </script>
    <style>
 span.intLink {
 cursor: pointer;
 color: #0000ff;
 text-decoration: underline;
 }
 </style>
  </head>

  <body>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices
      dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus
      auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in
      placerat est. Pellentesque habitant morbi tristique senectus et netus et
      malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor.
      Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris
      vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla
      consectetur aliquam purus. Curabitur convallis, justo posuere porta
      egestas, velit erat ornare tortor, non viverra justo diam eget arcu.
      Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit
      a hendrerit vitae, volutpat non ipsum.
    </p>
    <p>
      Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero,
      eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt
      rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida
      nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat.
      Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit.
      Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non
      felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et
      fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla
      mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent
      bibendum condimentum feugiat.
    </p>
    <p id="myBookmark1">
      [ <span class="intLink" onclick="showBookmark('#myBookmark2');"
 >Go to bookmark #2</span
 > ]
    </p>
    <p>
      Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin
      ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros
      convallis ut mollis magna pellentesque. Pellentesque placerat enim at
      lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt
      tincidunt. Nulla vitae tempor nisl. Etiam congue, elit vitae egestas
      mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus.
    </p>
    <p>
      Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc,
      vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis.
      Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem
      ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc.
      Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem
      ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu
      sem vehicula egestas.
    </p>
    <p>
      Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus
      sit amet lectus vitae eros egestas pellentesque fermentum eget magna.
      Quisque mauris nisl, gravida vitae placerat et, condimentum id metus.
      Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae
      sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales
      quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in
      mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis.
      Pellentesque habitant morbi tristique senectus et netus et malesuada fames
      ac turpis egestas.
    </p>
    <p>
      Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem
      ipsum dolor sit amet, consectetur adipiscing elit. Proin non lectus eu
      turpis vulputate cursus. Mauris interdum tincidunt erat id pharetra.
      Nullam in libero elit, sed consequat lectus. Morbi odio nisi, porta vitae
      molestie ut, gravida ut nunc. Ut non est dui, id ullamcorper orci.
      Praesent vel elementum felis. Maecenas ornare, dui quis auctor hendrerit,
      turpis sem ullamcorper odio, in auctor magna metus quis leo. Morbi at odio
      ante.
    </p>
    <p>
      Curabitur est ipsum, porta ac viverra faucibus, eleifend sed eros. In sit
      amet vehicula tortor. Vestibulum viverra pellentesque erat a elementum.
      Integer commodo ultricies lorem, eget tincidunt risus viverra et. In enim
      turpis, porttitor ac ornare et, suscipit sit amet nisl. Vestibulum ante
      ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
      Pellentesque vel ultrices nibh. Sed commodo aliquam aliquam. Nulla
      euismod, odio ut eleifend mollis, nisi dui gravida nibh, vitae laoreet
      turpis purus id ipsum. Donec convallis, velit non scelerisque bibendum,
      diam nulla auctor nunc, vel dictum risus ipsum sit amet est. Praesent ut
      nibh sit amet nibh congue pulvinar. Suspendisse dictum porttitor tempor.
    </p>
    <p>
      Vestibulum dignissim erat vitae lectus auctor ac bibendum eros semper.
      Integer aliquet, leo non ornare faucibus, risus arcu tristique dolor, a
      aliquet massa mauris quis arcu. In porttitor, lectus ac semper egestas,
      ligula magna laoreet libero, eu commodo mauris odio id ante. In hac
      habitasse platea dictumst. In pretium erat diam, nec consequat eros.
      Praesent augue mi, consequat sed porttitor at, volutpat vitae eros. Sed
      pretium pharetra dapibus. Donec auctor interdum erat, lacinia molestie
      nibh commodo ut. Maecenas vestibulum vulputate felis, ut ullamcorper arcu
      faucibus in. Curabitur id arcu est. In semper mollis lorem at
      pellentesque. Sed lectus nisl, vestibulum id scelerisque eu, feugiat et
      tortor. Pellentesque porttitor facilisis ultricies.
    </p>
    <p id="myBookmark2">
      [ <span class="intLink" onclick="showBookmark('#myBookmark1');"
 >Go to bookmark #1</span
 >
      |
      <span class="intLink" onclick="showBookmark('#myBookmark1', false);"
 >Go to bookmark #1 without using location.hash</span
 >
      |
      <span class="intLink" onclick="showBookmark('#myBookmark3');"
 >Go to bookmark #3</span
 > ]
    </p>
    <p>
      Phasellus tempus fringilla nunc, eget sagittis orci molestie vel. Nulla
      sollicitudin diam non quam iaculis ac porta justo venenatis. Quisque
      tellus urna, molestie vitae egestas sit amet, suscipit sed sem. Quisque
      nec lorem eu velit faucibus tristique ut ut dolor. Cras eu tortor ut
      libero placerat venenatis ut ut massa. Sed quis libero augue, et consequat
      libero. Morbi rutrum augue sed turpis elementum sed luctus nisl molestie.
      Aenean vitae purus risus, a semper nisl. Pellentesque malesuada, est id
      sagittis consequat, libero mauris tincidunt tellus, eu sagittis arcu purus
      rutrum eros. Quisque eget eleifend mi. Duis pharetra mi ac eros mattis
      lacinia rutrum ipsum varius.
    </p>
    <p>
      Fusce cursus pulvinar aliquam. Duis justo enim, ornare vitae elementum
      sed, porta a quam. Aliquam eu enim eu libero mollis tempus. Morbi ornare
      aliquam posuere. Proin faucibus luctus libero, sed ultrices lorem sagittis
      et. Vestibulum malesuada, ante nec molestie vehicula, quam diam mollis
      ipsum, rhoncus posuere mauris lectus in eros. Nullam feugiat ultrices
      augue, ac sodales sem mollis in.
    </p>
    <p id="myBookmark3"><em>Here is the bookmark #3</em></p>
    <p>
      Proin vitae sem non lorem pellentesque molestie. Nam tempus massa et
      turpis placerat sit amet sollicitudin orci sodales. Pellentesque enim
      enim, sagittis a lobortis ut, tempus sed arcu. Aliquam augue turpis,
      varius vel bibendum ut, aliquam at diam. Nam lobortis, dui eu hendrerit
      pellentesque, sem neque porttitor erat, non dapibus velit lectus in metus.
      Vestibulum sit amet felis enim. In quis est vitae nunc malesuada consequat
      nec nec sapien. Suspendisse aliquam massa placerat dui lacinia luctus sed
      vitae risus. Fusce tempus, neque id ultrices volutpat, mi urna auctor
      arcu, viverra semper libero sem vel enim. Mauris dictum, elit non placerat
      malesuada, libero elit euismod nibh, nec posuere massa arcu eu risus.
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna
      velit, dapibus eget varius feugiat, pellentesque sit amet ligula. Maecenas
      nulla nisl, facilisis eu egestas scelerisque, mollis eget metus.
      Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere
      cubilia Curae; Morbi sed congue mi.
    </p>
    <p>
      Fusce metus velit, pharetra at vestibulum nec, facilisis porttitor mi.
      Curabitur ligula sapien, fermentum vel porttitor id, rutrum sit amet
      magna. Sed sit amet sollicitudin turpis. Aenean luctus rhoncus dolor, et
      pulvinar ante egestas et. Donec ac massa orci, quis dapibus augue. Vivamus
      consectetur auctor pellentesque. Praesent vestibulum tincidunt ante sed
      consectetur. Cum sociis natoque penatibus et magnis dis parturient montes,
      nascetur ridiculus mus. Fusce purus metus, imperdiet vitae iaculis
      convallis, bibendum vitae turpis.
    </p>
    <p>
      Fusce aliquet molestie dolor, in ornare dui sodales nec. In molestie
      sollicitudin felis a porta. Mauris nec orci sit amet orci blandit
      tristique congue nec nunc. Praesent et tellus sollicitudin mauris accumsan
      fringilla. Morbi sodales, justo eu sollicitudin lacinia, lectus sapien
      ullamcorper eros, quis molestie urna elit bibendum risus. Proin eget
      tincidunt quam. Nam luctus commodo mauris, eu posuere nunc luctus non.
      Nulla facilisi. Vivamus eget leo rhoncus quam accumsan fringilla. Aliquam
      sit amet lorem est. Nullam vel tellus nibh, id imperdiet orci. Integer
      egestas leo eu turpis blandit scelerisque.
    </p>
    <p>
      Etiam in blandit tellus. Integer sed varius quam. Vestibulum dapibus mi
      gravida arcu viverra blandit. Praesent tristique augue id sem adipiscing
      pellentesque. Sed sollicitudin, leo sed interdum elementum, nisi ante
      condimentum leo, eget ornare libero diam semper quam. Vivamus augue urna,
      porta eget ultrices et, dapibus ut ligula. Ut laoreet consequat faucibus.
      Praesent at lectus ut lectus malesuada mollis. Nam interdum adipiscing
      eros, nec sodales mi porta nec. Proin et quam vitae sem interdum aliquet.
      Proin vel odio at lacus vehicula aliquet.
    </p>
    <p>
      Etiam placerat dui ut sem ornare vel vestibulum augue mattis. Sed semper
      malesuada mi, eu bibendum lacus lobortis nec. Etiam fringilla elementum
      risus, eget consequat urna laoreet nec. Etiam mollis quam non sem
      convallis vel consectetur lectus ullamcorper. Aenean mattis lacus quis
      ligula mattis eget vestibulum diam hendrerit. In non placerat mauris.
      Praesent faucibus nunc quis eros sagittis viverra. In hac habitasse platea
      dictumst. Suspendisse eget nisl erat, ac molestie massa. Praesent mollis
      vestibulum tincidunt. Fusce suscipit laoreet malesuada. Aliquam erat
      volutpat. Aliquam dictum elementum rhoncus. Praesent in est massa,
      pulvinar sodales nunc. Pellentesque gravida euismod mi ac convallis.
    </p>
    <p>
      Mauris vel odio vel nulla facilisis lacinia. Aliquam ultrices est at leo
      blandit tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et
      ultrices posuere cubilia Curae; Suspendisse porttitor adipiscing
      facilisis. Duis cursus quam iaculis augue interdum porttitor. Vestibulum
      ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
      Curae; Duis vulputate magna ac metus pretium condimentum. In tempus, est
      eget vestibulum blandit, velit massa dignissim nisl, ut scelerisque lorem
      neque vel velit. Maecenas fermentum commodo viverra. Curabitur a nibh non
      velit aliquam cursus. Integer semper condimentum tortor a pellentesque.
      Pellentesque semper, nisl id porttitor vehicula, sem dui feugiat lacus,
      vitae consequat augue urna vel odio.
    </p>
    <p>
      Vestibulum id neque nec turpis iaculis pulvinar et a massa. Vestibulum sed
      nibh vitae arcu eleifend egestas. Mauris fermentum ultrices blandit.
      Suspendisse vitae lorem libero. Aenean et pellentesque tellus. Morbi quis
      neque orci, eu dignissim dui. Fusce sollicitudin mauris ac arcu vestibulum
      imperdiet. Proin ultricies nisl sit amet enim imperdiet eu ornare dui
      tempus. Maecenas lobortis nisi a tortor vestibulum vel eleifend tellus
      vestibulum. Donec metus sapien, hendrerit a fermentum id, dictum quis
      libero.
    </p>
    <p>
      Pellentesque a lorem nulla, in tempor justo. Duis odio nisl, dignissim sed
      consequat sit amet, hendrerit ac neque. Nunc ac augue nec massa tempor
      rhoncus. Nam feugiat, tellus a varius euismod, justo nisl faucibus velit,
      ut vulputate justo massa eu nibh. Sed bibendum urna quis magna facilisis
      in accumsan dolor malesuada. Morbi sit amet nunc risus, in faucibus sem.
      Nullam sollicitudin magna sed sem mollis id commodo libero condimentum.
      Duis eu massa et lacus semper molestie ut adipiscing sem.
    </p>
    <p>
      Sed id nulla mi, eget suscipit eros. Aliquam tempus molestie rutrum. In
      quis varius elit. Nullam dignissim neque nec velit vulputate porttitor.
      Mauris ac ligula sit amet elit fermentum rhoncus. In tellus urna, pulvinar
      quis condimentum ut, porta nec justo. In hac habitasse platea dictumst.
      Proin volutpat elit id quam molestie ac commodo lacus sagittis. Quisque
      placerat, augue tempor placerat pulvinar, nisi nisi venenatis urna, eget
      convallis eros velit quis magna. Suspendisse volutpat iaculis quam, ut
      tristique lacus luctus quis.
    </p>
    <p>
      Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed
      facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu
      sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum
      aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices
      tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc
      fringilla eget. Praesent scelerisque urna vitae nibh tristique varius
      consequat neque luctus. Integer ornare, erat a porta tempus, velit justo
      fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel
      dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar
      laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque
      sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales
      eleifend interdum.
    </p>
  </body>
</html>
```

…the same thing but with an animated page scroll:

```js
const showBookmark = (() => {
  let _useHash;
  let _scrollX;
  let _scrollY;
  let _nodeX;
  let _nodeY;
  let _itFrame;
  let _scrollId = -1;
  let _bookMark;

  // duration: the duration in milliseconds of each frame
  // frames: number of frames for each scroll
  let duration = 200;
  let frames = 10;

  function \_next() {
    if (_itFrame > frames) {
      clearInterval(_scrollId);
      _scrollId = -1;
      return;
    }
    _isBot = true;
    document.documentElement.scrollTop = Math.round(
      _scrollY + ((_nodeY - _scrollY) \* _itFrame) / frames,
    );
    document.documentElement.scrollLeft = Math.round(
      _scrollX + ((_nodeX - _scrollX) \* _itFrame) / frames,
    );
    if (_useHash && _itFrame === frames) {
      location.hash = _bookMark;
    }
    _itFrame++;
  }

  function \_chkOwner() {
    if (_isBot) {
      _isBot = false;
      return;
    }
    if (_scrollId > -1) {
      clearInterval(_scrollId);
      _scrollId = -1;
    }
  }

  window.addEventListener("scroll", _chkOwner, false);

  return (bookmark, useHash) => {
    const node = document.querySelector(bookmark);
    _scrollY = document.documentElement.scrollTop;
    _scrollX = document.documentElement.scrollLeft;
    _bookMark = bookmark;
    _useHash = useHash === true;
    _nodeX = node.offsetLeft;
    _nodeY = node.offsetTop;
    _itFrame = 1;
    if (_scrollId === -1) {
      _scrollId = setInterval(_next, Math.round(duration / frames));
    }
  };
})();
```

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

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

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

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

See also
--------

* The interface of the returned value, `Location`
* A similar information, but attached to the document,
 `Document.location`
* Manipulating the browser history
* `hashchange`


Window: resize event - Web APIs

Window: resize event
====================

The **`resize`** event fires when the document view (window) has been resized.

This event is not cancelable and does not bubble.

In some earlier browsers it was possible to register `resize` event handlers on any HTML element. It is still possible to set `onresize` attributes or use `addEventListener()` to set a handler on any element. However, `resize` events are only fired on the `window` object (i.e. returned by `document.defaultView`). Only handlers registered on the `window` object will receive `resize` events.

While the `resize` event fires only for the window nowadays, you can get resize notifications for other elements using the ResizeObserver API.

If the resize event is triggered too many times for your application, see Optimizing window.onresize to control the time after which the event fires.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### Window size logger

The following example reports the window size each time it is resized.

#### HTML

```html
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
```

#### JavaScript

```js
const heightOutput = document.querySelector("#height");
const widthOutput = document.querySelector("#width");

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;
```

#### Result

**Note:** The example output here is in an `<iframe>`, so the reported width and height values are for the `<iframe>`, not the window that this page is in. In particular, it will be hard to adjust the window size so as to see a difference in the reported height.

The effect is easier to see if you view the example in its own window.

### addEventListener equivalent

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

```js
window.addEventListener("resize", reportWindowSize);
```

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

| Specification |
| --- |
| CSSOM View Module # eventdef-window-resize |

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

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


Window: getSelection() method - Web APIs

Window: getSelection() method
=============================

 The **`Window.getSelection()`** method returns a
 `Selection` object representing the range of text selected by the user or
 the current position of the caret.

Syntax
------

```js
getSelection()
```

### Parameters

None.

### Return value

A `Selection` object.

 When cast to string, either by appending an empty string (`""`) or using
 `Selection.toString()`, this object returns the text selected.

 When called on an `<iframe>` that is not displayed (e.g., where
 `display: none` is set) Firefox will return `null`, whereas other
 browsers will return a `Selection` object with
 `Selection.type` set to `None`.

Examples
--------

```js
function foo() {
  const selObj = window.getSelection();
  alert(selObj);
  const selRange = selObj.getRangeAt(0);
  // do stuff with the range
}
```

Notes
-----

### String representation of the Selection object

 In JavaScript, when an object is passed to a function expecting a string (like `window.alert()` or `document.write()`), the object's
 `toString()` method is called and the returned value is
 passed to the function. This can make the object appear to be a string when used with
 other functions when it is really an object with properties and methods.

 In the above example, `selObj.toString()` is automatically called when it is
 passed to `window.alert()`. However, attempting to use a JavaScript String property
 or method such as
 `length`
 or
 `substr`
 directly on a `Selection` object will result in an error if it does not
 have that property or method and may return unexpected results if it does. To use a
 `Selection` object as a string, call its `toString()` method
 directly:

```js
const selectedText = selObj.toString();
```

* `selObj` is a `Selection` object.
* `selectedText` is a string (Selected text).
### Related objects

 You can call `Document.getSelection()`, which works identically to
 `Window.getSelection()`.

 It is worth noting that currently `getSelection()` doesn't work on the
 content of `<textarea>` and `<input>` elements in Firefox
 and Edge (Legacy). `HTMLInputElement.setSelectionRange()`
 or the `selectionStart` and `selectionEnd` properties could be
 used to work around this.

 Notice also the difference between *selection* and *focus*.
 `Document.activeElement` returns the focused element.

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

| Specification |
| --- |
| Selection API # dom-window-getselection |

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

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

See also
--------

* Selection API
* `Selection`
* `Range`
* `Document.getSelection()`
* `HTMLInputElement.setSelectionRange()`


Window: cookieStore property - Web APIs

Window: cookieStore property
============================

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

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

The **`cookieStore`** read-only property of the `Window` interface returns a reference to the `CookieStore` object for the current document context. This is an entry point for the Cookie Store API.

Value
-----

A `CookieStore` object instance.

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

| Specification |
| --- |
| Cookie Store API # dom-window-cookiestore |

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

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


Window: alert() method - Web APIs

Window: alert() method
======================

`window.alert()` instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.

Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to dismiss the dialog.

Syntax
------

```js
alert()
alert(message)
```

### Parameters

`message` Optional

 A string you want to display in the alert dialog, or, alternatively, an object that
 is converted into a string and displayed.

### Return value

None (`undefined`).

Examples
--------

```js
window.alert("Hello world!");
alert("Hello world!");
```

Both produce:

![Black alert dialog box. At the top left small circle icon follow by white open and close square brackets containing this white text: JavaScript application. Below on the left, a Hello world! white text. And on the bottom right a small blue button. The button's text is: ok in black.](/en-US/docs/Web/API/Window/alert/alerthelloworld.png)

Notes
-----

 The alert dialog should be used for messages which do not require any response on the
 part of the user, other than the acknowledgement of the message.

 Dialog boxes are modal windows - they
 prevent the user from accessing the rest of the program's interface until the dialog box
 is closed. For this reason, you should not overuse any function that creates a dialog
 box (or modal window).

Alternatively `<dialog>` element can be used to display alerts.

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

| Specification |
| --- |
| HTML Standard # dom-alert-dev |

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

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

See also
--------

* `<dialog>` element
* `confirm`
* `prompt`


Window: statusbar property - Web APIs

Window: statusbar property
==========================

Returns the `statusbar` object.

This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible.

For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise.

Value
-----

An object containing a single property:

`visible` Read only

A boolean property, `false` if this `Window` is a popup, and `true` otherwise.

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

| Specification |
| --- |
| HTML Standard # dom-window-statusbar-dev |

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

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

See also
--------

* `window.locationbar`
* `window.menubar`
* `window.personalbar`
* `window.scrollbars`
* `window.toolbar`


Window: close() method - Web APIs

Window: close() method
======================

 The **`Window.close()`** method closes the current window, or
 the window on which it was called.

 This method can only be called on windows that were opened by a script using the
 `Window.open()` method, or on top-level windows that have a single history entry. If the window doesn't match these requirements, an error
 similar to this one appears in the console:
 `Scripts may not close windows that were not opened by script.`

 Note also that `close()` has no effect when called on `Window`
 objects returned by
 `HTMLIFrameElement.contentWindow`.

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Closing a window opened with `window.open()`

 This example shows a method which opens a window and a second one which closes the
 window; this demonstrates how to use `Window.close()` to close a window
 opened by calling `window.open()`.

```js
//Global variable to store a reference to the opened window
let openedWindow;

function openWindow() {
  openedWindow = window.open("moreinfo.htm");
}

function closeOpenedWindow() {
  openedWindow.close();
}
```

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

| Specification |
| --- |
| HTML Standard # dom-window-close-dev |

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

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


Window: screenY property - Web APIs

Window: screenY property
========================

The **`Window.screenY`** read-only property returns the vertical distance, in CSS pixels, of the top border of the user's browser viewport to the top edge of the screen.

**Note:** An alias of `screenY` was implemented across modern browsers in more recent times — `Window.screenTop`. This was originally supported only in IE but was introduced everywhere due to popularity.

Value
-----

A number equal to the number of CSS pixels from the top edge of the browser viewport to the top edge of the screen.

Examples
--------

In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using `Window.screenLeft`/`Window.screenTop` plus `Window.requestAnimationFrame()` to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.

```js
initialLeft = window.screenLeft + canvasElem.offsetLeft;
initialTop = window.screenTop + canvasElem.offsetTop;

function positionElem() {
  let newLeft = window.screenLeft + canvasElem.offsetLeft;
  let newTop = window.screenTop + canvasElem.offsetTop;

  let leftUpdate = initialLeft - newLeft;
  let topUpdate = initialTop - newTop;

  ctx.fillStyle = "rgb(0 0 0)";
  ctx.fillRect(0, 0, width, height);
  ctx.fillStyle = "rgb(0 0 255)";
  ctx.beginPath();
  ctx.arc(
    leftUpdate + width / 2,
    topUpdate + height / 2 + 35,
    50,
    degToRad(0),
    degToRad(360),
    false,
  );
  ctx.fill();

  pElem.textContent = `Window.screenLeft: ${window.screenLeft}, Window.screenTop: ${window.screenTop}`;

  window.requestAnimationFrame(positionElem);
}

window.requestAnimationFrame(positionElem);
```

These work in exactly the same way as `screenX`/`screenY`.

Also in the code we include a snippet that detects whether `screenLeft` is supported, and if not, polyfills in `screenLeft`/`screenTop` using `screenX`/`screenY`.

```js
if (!window.screenLeft) {
  window.screenLeft = window.screenX;
  window.screenTop = window.screenY;
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-window-screeny |

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

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

See also
--------

* `window.screenTop`
* `window.screenX`


Window: document property - Web APIs

Window: document property
=========================

**`window.document`** returns a reference to the document contained in the window.

Value
-----

A document object.

Examples
--------

```js
console.log(window.document.title);
```

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

| Specification |
| --- |
| HTML Standard # dom-document-dev |

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

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


Window: afterprint event - Web APIs

Window: afterprint event
========================

The **`afterprint`** event is fired after the associated document has started printing or the print preview has been closed.

The `beforeprint` and `afterprint` events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. In general, you should prefer the use of a `@media print` CSS at-rule, but it may be necessary to use these events in some cases.

Syntax
------

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

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

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

A generic `Event`.

Examples
--------

Using `addEventListener()`:

```js
window.addEventListener("afterprint", (event) => {
  console.log("After print");
});
```

Using the `onafterprint` event handler property:

```js
window.onafterprint = (event) => {
  console.log("After print");
};
```

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

| Specification |
| --- |
| HTML Standard # event-afterprint |
| HTML Standard # handler-window-onafterprint |

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

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

See also
--------

* Related events: `beforeprint`


Window: setImmediate() method - Web APIs

Window: setImmediate() 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.

This method is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates.

Syntax
------

```js
setImmediate(func)
setImmediate(func, param1)
setImmediate(func, param1, param2)
setImmediate(func, param1, param2, /\* …, \*/ paramN)
```

### Parameters

`func`

The function you wish to call.

`param1`, …, `paramN`

All parameters will be passed directly to your function.

### Return value

The ID of the immediate which can be used later with `window.clearImmediate`.

Notes
-----

The `clearImmediate` method can be used to clear the immediate actions, just like `clearTimeout` for `setTimeout()`.

This method can be used instead of the `setTimeout(fn, 0)` method to execute heavy operations.

The feature can be emulated in a few different ways:

* `postMessage` can be used to trigger an immediate but yielding callback.
* `MessageChannel` can be used reliably inside of Web Workers whereas the
 semantics of postMessage mean it cannot be used there.
* `setTimeout(fn, 0)` *can* potentially be used, however as it is clamped to 4ms for timers nested more than 5 levels deep per the HTML spec, it does not make for a suitable polyfill for the natural immediacy of `setImmediate`.

All of these techniques are incorporated into a robust setImmediate polyfill.

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

 Not part of any current specifications.
 The Efficient Script Yielding specification is no longer being worked on.

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

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

See also
--------

* Polyfill of `setImmediate` in `core-js`
* Microsoft `setImmediate` API Demo
* `Window.clearImmediate()`
* `Window.requestIdleCallback()`


Window: clearImmediate() method - Web APIs

Window: clearImmediate() 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.

This method clears the action specified by `window.setImmediate`.

Syntax
------

```js
clearImmediate(immediateID)
```

### Parameters

`immediateID`

The ID returned by `window.setImmediate`.

### Return value

None (`undefined`).

Examples
--------

```js
let immediateID = setImmediate(() => {
  // Run some code
});

document.getElementById("button").addEventListener(() => {
  clearImmediate(immediateID);
});
```

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

 Not part of any current specifications.
 The Efficient Script Yielding
 specification is no longer being worked on.

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

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

See also
--------

* Polyfill of `clearImmediate` in `core-js`
* `Window.setImmediate()`


Window: error event - Web APIs

Window: error event
===================

The `error` event is fired on a `Window` object when a resource failed to load or couldn't be used — for example if a script has an execution error.

Syntax
------

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

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

onerror = (event, source, lineno, colno, error) => {};
```

**Note:** Due to historical reasons, `onerror` on `window` is the only event handler property that receives more than one argument.

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

The event object is a `ErrorEvent` instance if it was generated from a user interface element, or an `Event` instance otherwise.

Event

ErrorEventUsage notes
-----------

### Event handler property

For historical reasons, the `onerror` event handler property, on `Window` objects only, has different behavior from other event handler properties.

Note that this only applies to handlers assigned to `onerror`, not to handlers added using `addEventListener()`.

#### Cancellation

Most event handlers assigned to event handler properties can cancel the event's default behavior by returning `false` from the handler:

```js
textarea.onkeydown = () => false;
```

However, for an event handler property to cancel the default behavior of the `error` event of `Window`, it must instead return `true`:

```js
window.onerror = () => true;
```

When canceled, the error won't appear in the console, but the current script will still stop executing.

#### Arguments

The event handler's signature is asymmetric between `addEventListener()` and `onerror`. The event handler passed to `Window.addEventListener()` receives a single `ErrorEvent` object, while the `onerror` handler receives five arguments, matching the `ErrorEvent` object's properties:

`event`

A string containing a human-readable error message describing the problem. Same as `ErrorEvent.message`.

`source`

A string containing the URL of the script that generated the error.

`lineno`

An integer containing the line number of the script file on which the error occurred.

`colno`

An integer containing the column number of the script file on which the error occurred.

`error`

The error being thrown. Usually an `Error` object.

```js
window.onerror = (a, b, c, d, e) => {
  console.log(`message: ${a}`);
  console.log(`source: ${b}`);
  console.log(`lineno: ${c}`);
  console.log(`colno: ${d}`);
  console.log(`error: ${e}`);

  return true;
};
```

**Note:** These parameter names are observable with an HTML event handler attribute, where the first parameter is called `event` instead of `message`.

This special behavior only happens for the `onerror` event handler on `window`. The `Element.onerror` handler still receives a single `ErrorEvent` object.

Examples
--------

### Live example

#### HTML

```html
<div class="controls">
  <button id="script-error" type="button">Generate script error</button>
  <img class="bad-img" />
</div>

<div class="event-log">
  <label for="eventLog">Event log:</label>
  <textarea
 readonly
 class="event-log-contents"
 rows="8"
 cols="30"
 id="eventLog"></textarea>
</div>
```

```
body {
  display: grid;
  grid-template-areas: "control log";
}

.controls {
  grid-area: control;
  display: flex;
  align-items: center;
  justify-content: center;
}

.event-log {
  grid-area: log;
}

.event-log-contents {
  resize: none;
}

label,
button {
  display: block;
}

button {
  height: 2rem;
  margin: 0.5rem;
}

img {
  width: 0;
  height: 0;
}
```

#### JavaScript

```js
const log = document.querySelector(".event-log-contents");

window.addEventListener("error", (event) => {
  log.textContent = `${log.textContent}${event.type}: ${event.message}\n`;
  console.log(event);
});

const scriptError = document.querySelector("#script-error");
scriptError.addEventListener("click", () => {
  const badCode = "const s;";
  eval(badCode);
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # event-error |
| HTML Standard # handler-onerror |

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

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

See also
--------

* This event on `Element` targets: `error` event


Window: scrollTo() method - Web APIs

Window: scrollTo() method
=========================

**`Window.scrollTo()`** scrolls to a particular set of
 coordinates in the document.

Syntax
------

```js
scrollTo(x-coord, y-coord)
scrollTo(options)
```

### Parameters

* `x-coord` is the pixel along the horizontal axis of the
 document that you want displayed in the upper left.
* `y-coord` is the pixel along the vertical axis of the document
 that you want displayed in the upper left.

- or -

`options`

A dictionary containing the following parameters:

`top`

Specifies the number of pixels along the Y axis to scroll the window or element.

`left`

Specifies the number of pixels along the X axis to scroll the window or element.

`behavior`

Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:

* `smooth`: scrolling should animate smoothly
* `instant`: scrolling should happen instantly in a single jump
* `auto`: scroll behavior is determined by the computed value of `scroll-behavior`

### Return value

None (`undefined`).

Examples
--------

```js
window.scrollTo(0, 1000);
```

Using `options`:

```js
window.scrollTo({
  top: 100,
  left: 100,
  behavior: "smooth",
});
```

Notes
-----

`Window.scroll()` is effectively the same as this method. For relative
 scrolling, see `Window.scrollBy()`, `Window.scrollByLines()`,
 and `Window.scrollByPages()`.

 For scrolling elements, see `Element.scrollTop` and
 `Element.scrollLeft`.

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

| Specification |
| --- |
| CSSOM View Module # dom-window-scrollto |

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

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


Window: paste event - Web APIs

Window: paste event
===================

The **`paste`** event is fired when the user has initiated a "paste" action through the browser's user interface.

The original target for this event is the `Element` that was the intended target of the paste action. You can listen for this event on the `Window` interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: paste event.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExamples
--------

```js
window.addEventListener("paste", (event) => {
  console.log("paste action initiated");
});
```

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-paste |
| HTML Standard # handler-onpaste |

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

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

See also
--------

* Related events: `cut`, `copy`
* This event on `Element` targets: `paste`
* This event on `Document` targets: `paste`


Window: frameElement property - Web APIs

Window: frameElement property
=============================

 The **`Window.frameElement`** property
 returns the element (such as `<iframe>` or `<object>`)
 in which the window is embedded.

**Note:** Despite this property's name, it works for documents embedded
 within any embedding point, including `<object>`,
 `<iframe>`, or `<embed>`.

Value
-----

 The element which the window is embedded into. If the window isn't embedded into
 another document, or if the document into which it's embedded has a different
 origin, the value is `null` instead.

Examples
--------

```js
const frameEl = window.frameElement;
// If we're embedded, change the containing element's URL to 'https://mozilla.org/'
if (frameEl) {
  frameEl.src = "https://mozilla.org/";
}
```

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

| Specification |
| --- |
| HTML Standard # dom-frameelement-dev |

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

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

See also
--------

* `window.frames` returns an array-like object, listing the direct
 sub-frames of the current window.
* `window.parent` returns the parent window, which is the window
 containing the `frameElement` of the child window.


Window: screenTop property - Web APIs

Window: screenTop property
==========================

 The **`Window.screenTop`** read-only property returns the
 vertical distance, in CSS pixels, from the top border of the user's browser viewport to
 the top side of the screen.

**Note:** `screenTop` is an alias of the older
 `Window.screenY` property. `screenTop` was originally
 supported only in IE but was introduced everywhere due to popularity.

Value
-----

 A number equal to the number of CSS pixels from the top edge of the browser viewport to
 the top edge of the screen.

Examples
--------

 In our screenleft-screentop
 example, you'll see a canvas onto which has been drawn a circle. In this example we are
 using `screenLeft`/`screenTop` plus
 `Window.requestAnimationFrame()` to constantly redraw the circle in the
 same physical position on the screen, even if the window position is moved.

```js
initialLeft = window.screenLeft + canvasElem.offsetLeft;
initialTop = window.screenTop + canvasElem.offsetTop;

function positionElem() {
  let newLeft = window.screenLeft + canvasElem.offsetLeft;
  let newTop = window.screenTop + canvasElem.offsetTop;

  let leftUpdate = initialLeft - newLeft;
  let topUpdate = initialTop - newTop;

  ctx.fillStyle = "rgb(0 0 0)";
  ctx.fillRect(0, 0, width, height);
  ctx.fillStyle = "rgb(0 0 255)";
  ctx.beginPath();
  ctx.arc(
    leftUpdate + width / 2,
    topUpdate + height / 2 + 35,
    50,
    degToRad(0),
    degToRad(360),
    false,
  );
  ctx.fill();

  pElem.textContent = `Window.screenLeft: ${window.screenLeft}, Window.screenTop: ${window.screenTop}`;

  window.requestAnimationFrame(positionElem);
}

window.requestAnimationFrame(positionElem);
```

 Also in the code we include a snippet that detects whether `screenLeft` is
 supported, and if not, polyfills in `screenLeft`/`screenTop` using
 `Window.screenX`/`Window.screenY`.

```js
if (!window.screenLeft) {
  window.screenLeft = window.screenX;
  window.screenTop = window.screenY;
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-window-screentop |

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

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

See also
--------

* `window.screenLeft`
* `Window.screenY`