URL Pattern API - Web APIs

URL Pattern API
===============

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

 The **URL Pattern API** defines a syntax that is used to create URL pattern
 matchers. These patterns can be matched against URLs or individual URL
 components. The URL Pattern API is used by the `URLPattern`
 interface.

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

Concepts and usage
------------------

 The pattern syntax is based on the syntax from the
 path-to-regexp library. Patterns
 can contain:

* Literal strings which will be matched exactly.
* Wildcards (`/posts/*`) that match any character.
* Named groups (`/books/:id`) which extract a part of the matched URL.
* Non-capturing groups (`/books{/old}?`) which make parts of a pattern optional
 or be matched multiple times.
* `RegExp` groups (`/books/(\\d+)`) which make arbitrarily complex
 regex matches with a few limitations.

 You can find details about the syntax in the pattern syntax
 section below.

Interfaces
----------

The URL Pattern API only has a single related interface:

`URLPattern`
Experimental

Represents a pattern that can match URLs or parts of URLs. The pattern can contain capturing groups that extract parts of the matched URL.

Pattern syntax
--------------

 The syntax for patterns is based on the
 path-to-regexp JavaScript library.
 This syntax is similar to the one used in
 Ruby on Rails, or JavaScript frameworks like
 Express or Next.js.

### Fixed text and capture groups

 Each pattern can contain a combination of fixed text and groups. The fixed text
 is a sequence of characters that is matched exactly. Groups match an arbitrary
 string based on matching rules. Each URL part has its own default rules that are
 explained below, but they can be overwritten.

```js
// A pattern matching some fixed text
const pattern = new URLPattern({ pathname: "/books" });
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.exec("https://example.com/books").pathname.groups); // {}
```

```js
// A pattern matching with a named group
const pattern = new URLPattern({ pathname: "/books/:id" });
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { id: '123' }
```

### Segment wildcard

 By default, a group matching the `pathname` part of the URL will match all
 characters but the forward slash (`/`). In the `hostname` part, the group will
 match all characters except the dot (`.`). In all other parts, the group will
 match all characters. The segment wildcard is non-greedy, meaning that it will
 match the shortest possible string.

### Regex matchers

 Instead of using the default match rules for a group, you can use a regex for
 each group. This regex defines the matching rules for the group. Below is an
 example of a regex matcher on a named group that constrains the group to only
 match if it contains one or more digits:

```js
const pattern = new URLPattern("/books/:id(\\d+)", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books/abc")); // false
console.log(pattern.test("https://example.com/books/")); // false
```

### Regex matchers limitations

Some regex patterns do not work as you may expect:

* Starts with `^` will only match if used at the start of the protocol portion of the URLPattern and is redundant if used.

```js
// with `^` in pathname
const pattern = new URLPattern({ pathname: "(^b)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false
```

```js
// with `^` in protocol
const pattern = new URLPattern({ protocol: "(^https?)" });
console.log(pattern.test("https://example.com/index.html")); // true
console.log(pattern.test("xhttps://example.com/index.html")); // false
```

```js
// without `^` in protocol
const pattern = new URLPattern({ protocol: "(https?)" });
console.log(pattern.test("https://example.com/index.html")); // true
console.log(pattern.test("xhttps://example.com/index.html")); // false
```

* Ends with `$` will only match if used at the end of the hash portion of the URLPattern and is redundant if used.

```js
// with `$` in pathname
const pattern = new URLPattern({ pathname: "(path$)" });
console.log(pattern.test("https://example.com/path")); // false
console.log(pattern.test("https://example.com/other")); // false
```

```js
// with `$` in hash
const pattern = new URLPattern({ hash: "(hash$)" });
console.log(pattern.test("https://example.com/#hash")); // true
console.log(pattern.test("xhttps://example.com/#otherhash")); // false
```

```js
// without `$` in hash
const pattern = new URLPattern({ hash: "(hash)" });
console.log(pattern.test("https://example.com/#hash")); // true
console.log(pattern.test("xhttps://example.com/#otherhash")); // false
```

* Lookaheads, and lookbehinds will never match any portion of the URLPattern.

```js
// lookahead
const pattern = new URLPattern({ pathname: "(a(?=b))" });
console.log(pattern.test("https://example.com/ab")); // false
console.log(pattern.test("https://example.com/ax")); // false
```

```js
// negative-lookahead
const pattern = new URLPattern({ pathname: "(a(?!b))" });
console.log(pattern.test("https://example.com/ab")); // false
console.log(pattern.test("https://example.com/ax")); // false
```

```js
// lookbehind
const pattern = new URLPattern({ pathname: "((?<=b)a)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false
```

```js
// negative-lookbehind
const pattern = new URLPattern({ pathname: "((?<!b)a)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false
```

* Parentheses need to be escaped in range expressions within URLPattern even though they don't in RegExp.

```js
new URLPattern({ pathname: "([()])" }); // throws
new URLPattern({ pathname: "([\\(\\)])" }); // ok

new RegExp("[()]"); // ok
new RegExp("[\\(\\)]"); // ok
```

### Unnamed and named groups

 Groups can either be named or unnamed. Named groups are specified by prefixing
 the group name with a colon (`:`). Regexp groups that are not prefixed by a
 colon and a name are unnamed. Unnamed groups are numerically indexed in the match
 result based on their order in the pattern.

```js
// A named group
const pattern = new URLPattern("/books/:id(\\d+)", "https://example.com");
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { id: '123' }
```

```js
// An unnamed group
const pattern = new URLPattern("/books/(\\d+)", "https://example.com");
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { '0': '123' }
```

### Group modifiers

 Groups can also have modifiers. These are specified after the group name (or
 after the regexp if there is one). There are three modifiers: `?` to make the
 group optional, `+` to make the group repeat one or more times, and `*` to make
 the group repeat zero or more times.

```js
// An optional group
const pattern = new URLPattern("/books/:id?", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // false
console.log(pattern.test("https://example.com/books/123/456/789")); // false
```

```js
// A repeating group with a minimum of one
const pattern = new URLPattern("/books/:id+", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/456/789")); // true
```

```js
// A repeating group with a minimum of zero
const pattern = new URLPattern("/books/:id\*", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/456/789")); // true
```

### Group delimiters

 Patterns can also contain group delimiters. These are pieces of a pattern that
 are surrounded by curly braces (`{}`). These group delimiters are not captured
 in the match result like capturing groups, but can still have modifiers applied
 to them, just like groups. If group delimiters are not modified by a modifier,
 they are treated as if the items in them were just part of the parent pattern.
 Group delimiters may not contain other group delimiters, but may contain any
 other pattern items (capturing groups, regex, wildcard, or fixed text).

```js
// A group delimiter with a ? (optional) modifier
const pattern = new URLPattern("/book{s}?", "https://example.com");
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/book")); // true
console.log(pattern.exec("https://example.com/books").pathname.groups); // {}
```

```js
// A group delimiter without a modifier
const pattern = new URLPattern("/book{s}", "https://example.com");
console.log(pattern.pathname); // /books
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/book")); // false
```

```js
// A group delimiter containing a capturing group
const pattern = new URLPattern({ pathname: "/blog/:id(\\d+){-:title}?" });
console.log(pattern.test("https://example.com/blog/123-my-blog")); // true
console.log(pattern.test("https://example.com/blog/123")); // true
console.log(pattern.test("https://example.com/blog/my-blog")); // false
```

### Automatic group prefixing in pathnames

 In patterns that match against the `pathname` part of a URL, groups get an
 automatic slash (`/`) prefix added if the group definition is preceded by a
 slash (`/`). This is useful for groups with modifiers, as it allows for
 repeating groups to work as expected.

 If you do not want automatic prefixing, you can disable it by surrounding the
 group with group delimiters (`{}`). Group delimiters do not have automatic
 prefixing behavior.

```js
// A pattern with an optional group, preceded by a slash
const pattern = new URLPattern("/books/:id?", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false
```

```js
// A pattern with a repeating group, preceded by a slash
const pattern = new URLPattern("/books/:id+", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/")); // false
console.log(pattern.test("https://example.com/books/123/456/")); // false
```

```js
// Segment prefixing does not occur outside of pathname patterns
const pattern = new URLPattern({ hash: "/books/:id?" });
console.log(pattern.test("https://example.com#/books/123")); // true
console.log(pattern.test("https://example.com#/books")); // false
console.log(pattern.test("https://example.com#/books/")); // true
```

```js
// Disabling segment prefixing for a group using a group delimiter
const pattern = new URLPattern({ pathname: "/books/{:id}?" });
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // true
```

### Wildcard tokens

 The wildcard token (`*`) is a shorthand for an unnamed capturing group that
 matches all characters zero or more times. You can place this anywhere in the
 pattern. The wildcard is greedy, meaning that it will match the longest possible
 string.

```js
// A wildcard at the end of a pattern
const pattern = new URLPattern("/books/\*", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // true
console.log(pattern.test("https://example.com/books/123/456")); // true
```

```js
// A wildcard in the middle of a pattern
const pattern = new URLPattern("/\*.png", "https://example.com");
console.log(pattern.test("https://example.com/image.png")); // true
console.log(pattern.test("https://example.com/image.png/123")); // false
console.log(pattern.test("https://example.com/folder/image.png")); // true
console.log(pattern.test("https://example.com/.png")); // true
```

### Pattern normalization

 When a pattern is parsed it is automatically normalized to a canonical form. For
 example, unicode characters are percent encoded in the pathname property,
 punycode encoding is used in the hostname, default port numbers are elided,
 paths like `/foo/./bar/` are collapsed to just `/foo/bar`, etc. In addition,
 there are some pattern representations that parse to the same underlying
 meaning, like `foo` and `{foo}`. Such cases are normalized to the simplest form.
 In this case `{foo}` gets changed to `foo`.

Case sensitivity
----------------

The URL Pattern API treats many parts of the URL as case-sensitive by default when matching. In contrast, many client-side JavaScript frameworks use case-insensitive URL matching. An `ignoreCase` option is available on the `URLPattern()` constructor to enable case-insensitive matching if desired.

```js
// Case-sensitive matching by default
const pattern = new URLPattern("https://example.com/2022/feb/\*");
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // false
```

Setting the `ignoreCase` option to `true` in the constructor switches all matching operations to case-insensitive for the given pattern:

```js
// Case-insensitive matching
const pattern = new URLPattern("https://example.com/2022/feb/\*", {
  ignoreCase: true,
});
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // true
```

Examples
--------

### Filter on a specific URL component

 The following example shows how a `URLPattern` filters a specific URL component.
 When the `URLPattern()` constructor is called with a structured object of
 component patterns any missing components default to the `*` wildcard value.

```js
// Construct a URLPattern that matches a specific domain and its subdomains.
// All other URL components default to the wildcard `\*` pattern.
const pattern = new URLPattern({
  hostname: "{\*.}?example.com",
});

console.log(pattern.hostname); // '{\*.}?example.com'

console.log(pattern.protocol); // '\*'
console.log(pattern.username); // '\*'
console.log(pattern.password); // '\*'
console.log(pattern.pathname); // '\*'
console.log(pattern.search); // '\*'
console.log(pattern.hash); // '\*'

console.log(pattern.test("https://example.com/foo/bar")); // true

console.log(pattern.test({ hostname: "cdn.example.com" })); // true

console.log(pattern.test("custom-protocol://example.com/other/path?q=1")); // false

// Prints `false` because the hostname component does not match
console.log(pattern.test("https://cdn-example.com/foo/bar"));
```

### Construct a URLPattern from a full URL string

 The following example shows how to construct a `URLPattern` from a full URL
 string with embedded patterns. For example, a `:` can be both the URL protocol
 suffix, like `https:`, and the beginning of a named pattern group, like `:foo`.
 It "just works" if there is no ambiguity between whether a character is part of
 the URL syntax or part of the pattern syntax.

```js
// Construct a URLPattern that matches URLs to CDN servers loading jpg images.
// URL components not explicitly specified, like search and hash here, result
// in the empty string similar to the URL() constructor.
const pattern = new URLPattern("https://cdn-\*.example.com/\*.jpg");

console.log(pattern.protocol); // 'https'

console.log(pattern.hostname); // 'cdn-\*.example.com'

console.log(pattern.pathname); // '/\*.jpg'

console.log(pattern.username); // ''
console.log(pattern.password); // ''
console.log(pattern.search); // ''
console.log(pattern.hash); // ''

// Prints `true`
console.log(
  pattern.test("https://cdn-1234.example.com/product/assets/hero.jpg"),
);

// Prints `false` because the search component does not match
console.log(
  pattern.test("https://cdn-1234.example.com/product/assets/hero.jpg?q=1"),
);
```

### Constructing a URLPattern with an ambiguous URL string

 The following example shows how a `URLPattern` constructed from an ambiguous
 string will favor treating characters as part of the pattern syntax. In this
 case the `:` character could be the protocol component suffix or it could be the
 prefix for a named group in the pattern. The constructor chooses to treat this
 as part of the pattern and therefore determines this is a relative pathname
 pattern. Since there is no base URL the relative pathname cannot be resolved and
 it throws an error.

```js
// Throws because this is interpreted as a single relative pathname pattern
// with a ":foo" named group and there is no base URL.
const pattern = new URLPattern("data:foo\*");
```

### Escaping characters to disambiguate URLPattern constructor strings

 The following example shows how an ambiguous constructor string character can be
 escaped to be treated as a URL separator instead of a pattern character. Here
 `:` is escaped as `\\:`.

```js
// Constructs a URLPattern treating the `:` as the protocol suffix.
const pattern = new URLPattern("data\\:foo\*");

console.log(pattern.protocol); // 'data'

console.log(pattern.pathname); // 'foo\*'

console.log(pattern.username); // ''
console.log(pattern.password); // ''
console.log(pattern.hostname); // ''
console.log(pattern.port); // ''
console.log(pattern.search); // ''
console.log(pattern.hash); // ''

console.log(pattern.test("data:foobar")); // true
```

### Using base URLs for test() and exec()

The following example shows how `test()` and `exec()` can use base URLs.

```js
const pattern = new URLPattern({ hostname: "example.com", pathname: "/foo/\*" });

// Prints `true` as the hostname based in the dictionary `baseURL` property
// matches.
console.log(
  pattern.test({
    pathname: "/foo/bar",
    baseURL: "https://example.com/baz",
  }),
);

// Prints `true` as the hostname in the second argument base URL matches.
console.log(pattern.test("/foo/bar", "https://example.com/baz"));

// Throws because the second argument cannot be passed with a dictionary input.
try {
  pattern.test({ pathname: "/foo/bar" }, "https://example.com/baz");
} catch (e) {}

// The `exec()` method takes the same arguments as `test()`.
const result = pattern.exec("/foo/bar", "https://example.com/baz");

console.log(result.pathname.input); // '/foo/bar'

console.log(result.pathname.groups[0]); // 'bar'

console.log(result.hostname.input); // 'example.com'
```

### Using base URLs in the URLPattern constructor

 The follow example shows how base URLs can also be used to construct the
 `URLPattern`. Note that the base URL in these cases is treated strictly as a URL
 and cannot contain any pattern syntax itself.

 Also, since the base URL provides a value for every component the resulting
 `URLPattern` will also have a value for every component, even if it's the empty
 string. This means you do not get the "default to wildcard" behavior.

```js
const pattern1 = new URLPattern({
  pathname: "/foo/\*",
  baseURL: "https://example.com",
});

console.log(pattern1.protocol); // 'https'
console.log(pattern1.hostname); // 'example.com'
console.log(pattern1.pathname); // '/foo/\*'

console.log(pattern1.username); // ''
console.log(pattern1.password); // ''
console.log(pattern1.port); // ''
console.log(pattern1.search); // ''
console.log(pattern1.hash); // ''

// Equivalent to pattern1
const pattern2 = new URLPattern("/foo/\*", "https://example.com");

// Throws because a relative constructor string must have a base URL to resolve
// against.
try {
  const pattern3 = new URLPattern("/foo/\*");
} catch (e) {}
```

### Accessing matched group values

 The following example shows how input values that match pattern groups can later
 be accessed from the `exec()` result object. Unnamed groups are assigned index
 numbers sequentially.

```js
const pattern = new URLPattern({ hostname: "\*.example.com" });
const result = pattern.exec({ hostname: "cdn.example.com" });

console.log(result.hostname.groups[0]); // 'cdn'

console.log(result.hostname.input); // 'cdn.example.com'

console.log(result.inputs); // [{ hostname: 'cdn.example.com' }]
```

### Accessing matched group values using custom names

 The following example shows how groups can be given custom names which can be
 used to accessed the matched value in the result object.

```js
// Construct a URLPattern using matching groups with custom names. These
// names can then be later used to access the matched values in the result
// object.
const pattern = new URLPattern({ pathname: "/:product/:user/:action" });
const result = pattern.exec({ pathname: "/store/wanderview/view" });

console.log(result.pathname.groups.product); // 'store'
console.log(result.pathname.groups.user); // 'wanderview'
console.log(result.pathname.groups.action); // 'view'

console.log(result.pathname.input); // '/store/wanderview/view'

console.log(result.inputs); // [{ pathname: '/store/wanderview/view' }]
```

### Custom regular expression groups

 The following example shows how a matching group can use a custom regular
 expression.

```js
const pattern = new URLPattern({ pathname: "/(foo|bar)" });

console.log(pattern.test({ pathname: "/foo" })); // true
console.log(pattern.test({ pathname: "/bar" })); // true
console.log(pattern.test({ pathname: "/baz" })); // false

const result = pattern.exec({ pathname: "/foo" });

console.log(result.pathname.groups[0]); // 'foo'
```

### Named group with a custom regular expression

 The following example shows how to use a custom regular expression with a named
 group.

```js
const pattern = new URLPattern({ pathname: "/:type(foo|bar)" });
const result = pattern.exec({ pathname: "/foo" });

console.log(result.pathname.groups.type); // 'foo'
```

### Making matching groups optional

 The following example shows how to make a matching group optional by placing a
 `?` modifier after it. For the pathname component this also causes any preceding
 `/` character to be treated as an optional prefix to the group.

```js
const pattern = new URLPattern({ pathname: "/product/(index.html)?" });

console.log(pattern.test({ pathname: "/product/index.html" })); // true
console.log(pattern.test({ pathname: "/product" })); // true

const pattern2 = new URLPattern({ pathname: "/product/:action?" });

console.log(pattern2.test({ pathname: "/product/view" })); // true
console.log(pattern2.test({ pathname: "/product" })); // true

// Wildcards can be made optional as well. This may not seem to make sense
// since they already match the empty string, but it also makes the prefix
// `/` optional in a pathname pattern.
const pattern3 = new URLPattern({ pathname: "/product/\*?" });

console.log(pattern3.test({ pathname: "/product/wanderview/view" })); // true
console.log(pattern3.test({ pathname: "/product" })); // true
console.log(pattern3.test({ pathname: "/product/" })); // true
```

### Making matching groups repeated

 The following example shows how a matching group can be made repeated by placing
 `+` modifier after it. In the `pathname` component this also treats the `/`
 prefix as special. It is repeated with the group.

```js
const pattern = new URLPattern({ pathname: "/product/:action+" });
const result = pattern.exec({ pathname: "/product/do/some/thing/cool" });

result.pathname.groups.action; // 'do/some/thing/cool'

console.log(pattern.test({ pathname: "/product" })); // false
```

### Making matching groups optional and repeated

 The following example shows how to make a matching group that is both optional
 and repeated. Do this by placing a `*` modifier after the group. Again, the
 pathname component treats the `/` prefix as special. It both becomes optional
 and is also repeated with the group.

```js
const pattern = new URLPattern({ pathname: "/product/:action\*" });
const result = pattern.exec({ pathname: "/product/do/some/thing/cool" });

console.log(result.pathname.groups.action); // 'do/some/thing/cool'

console.log(pattern.test({ pathname: "/product" })); // true
```

### Using a custom prefix or suffix for an optional or repeated modifier

 The following example shows how curly braces can be used to denote a custom
 prefix and/or suffix to be operated on by a subsequent `?`, `*`, or `+`
 modifier.

```js
const pattern = new URLPattern({ hostname: "{:subdomain.}\*example.com" });

console.log(pattern.test({ hostname: "example.com" })); // true
console.log(pattern.test({ hostname: "foo.bar.example.com" })); // true
console.log(pattern.test({ hostname: ".example.com" })); // false

const result = pattern.exec({ hostname: "foo.bar.example.com" });

console.log(result.hostname.groups.subdomain); // 'foo.bar'
```

### Making text optional or repeated without a matching group

 The following example shows how curly braces can be used to denote fixed text
 values as optional or repeated without using a matching group.

```js
const pattern = new URLPattern({ pathname: "/product{/}?" });

console.log(pattern.test({ pathname: "/product" })); // true
console.log(pattern.test({ pathname: "/product/" })); // true

const result = pattern.exec({ pathname: "/product/" });

console.log(result.pathname.groups); // {}
```

### Using multiple components and features at once

 The following example shows how many features can be combined across multiple
 URL components.

```js
const pattern = new URLPattern({
  protocol: "http{s}?",
  username: ":user?",
  password: ":pass?",
  hostname: "{:subdomain.}\*example.com",
  pathname: "/product/:action\*",
});

const result = pattern.exec(
  "http://foo:bar@sub.example.com/product/view?q=12345",
);

console.log(result.username.groups.user); // 'foo'
console.log(result.password.groups.pass); // 'bar'
console.log(result.hostname.groups.subdomain); // 'sub'
console.log(result.pathname.groups.action); // 'view'
```

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

| Specification |
| --- |
| URL Pattern Standard  |

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

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

See also
--------

* A polyfill of `URLPattern` is available
 on GitHub
* The pattern syntax used by URLPattern is similar to the syntax used by
 path-to-regexp


MIDIConnectionEvent - Web APIs

MIDIConnectionEvent
===================

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

The **`MIDIConnectionEvent`** interface of the Web MIDI API is the event passed to the `statechange` event of the `MIDIAccess` interface and the `statechange` event of the `MIDIPort` interface. This occurs any time a new port becomes available, or when a previously available port becomes unavailable. For example, this event is fired whenever a MIDI device is either plugged in to or unplugged from a computer.

Event

MIDIConnectionEventConstructor
-----------

`MIDIConnectionEvent()`

Creates a new `MIDIConnectionEvent` object.

Instance properties
-------------------

`MIDIConnectionEvent.port` Read only

Returns a reference to a `MIDIPort` instance for a port that has been connected or disconnected.

Examples
--------

The `Navigator.requestMIDIAccess()` method returns a promise that resolves with a `MIDIAccess` object. When a port changes state, a `MIDIConnectionEvent` is passed to `statechange` event. Information about the port can then be printed to the console.

```js
navigator.requestMIDIAccess().then((access) => {
  access.onstatechange = (event) => {
    console.log(event.port.name, event.port.manufacturer, event.port.state);
  };
});
```

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

| Specification |
| --- |
| Web MIDI API # midiconnectionevent-interface |

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

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


Service Worker API - Web APIs

Service Worker API
==================

Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.

Service worker concepts and usage
---------------------------------

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available).

A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is non-blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and Web Storage can't be used inside a service worker.

 Service workers can't import JavaScript module dynamically, and `import()` will throw if it is called in a service worker global scope.
 Static import using the `import` statement is allowed.

Service workers only run over HTTPS, for security reasons. Most significantly, HTTP connections are susceptible to malicious code injection by man in the middle attacks, and such attacks could be worse if allowed access to these powerful APIs. In Firefox, service worker APIs are also hidden and cannot be used when the user is in private browsing mode.

**Note:** On Firefox, for testing you can run service workers over HTTP (insecurely); simply check the **Enable Service Workers over HTTP (when toolbox is open)** option in the Firefox Devtools options/gear menu.

**Note:** Unlike previous attempts in this area such as AppCache, service workers don't make assumptions about what you are trying to do, but then break when those assumptions are not exactly right. Instead, service workers give you much more granular control.

**Note:** Service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.

### Registration

A service worker is first registered using the `ServiceWorkerContainer.register()` method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.

### Download, install and activate

At this point, your service worker will observe the following lifecycle:

1. Download
2. Install
3. Activate

The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.

After that, it is updated when:

* A navigation to an in-scope page occurs.
* An event is fired on the service worker and it hasn't been downloaded in the last 24 hours.

Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.

If this is the first time a service worker has been made available, installation is attempted, then after a successful installation, it is activated.

If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the *worker in waiting*. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more pages to be loaded, the new service worker activates (becoming the *active worker*). Activation can happen sooner using `ServiceWorkerGlobalScope.skipWaiting()` and existing pages can be claimed by the active worker using `Clients.claim()`.

You can listen for the `install` event; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

There is also an `activate` event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.

Your service worker can respond to requests using the `FetchEvent` event. You can modify the response to these requests in any way you want, using the `FetchEvent.respondWith()` method.

**Note:** Because `install`/`activate` events could take a while to complete, the service worker spec provides a `waitUntil()` method. Once it is called on `install` or `activate` events with a promise, functional events such as `fetch` and `push` will wait until the promise is successfully resolved.

For a complete tutorial to show how to build up your first basic example, read Using Service Workers.

Other use case ideas
--------------------

Service workers are also intended to be used for such things as:

* Background data synchronization.
* Responding to resource requests from other origins.
* Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data.
* Client-side compiling and dependency management of CoffeeScript, less, CJS/AMD modules, etc. for development purposes.
* Hooks for background services.
* Custom templating based on certain URL patterns.
* Performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.
* API mocking.

In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

* Background synchronization: Start up a service worker even when no users are at the site, so caches can be updated, etc.
* Reacting to push messages: Start up a service worker to send users a message to tell them new content is available.
* Reacting to a particular time & date.
* Entering a geo-fence.
Interfaces
----------

`Cache`

Represents the storage for `Request` / `Response` object pairs that are cached as part of the `ServiceWorker` life cycle.

`CacheStorage`

Represents the storage for `Cache` objects. It provides a master directory of all the named caches that a `ServiceWorker` can access, and maintains a mapping of string names to corresponding `Cache` objects.

`Client`

Represents the scope of a service worker client. A service worker client is either a document in a browser context or a `SharedWorker`, which is controlled by an active worker.

`Clients`

Represents a container for a list of `Client` objects; the main way to access the active service worker clients at the current origin.

`ExtendableEvent`

Extends the lifetime of the `install` and `activate` events dispatched on the `ServiceWorkerGlobalScope`, as part of the service worker lifecycle. This ensures that any functional events (like `FetchEvent`) are not dispatched to the `ServiceWorker`, until it upgrades database schemas, and deletes outdated cache entries, etc.

`ExtendableMessageEvent`

The event object of a `message` event fired on a service worker (when a channel message is received on the `ServiceWorkerGlobalScope` from another context) — extends the lifetime of such events.

`FetchEvent`

The parameter passed into the `onfetch` handler, `FetchEvent` represents a fetch action that is dispatched on the `ServiceWorkerGlobalScope` of a `ServiceWorker`. It contains information about the request and resulting response, and provides the `FetchEvent.respondWith()` method, which allows us to provide an arbitrary response back to the controlled page.

`InstallEvent`
Deprecated

Non-standard

The parameter passed into the `oninstall` handler, the `InstallEvent` interface represents an install action that is dispatched on the `ServiceWorkerGlobalScope` of a `ServiceWorker`. As a child of `ExtendableEvent`, it ensures that functional events such as `FetchEvent` are not dispatched during installation.

`NavigationPreloadManager`

Provides methods for managing the preloading of resources with a service worker.

`ServiceWorker`

Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same `ServiceWorker` object.

`ServiceWorkerContainer`

Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister, and update service workers, and access the state of service workers and their registrations.

`ServiceWorkerGlobalScope`

Represents the global execution context of a service worker.

`ServiceWorkerRegistration`

Represents a service worker registration.

`WindowClient`

Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of `Client` object, with some additional methods and properties available.

### Extensions to other interfaces

`caches`

Returns the `CacheStorage` object associated with the current context.

`Navigator.serviceWorker`

Returns a `ServiceWorkerContainer` object, which provides access to registration, removal, upgrade, and communication with the `ServiceWorker` objects for the associated document.

`WorkerNavigator.serviceWorker`

Returns a `ServiceWorkerContainer` object, which provides access to registration, removal, upgrade, and communication with the `ServiceWorker` objects for the associated document.

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

| Specification |
| --- |
| Service Workers  |

See also
--------

* ServiceWorker Cookbook
* Using Service Workers
* Service workers basic code example
* Web APIs that are related to the Service Worker API:
    + Background Fetch API
    + Background Synchronization API
    + Content Index API
    + Cookie Store API
    + Notifications API
    + Payment Handler API
    + Push API
    + Web Periodic Background Synchronization API


PerformanceNavigationTiming - Web APIs

PerformanceNavigationTiming
===========================

The **`PerformanceNavigationTiming`** interface provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. For example, this interface can be used to determine how much time it takes to load or unload a document.

Only the current document is included in the performance timeline, so there is only one `PerformanceNavigationTiming` object in the performance timeline. It inherits all of the properties and methods of `PerformanceResourceTiming` and `PerformanceEntry`.

PerformanceEntry

PerformanceResourceTiming

PerformanceNavigationTiming
The following diagram shows all of the timestamp properties defined in `PerformanceNavigationTiming`.

![Timestamp diagram listing timestamps in the order in which they are recorded for the fetching of a document](/en-US/docs/Web/API/PerformanceNavigationTiming/timestamp-diagram.svg)

Instance properties
-------------------

This interface extends the following `PerformanceEntry` properties by qualifying and constraining them as follows:

`PerformanceEntry.entryType` Read only

Returns `"navigation"`.

`PerformanceEntry.name` Read only

Returns the document's URL.

`PerformanceEntry.startTime` Read only

Returns a `DOMHighResTimeStamp` with a value of "`0`".

`PerformanceEntry.duration` Read only

Returns a `timestamp` that is the difference between the `PerformanceNavigationTiming.loadEventEnd` and `PerformanceEntry.startTime` properties.

This interface also extends the following `PerformanceResourceTiming` properties by qualifying and constraining them as follows:

`PerformanceResourceTiming.initiatorType` Read only

Returns `"navigation"`.

The interface also supports the following properties:

`PerformanceNavigationTiming.activationStart` Read only
Experimental

A `DOMHighResTimeStamp` representing the time between when a document starts prerendering and when it is activated.

`PerformanceNavigationTiming.domComplete` Read only

A `DOMHighResTimeStamp` representing the time immediately before the user agent sets the document's `readyState` to `"complete"`.

`PerformanceNavigationTiming.domContentLoadedEventEnd` Read only

A `DOMHighResTimeStamp` representing the time immediately after the current document's `DOMContentLoaded` event handler completes.

`PerformanceNavigationTiming.domContentLoadedEventStart` Read only

A `DOMHighResTimeStamp` representing the time immediately before the current document's `DOMContentLoaded` event handler starts.

`PerformanceNavigationTiming.domInteractive` Read only

A `DOMHighResTimeStamp` representing the time immediately before the user agent sets the document's `readyState` to `"interactive"`.

`PerformanceNavigationTiming.loadEventEnd` Read only

A `DOMHighResTimeStamp` representing the time immediately after the current document's `load` event handler completes.

`PerformanceNavigationTiming.loadEventStart` Read only

A `DOMHighResTimeStamp` representing the time immediately before the current document's `load` event handler starts.

`PerformanceNavigationTiming.redirectCount` Read only

A number representing the number of redirects since the last non-redirect navigation in the current browsing context.

`PerformanceNavigationTiming.type` Read only

A string representing the navigation type. Either `"navigate"`, `"reload"`, `"back_forward"` or `"prerender"`.

`PerformanceNavigationTiming.unloadEventEnd` Read only

A `DOMHighResTimeStamp` representing the time immediately after the current document's `unload` event handler completes.

`PerformanceNavigationTiming.unloadEventStart` Read only

A `DOMHighResTimeStamp` representing the time immediately before the current document's `unload` event handler starts.

Instance methods
----------------

`PerformanceNavigationTiming.toJSON()`

Returns a JSON representation of the `PerformanceNavigationTiming` object.

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

| Specification |
| --- |
| Navigation Timing Level 2 # sec-PerformanceNavigationTiming |

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

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

See also
--------

* `Performance.navigation`
* `PerformanceNavigation`


XRRigidTransform - Web APIs

XRRigidTransform
================

The **`XRRigidTransform`** is a WebXR API interface that represents the 3D geometric transform described by a position and orientation.

`XRRigidTransform` is used to specify transforms throughout the WebXR APIs, including:

* The offset and orientation relative to the parent reference space to use when creating a new reference space with `getOffsetReferenceSpace()`.
* The `transform` of an `XRView`.
* The `transform` of an `XRPose`.
* The `XRReferenceSpaceEvent` event's `transform` property, as found in the `reset` event received by an `XRReferenceSpace`.

Using `XRRigidTransform` in these places rather than bare arrays that provide the matrix data has an advantage. It automatically computes the inverse of the transform and even caches it making subsequent requests significantly faster.

Constructor
-----------

`new XRRigidTransform()`

Creates a new `XRRigidTransform` object which represents a transform that applies a specified position and/or orientation.

Instance properties
-------------------

`XRRigidTransform.position` Read only

A `DOMPointReadOnly` specifying a 3-dimensional point, expressed in meters, describing the translation component of the transform. The `w` property is always `1.0`.

`XRRigidTransform.orientation` Read only

A `DOMPointReadOnly` which contains a unit quaternion describing the rotational component of the transform. As a unit quaternion, its length is always normalized to `1.0`.

`XRRigidTransform.matrix` Read only

Returns the transform matrix in the form of a 16-member `Float32Array`. See the section Matrix format for how the array is used to represent a matrix.

`XRRigidTransform.inverse` Read only

Returns a `XRRigidTransform` which is the inverse of this transform. That is, if applied to an object that had been previously transformed by the original transform, it will undo the transform and return the original object.

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

When an `XRRigidTransform` is interpreted, the orientation is always applied to the affected object before the position is applied.

Example
-------

This code snippet creates an `XRRigidTransform` to specify the offset and orientation in relation to the current reference space to use when creating a new reference space. It then requests the first animation frame callback by calling the session's `requestAnimationFrame()` method.

```js
xrSession.requestReferenceSpace(refSpaceType).then((refSpace) => {
  xrReferenceSpace = refSpace;
  xrReferenceSpace = xrReferenceSpace.getOffsetReferenceSpace(
    new XRRigidTransform(viewerStartPosition, cubeOrientation),
  );
  animationFrameRequestID = xrSession.requestAnimationFrame(drawFrame);
});
```

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

| Specification |
| --- |
| WebXR Device API # xrrigidtransform-interface |

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

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


PeriodicWave - Web APIs

PeriodicWave
============

The **`PeriodicWave`** interface defines a periodic waveform that can be used to shape the output of an `OscillatorNode`.

`PeriodicWave` has no inputs or outputs; it is used to define custom oscillators when calling `OscillatorNode.setPeriodicWave()`. The `PeriodicWave` itself is created/returned by `BaseAudioContext.createPeriodicWave`.

Constructor
-----------

`PeriodicWave()`

Creates a new `PeriodicWave` object instance using the default values for all properties. If you wish to establish custom property values at the outset, use the `BaseAudioContext.createPeriodicWave` factory method instead.

Instance properties
-------------------

None; also, `PeriodicWave` doesn't inherit any properties.

Instance methods
----------------

None; also, `PeriodicWave` doesn't inherit any methods.

Example
-------

See `BaseAudioContext.createPeriodicWave` for simple example code that shows how to create a `PeriodicWave` object containing a simple sine wave.

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

| Specification |
| --- |
| Web Audio API # PeriodicWave |

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

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

See also
--------

* Using the Web Audio API


console - Web APIs

console
=======

The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). The specifics of how it works vary from browser to browser or server runtimes (Node.js, for example), but there is a *de facto* set of features that are typically provided.

The `console` object can be accessed from any global object. `Window` on browsing scopes and `WorkerGlobalScope` as specific variants in workers via the property console. It's exposed as `Window.console`, and can be referenced as `console`. For example:

```js
console.log("Failed to open the specified link");
```

This page documents the Methods available on the `console` object and gives a few Usage examples.

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

**Note:** Certain online IDEs and editors may implement the console API differently than the browsers. As a result, certain functionality of the console API, such as the timer methods, may not be outputted in the console of online IDEs or editors. Always open your browser's DevTools console to see the logs as shown in this documentation.

Instance methods
----------------

`console.assert()`

Log a message and stack trace to console if the first argument is `false`.

`console.clear()`

Clear the console.

`console.count()`

Log the number of times this line has been called with the given label.

`console.countReset()`

Resets the value of the counter with the given label.

`console.debug()`

Outputs a message to the console with the log level `debug`.

`console.dir()`

Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.

`console.dirxml()`

Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.

`console.error()`

Outputs an error message. You may use string substitution and additional arguments with this method.

`console.exception()`
Non-standard

Deprecated

An alias for `console.error()`.

`console.group()`

Creates a new inline group, indenting all following output by another level. To move back out a level, call `console.groupEnd()`.

`console.groupCollapsed()`

Creates a new inline group, indenting all following output by another level. However, unlike `console.group()` this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call `console.groupEnd()`.

`console.groupEnd()`

Exits the current inline group.

`console.info()`

Informative logging of information. You may use string substitution and additional arguments with this method.

`console.log()`

For general output of logging information. You may use string substitution and additional arguments with this method.

`console.profile()`
Non-standard

Starts the browser's built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.

`console.profileEnd()`
Non-standard

Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).

`console.table()`

Displays tabular data as a table.

`console.time()`

Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.

`console.timeEnd()`

Stops the specified timer and logs the elapsed time in milliseconds since it started.

`console.timeLog()`

Logs the value of the specified timer to the console.

`console.timeStamp()`
Non-standard

Adds a marker to the browser performance tool's timeline (Chrome or Firefox).

`console.trace()`

Outputs a stack trace.

`console.warn()`

Outputs a warning message. You may use string substitution and additional arguments with this method.

Examples
--------

### Outputting text to the console

The console's most frequently used feature is logging text and other data. There are several categories of output you can generate using the `console.log()`, `console.info()`, `console.warn()`, `console.error()`, or `console.debug()` methods. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to view only the kinds of output that interest you.

There are two ways to use each of the output methods:

* Pass in a variable number of arguments whose string representations get concatenated into one string, then output to the console.
* Pass in a string containing zero or more substitution strings followed by a variable number of arguments to replace them.

#### Outputting a single object

The simplest way to use the logging methods is to output a single object:

```js
const someObject = { str: "Some text", id: 5 };
console.log(someObject);
```

The output looks something like this:
```

{str:"Some text", id:5}
```

#### Outputting multiple objects

You can also output multiple objects by listing them when calling the logging method, like this:

```js
const car = "Dodge Charger";
const someObject = { str: "Some text", id: 5 };
console.info("My first car was a", car, ". The object is:", someObject);
```

The output will look like this:
```

My first car was a Dodge Charger. The object is: {str:"Some text", id:5}
```

#### Using string substitutions

When passing a string to one of the `console` object's methods that accepts a string (such as `console.log()`), you may use these substitution strings:

`%o` or `%O`

Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.

`%d` or `%i`

Outputs an integer. Number formatting is supported, for example `console.log("Foo %.2d", 1.1)` will output the number as two significant figures with a leading 0: `Foo 01`.

`%s`

Outputs a string.

`%f`

Outputs a floating-point value. Formatting is supported, for example `console.log("Foo %.2f", 1.1)` will output the number to 2 decimal places: `Foo 1.10`.

**Note:** Precision formatting doesn't work in Chrome.

Each of these pulls the next argument after the format string off the parameter list. For example:

```js
for (let i = 0; i < 5; i++) {
  console.log("Hello, %s. You've called me %d times.", "Bob", i + 1);
}
```

The output looks like this:
```

Hello, Bob. You've called me 1 times.
Hello, Bob. You've called me 2 times.
Hello, Bob. You've called me 3 times.
Hello, Bob. You've called me 4 times.
Hello, Bob. You've called me 5 times.
```

#### Styling console output

You can use the `%c` directive to apply a CSS style to console output:

```js
console.log(
  "This is %cMy stylish message",
  "color: yellow; font-style: italic; background-color: blue;padding: 2px",
);
```

The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.

![Styled Text in Firefox console](/en-US/docs/Web/API/console/css-styling.png)

You may use `%c` multiple times:

```js
console.log(
  "Multiple styles: %cred %corange",
  "color: red",
  "color: orange",
  "Additional unformatted message",
);
```

The properties usable along with the `%c` syntax are as follows (at least, in Firefox — they may differ in other browsers):

* `background` and its longhand equivalents
* `border` and its longhand equivalents
* `border-radius`
* `box-decoration-break`
* `box-shadow`
* `clear` and `float`
* `color`
* `cursor`
* `display`
* `font` and its longhand equivalents
* `line-height`
* `margin`
* `outline` and its longhand equivalents
* `padding`
* `text-*` properties such as `text-transform`
* `white-space`
* `word-spacing` and `word-break`
* `writing-mode`

**Note:** The console message behaves like an inline element by default. To see the effects of `padding`, `margin`, etc. you should set it to for example `display: inline-block`.

### Using groups in the console

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call `console.group()`. The `console.groupCollapsed()` method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

To exit the current group, call `console.groupEnd()`. For example, given this code:

```js
console.log("This is the outer level");
console.group("First group");
console.log("In the first group");
console.group("Second group");
console.log("In the second group");
console.warn("Still in the second group");
console.groupEnd();
console.log("Back to the first group");
console.groupEnd();
console.debug("Back to the outer level");
```

The output looks like this:

![Demo of nested groups in Firefox console](/en-US/docs/Web/API/console/console_groups_demo.png)

### Timers

You can start a timer to calculate the duration of a specific operation. To start one, call the `console.time()` method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the `console.timeEnd()` method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

For example, given this code:

```js
console.time("answer time");
alert("Click to continue");
console.timeLog("answer time");
alert("Do a bunch of other stuff…");
console.timeEnd("answer time");
```

Will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console:

![Time log in Firefox console](/en-US/docs/Web/API/console/console-timelog.png)

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

### Stack traces

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call `console.trace()`. Given code like this:

```js
function foo() {
  function bar() {
    console.trace();
  }
  bar();
}

foo();
```

The output in the console looks something like this:

![Stack trace in Firefox console](/en-US/docs/Web/API/console/api-trace2.png)

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

| Specification |
| --- |
| Console Standard # console-namespace |

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

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

Notes
-----

* At least in Firefox, if a page defines a `console` object, that object overrides the one built into Firefox.
See also
--------

* Firefox Developer Tools
* Web console — how the Web console in Firefox handles console API calls
* about:debugging — how to see console output when the debugging target is a mobile device
### Other implementations

* Google Chrome DevTools
* Microsoft Edge DevTools
* Safari Web Inspector


ResizeObserverSize - Web APIs

ResizeObserverSize
==================

The **`ResizeObserverSize`** interface of the `Resize Observer API` is used by the `ResizeObserverEntry` interface to access the box sizing properties of the element being observed.

**Note:** In multi-column layout, which is a fragmented context, the sizing returned by `ResizeObserverSize` will be the size of the first column.

Instance properties
-------------------

`ResizeObserverSize.blockSize` Read only

The length of the observed element's border box in the block dimension. For boxes with a horizontal `writing-mode`, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width.

`ResizeObserverSize.inlineSize` Read only

The length of the observed element's border box in the inline dimension. For boxes with a horizontal `writing-mode`, this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height.

**Note:** For more explanation of writing modes and block and inline dimensions, read Handling different text directions.

Examples
--------

In this example the `ResizeObserverEntry.contentBoxSize` property returns a `ResizeObserverSize` object. This is an array containing the sizing information for the content box of the observed element.

```js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    console.log(entry.contentBoxSize[0]); // a ResizeObserverSize
  }
});

resizeObserver.observe(divElem);
```

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

| Specification |
| --- |
| Resize Observer # resizeobserversize |

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

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


NetworkInformation - Web APIs

NetworkInformation
==================

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

 The **`NetworkInformation`** interface of the Network Information API provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes.
 The `NetworkInformation` interface cannot be instantiated. It is instead accessed through the `connection` property of the `Navigator` interface.

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

EventTarget

NetworkInformationInstance properties
-------------------

*This interface also inherits properties of its parent, `EventTarget`.*

`NetworkInformation.downlink` Read only
Experimental

Returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds.

`NetworkInformation.downlinkMax` Read only
Experimental

Returns the maximum downlink speed, in megabits per second (Mbps), for the underlying connection technology.

`NetworkInformation.effectiveType` Read only
Experimental

Returns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'. This value is determined using a combination of recently observed round-trip time and downlink values.

`NetworkInformation.rtt` Read only
Experimental

Returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds.

`NetworkInformation.saveData` Read only
Experimental

Returns `true` if the user has set a reduced data usage option on the user agent.

`NetworkInformation.type` Read only
Experimental

Returns the type of connection a device is using to communicate with the network. It will be one of the following values:

* `bluetooth`
* `cellular`
* `ethernet`
* `none`
* `wifi`
* `wimax`
* `other`
* `unknown`

Instance methods
----------------

*This interface also inherits methods of its parent, `EventTarget`.*

Events
------

`change`
Experimental

The event that's fired when connection information changes.

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

| Specification |
| --- |
| Network Information API # networkinformation-interface |

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

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

See also
--------

* Online and offline events


TaskSignal - Web APIs

TaskSignal
==========

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

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

* Learn more
* See full compatibility
* Report feedback
The **`TaskSignal`** interface of the Prioritized Task Scheduling API represents a signal object that allows you to communicate with a prioritized task, and abort it or change the priority (if required) via a `TaskController` object.

 An object of this type is created, and associated with, a `TaskController`.
 The initial priority of the signal may be set by specifying it as an argument to the `TaskController()` constructor (by default it is `"user-visible"`).
 The priority can be changed by calling `TaskController.setPriority()` on the controller.

 The signal may be passed as the `options.signal` argument in `Scheduler.postTask()`, after which it's associated controller can be used to abort the task.
 If the task priority is mutable, the controller can also be used to change the task's priority.
 Abortable tasks that do not need the priority to change may instead specify an `AbortSignal` as the `options.signal` argument.

EventTarget

AbortSignal

TaskSignalInstance properties
-------------------

*The `TaskSignal` interface also inherits properties from its parent interface, `AbortSignal`.*

`TaskSignal.priority` Read only

Returns the priority of the signal.

Static methods
--------------

*The `TaskSignal` interface inherits methods from its parent interface, `AbortSignal`.*

`TaskSignal.any()`
Experimental

Returns an **`TaskSignal`** that aborts when any of the given abort signals abort.

Instance methods
----------------

*The `TaskSignal` interface inherits methods from its parent interface, `AbortSignal`.*

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

`prioritychange`

 Fired when the priority is changed.
 This is triggered by calling `TaskController.setPriority()` on the associated controller.

Examples
--------

Examples for how the `TaskSignal` is created and used for prioritizing and aborting tasks can be found here:

* Prioritized Task Scheduling API > Examples
* `TaskController` > Examples
* `TaskSignal: prioritychange` event > Examples
Specifications
--------------

| Specification |
| --- |
| Prioritized Task Scheduling # tasksignal |

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

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


PushManager - Web APIs

PushManager
===========

The **`PushManager`** interface of the Push API provides a way to receive notifications from third-party servers as well as request URLs for push notifications.

This interface is accessed via the `ServiceWorkerRegistration.pushManager` property.

Static properties
-----------------

`PushManager.supportedContentEncodings`

Returns an array of supported content codings that can be used to encrypt the payload of a push message.

Instance methods
----------------

`PushManager.getSubscription()`

Retrieves an existing push subscription. It returns a `Promise` that resolves to a `PushSubscription` object containing details of an existing subscription. If no existing subscription exists, this resolves to a `null` value.

`PushManager.permissionState()`

Returns a `Promise` that resolves to the permission state of the current `PushManager`, which will be one of `'granted'`, `'denied'`, or `'prompt'`.

`PushManager.subscribe()`

Subscribes to a push service. It returns a `Promise` that resolves to a `PushSubscription` object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription.

### Deprecated methods

`PushManager.hasPermission()`
Deprecated

Returns a `Promise` that resolves to the `PushPermissionStatus` of the requesting webapp, which will be one of `granted`, `denied`, or `default`. Replaced by `PushManager.permissionState()`.

`PushManager.register()`
Deprecated

Subscribes to a push subscription. Replaced by `PushManager.subscribe()`.

`PushManager.registrations()`
Deprecated

Retrieves existing push subscriptions. Replaced by `PushManager.getSubscription()`.

`PushManager.unregister()`
Deprecated

Unregisters and deletes a specified subscription endpoint. In the updated API, a subscription is unregistered by calling the `PushSubscription.unsubscribe()` method.

Example
-------

```js
this.onpush = (event) => {
  console.log(event.data);
  // From here we can write the data to IndexedDB, send it to any open
  // windows, display a notification, etc.
};

navigator.serviceWorker
  .register("serviceworker.js")
  .then((serviceWorkerRegistration) => {
    serviceWorkerRegistration.pushManager.subscribe().then(
      (pushSubscription) => {
        console.log(pushSubscription.endpoint);
        // The push subscription details needed by the application
        // server are now available, and can be sent to it using,
        // for example, the fetch() API.
      },
      (error) => {
        console.error(error);
      },
    );
  });
```

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

| Specification |
| --- |
| Push API # pushmanager-interface |

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

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

See also
--------

* Push API
* Service Worker API


OffscreenCanvas - Web APIs

OffscreenCanvas
===============

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

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

* Learn more
* See full compatibility
* Report feedback

 When using the `<canvas>` element or the Canvas API, rendering, animation, and user interaction usually happen on the main execution thread of a web application.
 The computation relating to canvas animations and rendering can have a significant impact on application performance.

 The **`OffscreenCanvas`** interface provides a canvas that can be rendered off screen, decoupling the DOM and the Canvas API so that the `<canvas>` element is no longer entirely dependent on the DOM.
 Rendering operations can also be run inside a worker context, allowing you to run some tasks in a separate thread and avoid heavy work on the main thread.

`OffscreenCanvas` is a transferable object.

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

EventTarget

OffscreenCanvasConstructors
------------

`OffscreenCanvas()`

`OffscreenCanvas` constructor. Creates a new `OffscreenCanvas` object.

Instance properties
-------------------

`OffscreenCanvas.height`

The height of the offscreen canvas.

`OffscreenCanvas.width`

The width of the offscreen canvas.

Instance methods
----------------

`OffscreenCanvas.getContext()`

Returns a rendering context for the offscreen canvas.

`OffscreenCanvas.convertToBlob()`

Creates a `Blob` object representing the image contained in the canvas.

`OffscreenCanvas.transferToImageBitmap()`

Creates an `ImageBitmap` object from the most recently rendered image of the `OffscreenCanvas`. See the `API description` for important notes on managing this `ImageBitmap`.

Examples
--------

### Synchronous display of frames produced by an `OffscreenCanvas`

One way to use the `OffscreenCanvas` API is to use a rendering context that has been obtained from an `OffscreenCanvas` object to generate new frames. Once a new frame has finished rendering in this context, the `transferToImageBitmap()` method can be called to save the most recent rendered image. This method returns an `ImageBitmap` object, which can be used in a variety of Web APIs and also in a second canvas without creating a transfer copy.

To display the `ImageBitmap`, you can use an `ImageBitmapRenderingContext` context, which can be created by calling `canvas.getContext("bitmaprenderer")` on a (visible) canvas element. This context only provides functionality to replace the canvas's contents with the given `ImageBitmap`. A call to `ImageBitmapRenderingContext.transferFromImageBitmap()` with the previously rendered and saved `ImageBitmap` from the OffscreenCanvas, will display the `ImageBitmap` on the canvas and transfer its ownership to the canvas. A single `OffscreenCanvas` may transfer frames into an arbitrary number of other `ImageBitmapRenderingContext` objects.

Given these two `<canvas>` elements

```html
<canvas id="one"></canvas> <canvas id="two"></canvas>
```

the following code will provide the rendering using `OffscreenCanvas` as described above.

```js
const one = document.getElementById("one").getContext("bitmaprenderer");
const two = document.getElementById("two").getContext("bitmaprenderer");

const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");

// Perform some drawing for the first canvas using the gl context
const bitmapOne = offscreen.transferToImageBitmap();
one.transferFromImageBitmap(bitmapOne);

// Perform some more drawing for the second canvas
const bitmapTwo = offscreen.transferToImageBitmap();
two.transferFromImageBitmap(bitmapTwo);
```

### Asynchronous display of frames produced by an `OffscreenCanvas`

Another way to use the `OffscreenCanvas` API, is to call `transferControlToOffscreen()` on a `<canvas>` element, either on a worker or the main thread, which will return an `OffscreenCanvas` object from an `HTMLCanvasElement` object from the main thread. Calling `getContext()` will then obtain a rendering context from that `OffscreenCanvas`.

The `main.js` script (main thread) may look like this:

```js
const htmlCanvas = document.getElementById("canvas");
const offscreen = htmlCanvas.transferControlToOffscreen();

const worker = new Worker("offscreencanvas.js");
worker.postMessage({ canvas: offscreen }, [offscreen]);
```

While the `offscreencanvas.js` script (worker thread) can look like this:

```js
onmessage = (evt) => {
  const canvas = evt.data.canvas;
  const gl = canvas.getContext("webgl");
  // Perform some drawing using the gl context
};
```

It's also possible to use `requestAnimationFrame()` in workers:

```js
onmessage = (evt) => {
  const canvas = evt.data.canvas;
  const gl = canvas.getContext("webgl");

  function render(time) {
    // Perform some drawing using the gl context
    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);
};
```

For a full example, see the OffscreenCanvas example source on GitHub or run the OffscreenCanvas example live.

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

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

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

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

See also
--------

* `CanvasRenderingContext2D`
* `OffscreenCanvasRenderingContext2D`
* `ImageBitmap`
* `ImageBitmapRenderingContext`
* `HTMLCanvasElement.transferControlToOffscreen()`
* `requestAnimationFrame()`
* WebGL Off the Main Thread – Mozilla Hacks (2016)


FileSystemSyncAccessHandle - Web APIs

FileSystemSyncAccessHandle
==========================

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

The **`FileSystemSyncAccessHandle`** interface of the File System API represents a synchronous handle to a file system entry.

This class is only accessible inside dedicated Web Workers (so that its methods do not block execution on the main thread) for files within the origin private file system, which is not visible to end-users.

As a result, its methods are not subject to the same security checks as methods running on files within the user-visible file system, and so are much more performant. This makes them suitable for significant, large-scale file updates such as SQLite database modifications.

The interface is accessed through the `FileSystemFileHandle.createSyncAccessHandle()` method.

**Note:** In earlier versions of the spec, `close()`, `flush()`, `getSize()`, and `truncate()` were wrongly specified as asynchronous methods, and older versions of some browsers implement them in this way. However, all current browsers that support these methods implement them as synchronous methods.

Instance properties
-------------------

None.

Instance methods
----------------

`close()`

Closes an open synchronous file handle, disabling any further operations on it and releasing the exclusive lock previously put on the file associated with the file handle.

`flush()`

Persists any changes made to the file associated with the handle via the `write()` method to disk.

`getSize()`

Returns the size of the file associated with the handle in bytes.

`read()`

Reads the content of the file associated with the handle into a specified buffer, optionally at a given offset.

`truncate()`

Resizes the file associated with the handle to a specified number of bytes.

`write()`

Writes the content of a specified buffer to the file associated with the handle, optionally at a given offset.

Examples
--------

The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:

* Creates a synchronous file access handle.
* Gets the size of the file and creates an `ArrayBuffer` to contain it.
* Reads the file contents into the buffer.
* Encodes the message and writes it to the end of the file.
* Persists the changes to disk and closes the access handle.

```js
onmessage = async (e) => {
  // Retrieve message sent to work from main script
  const message = e.data;

  // Get handle to draft file
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Get size of the file.
  const fileSize = accessHandle.getSize();
  // Read file content to a buffer.
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // Write the message to the end of the file.
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
};
```

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

| Specification |
| --- |
| File System Standard # api-filesystemsyncaccesshandle |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


PerformanceEventTiming - Web APIs

PerformanceEventTiming
======================

The `PerformanceEventTiming` interface of the Event Timing API provides insights into the latency of certain event types triggered by user interaction.

Description
-----------

This API enables visibility into slow events by providing event timestamps and duration for certain event types (see below). For example, you can monitor the time between a user action and the start of its event handler, or the time an event handler takes to run.

This API is particularly useful for measuring the first input delay (FID): the time from the point when a user first interacts with your app to the point when the browser is actually able to respond to that interaction.

You typically work with `PerformanceEventTiming` objects by creating a `PerformanceObserver` instance and then calling its `observe()` method, passing in `"event"` or `"first-input"` as the value of the `type` option. The `PerformanceObserver` object's callback will then be called with a list of `PerformanceEventTiming` objects which you can analyze. See the example below for more.

 By default, `PerformanceEventTiming` entries are exposed when their `duration` is 104ms or greater. Research suggests that user input that is not handled within 100ms is considered slow and 104ms is the first multiple of 8 greater than 100ms (for security reasons, this API is rounded to the nearest multiple of 8ms).
 However, you can set the `PerformanceObserver` to a different threshold using the `durationThreshold` option in the `observe()` method.

This interface inherits methods and properties from its parent, `PerformanceEntry`:

PerformanceEntry

PerformanceEventTiming### Events exposed

The following event types are exposed by the Event Timing API:

|  |  |
| --- | --- |
| Click events | `auxclick`,
 `click`,
 `contextmenu`,
 `dblclick` |
| Composition events | `compositionend`,
 `compositionstart`,
 `compositionupdate` |
| Drag & drop events | `dragend`,
 `dragenter`,
 `dragleave`,
 `dragover`,
 `dragstart`,
 `drop` |
| Input events | `beforeinput`,
 `input` |
| Keyboard events | `keydown`,
 `keypress`,
 `keyup` |
| Mouse events | `mousedown`,
 `mouseenter`,
 `mouseleave`,
 `mouseout`,
 `mouseover`,
 `mouseup` |
| Pointer events | `pointerover`,
 `pointerenter`,
 `pointerdown`,
 `pointerup`,
 `pointercancel`,
 `pointerout`,
 `pointerleave`,
 `gotpointercapture`,
 `lostpointercapture` |
| Touch events | `touchstart`,
 `touchend`,
 `touchcancel` |

 Note that the following events are not included in the list because they are continuous events and no meaningful event counts or performance metrics can be obtained at this point: `mousemove`, `pointermove`,
 `pointerrawupdate`, `touchmove`, `wheel`, `drag`.

To get a list of all exposed events, you can also look up keys in the `performance.eventCounts` map:

```js
const exposedEventsList = [...performance.eventCounts.keys()];
```

Constructor
-----------

This interface has no constructor on its own. See the example below for how to typically get the information the `PerformanceEventTiming` interface holds.

Instance properties
-------------------

This interface extends the following `PerformanceEntry` properties for event timing performance entry types by qualifying them as follows:

`PerformanceEntry.duration` Read only

Returns a `DOMHighResTimeStamp` representing the time from `startTime` to the next rendering paint (rounded to the nearest 8ms).

`PerformanceEntry.entryType` Read only

Returns `"event"` (for long events) or `"first-input"` (for the first user interaction).

`PerformanceEntry.name` Read only

Returns the associated event's type.

`PerformanceEntry.startTime` Read only

Returns a `DOMHighResTimeStamp` representing the associated event's `timestamp` property. This is the time the event was created and can be considered as a proxy for the time the user interaction occurred.

This interface also supports the following properties:

`PerformanceEventTiming.cancelable` Read only

Returns the associated event's `cancelable` property.

`PerformanceEventTiming.interactionId` Read only
Experimental

Returns the ID that uniquely identifies the user interaction which triggered the associated event.

`PerformanceEventTiming.processingStart` Read only

Returns a `DOMHighResTimeStamp` representing the time at which event dispatch started. To measure the time between a user action and the time the event handler starts to run, calculate `processingStart-startTime`.

`PerformanceEventTiming.processingEnd` Read only

Returns a `DOMHighResTimeStamp` representing the time at which the event dispatch ended. To measure the time the event handler took to run, calculate `processingEnd-processingStart`.

`PerformanceEventTiming.target` Read only

Returns the associated event's last target, if it is not removed.

Instance methods
----------------

`PerformanceEventTiming.toJSON()`

Returns a JSON representation of the `PerformanceEventTiming` object.

Examples
--------

### Getting event timing information

To get event timing information, create a `PerformanceObserver` instance and then call its `observe()` method, passing in `"event"` or `"first-input"` as the value of the `type` option. You also need to set `buffered` to `true` to get access to events the user agent buffered while constructing the document. The `PerformanceObserver` object's callback will then be called with a list of `PerformanceEventTiming` objects which you can analyze.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    // Full duration
    const duration = entry.duration;

    // Input delay (before processing event)
    const delay = entry.processingStart - entry.startTime;

    // Synchronous event processing time
    // (between start and end dispatch)
    const eventHandlerTime = entry.processingEnd - entry.processingStart;
    console.log(`Total duration: ${duration}`);
    console.log(`Event delay: ${delay}`);
    console.log(`Event handler duration: ${eventHandlerTime}`);
  });
});

// Register the observer for events
observer.observe({ type: "event", buffered: true });
```

You can also set a different `durationThreshold`. The default is 104ms and the minimum possible duration threshold is 16ms.

```js
observer.observe({ type: "event", durationThreshold: 16, buffered: true });
```

### Reporting the First Input Delay (FID)

The first input delay or FID, measures the time from when a user first interacts with a page (i.e. when they click a link or tap on a button) to the time when the browser is actually able to begin processing event handlers in response to that interaction.

```js
// Keep track of whether (and when) the page was first hidden, see:
// https://github.com/w3c/page-visibility/issues/29
// NOTE: ideally this check would be performed in the document <head>
// to avoid cases where the visibility state changes before this code runs.
let firstHiddenTime = document.visibilityState === "hidden" ? 0 : Infinity;
document.addEventListener(
  "visibilitychange",
  (event) => {
    firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp);
  },
  { once: true },
);

// Sends the passed data to an analytics endpoint. This code
// uses `/analytics`; you can replace it with your own URL.
function sendToAnalytics(data) {
  const body = JSON.stringify(data);
  // Use `navigator.sendBeacon()` if available,
  // falling back to `fetch()`.
  (navigator.sendBeacon && navigator.sendBeacon("/analytics", body)) ||
    fetch("/analytics", { body, method: "POST", keepalive: true });
}

// Use a try/catch instead of feature detecting `first-input`
// support, since some browsers throw when using the new `type` option.
// https://webkit.org/b/209216
try {
  function onFirstInputEntry(entry) {
    // Only report FID if the page wasn't hidden prior to
    // the entry being dispatched. This typically happens when a
    // page is loaded in a background tab.
    if (entry.startTime < firstHiddenTime) {
      const fid = entry.processingStart - entry.startTime;

      // Report the FID value to an analytics endpoint.
      sendToAnalytics({ fid });
    }
  }

  // Create a PerformanceObserver that calls
  // `onFirstInputEntry` for each entry.
  const po = new PerformanceObserver((entryList) => {
    entryList.getEntries().forEach(onFirstInputEntry);
  });

  // Observe entries of type `first-input`, including buffered entries,
  // i.e. entries that occurred before calling `observe()` below.
  po.observe({
    type: "first-input",
    buffered: true,
  });
} catch (e) {
  // Do nothing if the browser doesn't support this API.
}
```

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

| Specification |
| --- |
| Event Timing API # sec-performance-event-timing |

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

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


SVGMPathElement - Web APIs

SVGMPathElement
===============

The **`SVGMPathElement`** interface corresponds to the `<mpath>` element.

EventTarget

Node

Element

SVGElement

SVGMPathElementInstance properties
-------------------

*This interface also inherits properties from its parent, `SVGElement`.*

`SVGMPathElement.href` Read only

An `SVGAnimatedString` that corresponds to the `href` or `xlink:href`
Deprecated
 attribute of the given `<mpath>` element.

Instance methods
----------------

*This interface doesn't implement any specific methods, but inherits methods from its parent interface, `SVGElement`.*

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

| Specification |
| --- |
| SVG Animations Level 2 # InterfaceSVGMPathElement |

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

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


CompressionStream - Web APIs

CompressionStream
=================

The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data.

Constructor
-----------

`CompressionStream()`

Creates a new `CompressionStream`

Instance properties
-------------------

`CompressionStream.readable`

Returns the `ReadableStream` instance controlled by this object.

`CompressionStream.writable`

Returns the `WritableStream` instance controlled by this object.

Examples
--------

In this example a stream is compressed using gzip compression.

```js
const compressedReadableStream = inputReadableStream.pipeThrough(
  new CompressionStream("gzip"),
);
```

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

| Specification |
| --- |
| Compression Streams # compression-stream |

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

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


SVGFontFaceElement - Web APIs

SVGFontFaceElement
==================

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

The **`SVGFontFaceElement`** interface corresponds to the `<font-face>` elements.

Object-oriented access to the attributes of the `<font-face>` element via the SVG DOM is not possible.

Instance properties
-------------------

*This interface has no properties but inherits properties from its parent, `SVGElement`.*

Instance methods
----------------

*This interface has no methods but inherits methods from its parent, `SVGElement`.*

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 1.1 (Second Edition) # InterfaceSVGFontFaceElement |

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

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

See also
--------

* `<font-face>`


Screen Wake Lock API - Web APIs

Screen Wake Lock API
====================

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

The **Screen Wake Lock API** provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.

Concepts and usage
------------------

Most devices by default turn off their screen after a specified amount of time to prolong the life of the hardware. Modern devices do this to save on battery power. Whilst this is a useful feature, some applications need the screen to stay awake to be their most useful.

The Screen Wake Lock API prevents the screen from turning off, dimming or locking. It allows for a simple platform-based solution for visible (active) documents to acquire the platform screen wake lock.

There are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a QR/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake).

You acquire a `WakeLockSentinel` object by calling the `navigator.wakeLock.request()` `Promise`-based method that resolves if the platform allows it. A request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible.

The sentinel is attached to the underlying system wake lock. It can be released by the system, again if the battery power is too low or the document is not active or visible. It can also be released manually via the `WakeLockSentinel.release()` method. It is good practice to store a reference to the sentinel object to control release later and also to reacquire the lock if need be.

The Screen Wake Lock API should be used to keep the screen on to benefit usability. It's a good idea to show some feedback on the interface to show if wake lock is active and a way for the user to disable it if they wish.

Interfaces
----------

`WakeLock`

Prevents device screens from dimming or locking when an application needs to keep running.

`WakeLockSentinel`

Provides a handle to the underlying platform wake lock and if referenced can be manually released and reacquired. Get an instance of the object by calling `WakeLock.request`.

### Extensions to other interfaces

`Navigator.wakelock` Read only

Returns a `WakeLock` object instance, from which all other functionality can be accessed.

Examples
--------

### Feature detection

This code checks for wake lock support and updates the UI accordingly.

```js
if ("wakeLock" in navigator) {
  isSupported = true;
  statusElem.textContent = "Screen Wake Lock API supported!";
} else {
  wakeButton.disabled = true;
  statusElem.textContent = "Wake lock is not supported by this browser.";
}
```

### Requesting a wake lock

The following example demonstrates how to request a `WakeLockSentinel` object. The `WakeLock.request` method is `Promise`-based and so we can create an asynchronous function, which in turn updates the UI to reflect the wake lock is active.

```js
// Create a reference for the Wake Lock.
let wakeLock = null;

// create an async function to request a wake lock
try {
  wakeLock = await navigator.wakeLock.request("screen");
  statusElem.textContent = "Wake Lock is active!";
} catch (err) {
  // The Wake Lock request has failed - usually system related, such as battery.
  statusElem.textContent = `${err.name}, ${err.message}`;
}
```

### Releasing wake lock

The following example shows how to release the previously acquired wake lock.

```js
wakeLock.release().then(() => {
  wakeLock = null;
});
```

### Listening for wake lock release

This example updates the UI if the wake lock has been released for any reason (such as navigating away from the active window/tab).

```js
wakeLock.addEventListener("release", () => {
  // the wake lock has been released
  statusElem.textContent = "Wake Lock has been released";
});
```

### Reacquiring a wake lock

The following code reacquires the wake lock should the visibility of the document change and the wake lock is released.

```js
document.addEventListener("visibilitychange", async () => {
  if (wakeLock !== null && document.visibilityState === "visible") {
    wakeLock = await navigator.wakeLock.request("screen");
  }
});
```

### Putting it all together

You can find the complete code on GitHub here. The demo uses a button to acquire a wake lock and also release it, which in turn updates the UI. The UI also updates if the wake lock is released automatically for any reason. There's a checkbox which when checked, will automatically reacquire the wake lock if the document's visibility state changes and becomes visible again.

Performance considerations
--------------------------

* Release the screen wake lock when user ends activity that required always-on screen. For example, a ticketing app which uses QR codes to transmit ticket information, might acquire screen wake lock when the QR code is displayed (so that code is successfully scanned) but release afterwards. A presentation app might hold the lock only while a presentation is active, but not when presentation is being edited.
* If your app is performing long-running downloads, consider using background fetch.
* If your app is synchronizing data from a remote server, consider using background sync.
* Only active documents can acquire screen wake locks and previously acquired locks are automatically released when document becomes inactive. Therefore make sure to re-acquire screen wake lock if necessary when document becomes active (listen for visibilitychange event).
Security considerations
-----------------------

 Access to the Screen Wake Lock API is controlled by the Permissions Policy directive `screen-wake-lock`.
 The default allowlist for `screen-wake-lock` is `self`.

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

| Specification |
| --- |
| Screen Wake Lock API  |

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

### api.WakeLock

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

### api.WakeLockSentinel

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

See also
--------

* Stay awake with the Screen Wake Lock API
* A Screen Wake Lock API demo on glitch


DOMStringList - Web APIs

DOMStringList
=============

The **`DOMStringList`** interface is a legacy type returned by some APIs and represents a non-modifiable list of strings (`DOMString`). Modern APIs use `Array` objects (in WebIDL: `sequence<DOMString>`) instead.

This interface is used in IndexedDB and in the `Location` API:

* `IDBDatabase.objectStoreNames`
* `IDBObjectStore.indexNames`
* `Location.ancestorOrigins`
Instance properties
-------------------

`DOMStringList.length` Read only

Returns the size of the list.

Instance methods
----------------

`DOMStringList.item()`

Returns a string from the list with the given index.

`DOMStringList.contains()`

Returns a boolean indicating whether the given string is in the list.

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

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

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

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