recursal/MDN huggingface dataset:
Functions and classes available to Web Workers
==============================================

In addition to the standard JavaScript set of functions (such as `String`, `Array`, `Object`, `JSON`, etc.), there are a variety of functions available from the DOM to workers. This article provides a list of those.

Worker Contexts & Functions
---------------------------

**Workers run in a different global context than the current window!** While `Window` is not directly available to workers, many of the same methods are defined in a shared mixin (`WindowOrWorkerGlobalScope`), and made available to workers through their own `WorkerGlobalScope`-derived contexts:

* `DedicatedWorkerGlobalScope` for dedicated workers
* `SharedWorkerGlobalScope` for shared workers
* `ServiceWorkerGlobalScope` for service workers

Some of the functions (a subset) that are common to all workers and to the main thread (from `WindowOrWorkerGlobalScope`) are:

* `atob()`
* `btoa()`
* `clearInterval()`
* `clearTimeout()`
* `createImageBitmap()`
* `dump()` 
Non-standard
* `fetch()`
* `queueMicrotask()`
* `reportError()`
* `setInterval()`
* `setTimeout()`
* `structuredClone()`
* `requestAnimationFrame()` (dedicated workers only)
* `cancelAnimationFrame()` (dedicated workers only)

The following functions are **only** available to workers:

* `WorkerGlobalScope.importScripts()` (all workers)
* `DedicatedWorkerGlobalScope.postMessage` (dedicated workers only)
Web APIs available in workers
-----------------------------

**Note:** If a listed API is supported by a platform in a particular version, then it can generally be assumed to be available in web workers. You can also test support for a particular object/function using the site: https://worker-playground.glitch.me/

The following Web APIs are available to workers:

* Background Fetch API
* Background Synchronization API
* Barcode Detection API
* Broadcast Channel API
* Canvas API
* Channel Messaging API
* Console API
* Compression Streams API
* CSS Font Loading API
* `CustomEvent`
* Encoding API (e.g. `TextEncoder`, `TextDecoder`)
* Fetch API
* File API
* File System API
* Idle Detection API
* IndexedDB API
* Media Capabilities API
* Media Source Extensions API (dedicated workers only)
* Network Information API
* Notifications API
* Payment Handler API
* Performance API
* Permissions API
* Prioritized Task Scheduling API
* Push API
* Server-sent events
* Service Worker API
* Streams API
* Trusted Types API
* URL API (e.g. `URL`)
* URL Pattern API
* User-Agent Client Hints API
* WebCodecs API
* Web Crypto API (e.g. `Crypto`)
* Web Locks API
* Web Serial API
* Web Periodic Background Synchronization API
* WebGPU API
* WebUSB API
* WebSockets API
* XMLHttpRequest API

Workers can also spawn other workers, so these APIs are also available:

* `Worker`
* `WorkerGlobalScope`
* `WorkerLocation`
* `WorkerNavigator`
See also
--------

* Using web workers
* `Worker`
The structured clone algorithm
==============================

 The **structured clone algorithm** copies complex JavaScript objects.
 It is used internally when invoking `structuredClone()`, to transfer data between Workers via `postMessage()`, storing objects with IndexedDB, or copying objects for other APIs.

It clones by recursing through the input object while maintaining a map of previously visited references, to avoid infinitely traversing cycles.

Things that don't work with structured clone
--------------------------------------------

* `Function` objects cannot be duplicated by the structured clone algorithm; attempting to throws a `DataCloneError` exception.
* Cloning DOM nodes likewise throws a `DataCloneError` exception.
* Certain object properties are not preserved:
    + The `lastIndex` property of `RegExp` objects is not preserved.
    + Property descriptors, setters, getters, and similar metadata-like features are not duplicated.
     For example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that's the default.
    + The prototype chain is not walked or duplicated.
Supported types
---------------

### JavaScript types

* `Array`
* `ArrayBuffer`
* `Boolean`
* `DataView`
* `Date`
* `Error` types (but see Error types below).
* `Map`
* `Number`
* `Object` objects: but only plain objects (e.g. from object literals).
* Primitive types, except `symbol`.
* `RegExp`: but note that `lastIndex` is not preserved.
* `Set`
* `String`
* `TypedArray`

#### Error types

For `Error` types, the error name must be one of: `Error`, `EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, `URIError` (or will be set to "Error").

Browsers must serialize the properties `name` and `message`, and are expected to serialize other "interesting" properties of the errors such as `stack`, `cause`, etc.

`AggregateError` support is expected to be added to the specification in whatwg/html#5749 (and is already supported in some browsers).

### Web/API types

* `AudioData`
* `Blob`
* `CropTarget`
* `CryptoKey`
* `DOMException`: browsers must serialize the properties `name` and `message`. Other attributes may also be serialized/cloned.
* `DOMMatrix`
* `DOMMatrixReadOnly`
* `DOMPoint`
* `DOMPointReadOnly`
* `DOMQuad`
* `DOMRect`
* `DOMRectReadOnly`
* `File`
* `FileList`
* `FileSystemDirectoryHandle`
* `FileSystemFileHandle`
* `FileSystemHandle`
* `GPUCompilationInfo`
* `GPUCompilationMessage`
* `ImageBitmap`
* `ImageData`
* `RTCCertificate`
* `VideoFrame`
See also
--------

* HTML Specification: Safe passing of structured data
* Transferable objects
* `structuredClone()`
* `window.postMessage()`
* Web Workers
* IndexedDB
Cache: delete() method
======================

 The **`delete()`** method of the `Cache` interface finds the `Cache` entry whose key is the request, and if found, deletes the `Cache` entry and returns a `Promise` that resolves to `true`.
 If no `Cache` entry is found, it resolves to `false`.

Syntax
------


```js
delete(request)
delete(request, options)
```

### Parameters

`request`

 The `Request` you are looking to delete.
 This can be a `Request` object or a URL.


`options` Optional

 An object whose properties control how matching is done in the `delete` operation.
 The available options are:


`ignoreSearch`

 A boolean value that specifies whether the matching process should ignore the query string in the URL.
 If set to `true`, the `?value=bar` part of `http://foo.com/?value=bar` would be ignored when performing a match.
 It defaults to `false`.


`ignoreMethod`

 A boolean value that, when set to
 `true`, prevents matching operations from validating the
 `Request` `HTTP` method (normally only `GET`
 and `HEAD` are allowed.) It defaults to `false`.


`ignoreVary`

 A boolean value that, when set to
 `true,` tells the matching operation not to perform `VARY`
 header matching. In other words, if the URL matches you will get a match
 regardless of whether the `Response` object has a `VARY`
 header. It defaults to `false`.


`cacheName`

A string that represents a specific cache to search within. Note that this option is ignored by `Cache.delete()`.


### Return value

 a `Promise` that resolves to `true` if the cache entry is
 deleted, or `false` otherwise.

Examples
--------


```js
caches.open("v1").then((cache) => {
  cache.delete("/images/image.png").then((response) => {
    someUIUpdateFunction();
  });
});
```

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

| Specification |
| --- |
| Service Workers # cache-delete |

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

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

See also
--------

* Using Service Workers
* `Cache`
* `caches`
Cache: put() method
===================

 The **`put()`** method of the
 `Cache` interface allows key/value pairs to be added to the current
 `Cache` object.

 Often, you will just want to `fetch()`
 one or more requests, then add the result straight to your cache. In such cases you are
 better off using
 `Cache.add()`/`Cache.addAll()`, as
 they are shorthand functions for one or more of these operations.


```js
fetch(url).then((response) => {
  if (!response.ok) {
    throw new TypeError("Bad response status");
  }
  return cache.put(url, response);
});
```


**Note:** `put()` will overwrite any key/value pair
 previously stored in the cache that matches the request.



**Note:** `Cache.add`/`Cache.addAll` do not
 cache responses with `Response.status` values that are not in the 200
 range, whereas `Cache.put` lets you store any request/response pair. As a
 result, `Cache.add`/`Cache.addAll` can't be used to store
 opaque responses, whereas `Cache.put` can.


Syntax
------


```js
put(request, response)
```

### Parameters

`request`

The `Request` object or URL that you want to add to the cache.

`response`

The `Response` you want to match up to the request.

### Return value

A `Promise` that resolves with `undefined`.

### Exceptions

`TypeError`

Returned if the URL scheme is not `http` or `https`.

Examples
--------

 This example is from the MDN simple-service-worker example (see simple-service-worker running live).
 Here we wait for a `FetchEvent` to fire. We construct a custom response
 like so:

1. Check whether a match for the request is found in the `CacheStorage`
 using `CacheStorage.match()`. If so, serve that.
2. If not, open the `v1` cache using `open()`, put the default
 network request in the cache using `Cache.put()` and return a
 clone of the default network request using `return response.clone()`. Clone
 is needed because `put()` consumes the response body.
3. If this fails (e.g., because the network is down), return a fallback response.


```js
let response;
const cachedResponse = caches
  .match(event.request)
  .then((r) => (r !== undefined ? r : fetch(event.request)))
  .then((r) => {
    response = r;
    caches.open("v1").then((cache) => {
      cache.put(event.request, response);
    });
    return response.clone();
  })
  .catch(() => caches.match("/gallery/myLittleVader.jpg"));
```

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

| Specification |
| --- |
| Service Workers # cache-put |

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

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

See also
--------

* Using Service Workers
* `Cache`
* `caches`
Cache: keys() method
====================

 The **`keys()`** method of the `Cache` interface returns a
 `Promise` that resolves to an array of `Request` objects
 representing the keys of the `Cache`.

The requests are returned in the same order that they were inserted.

**Note:** Requests with duplicate URLs but different headers can be
 returned if their responses have the `VARY` header set on them.


Syntax
------


```js
keys()
keys(request)
keys(request, options)
```

### Parameters

`request` Optional

 The `Request` want to return, if a specific key is desired. This can be
 a `Request` object or a URL.


`options` Optional

 An object whose properties control how matching is done in the `keys`
 operation. The available options are:


`ignoreSearch`

 A boolean value that specifies whether the
 matching process should ignore the query string in the URL. If set to
 `true`, the `?value=bar` part of
 `http://foo.com/?value=bar` would be ignored when performing a match.
 It defaults to `false`.


`ignoreMethod`

 A boolean value that, when set to
 `true`, prevents matching operations from validating the
 `Request` `HTTP` method (normally only `GET`
 and `HEAD` are allowed.) It defaults to `false`.


`ignoreVary`

 A boolean value that, when set to
 `true,` tells the matching operation not to perform `VARY`
 header matching. In other words, if the URL matches you will get a match
 regardless of whether the `Response` object has a `VARY`
 header. It defaults to `false`.


`cacheName`

 A string that represents a specific
 cache to search within. Note that this option is ignored by
 `Cache.keys()`.



### Return value

 A `Promise` that resolves to an array of `Request`
 objects.

Examples
--------


```js
caches.open("v1").then((cache) => {
  cache.keys().then((keys) => {
    keys.forEach((request, index, array) => {
      cache.delete(request);
    });
  });
});
```

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

| Specification |
| --- |
| Service Workers # cache-keys |

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

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

See also
--------

* Using Service Workers
* `Cache`
* `caches`
Cache: add() method
===================

The **`add()`** method of the `Cache` interface takes a URL, retrieves it, and adds the resulting response object to the given cache.

The `add()` method is functionally equivalent to the following:


```js
fetch(url).then((response) => {
  if (!response.ok) {
    throw new TypeError("bad response status");
  }
  return cache.add(url);
});
```


For more complex operations, you'll need to use `Cache.put()` directly.

**Note:** `add()` will overwrite any key/value pair previously stored in the cache that matches the request.

Syntax
------


```js
add(request)
```

### Parameters

`request`

A request for the resource you want to add to the cache. This can be a `Request` object or a URL.

This parameter is used as a parameter to the `Request()` constructor, so URLs follow the same rules as for that constructor. In particular, URLs may be relative to the base URL, which is the document's `baseURI` in a window context, or `WorkerGlobalScope.location` in a worker context.

### Return value

A `Promise` that resolves with `undefined`.

### Exceptions

`TypeError`

The URL scheme is not `http` or `https`.

The Response status is not in the 200 range (i.e., not a successful response.) This occurs if the request does not return successfully, but also if the request is a *cross-origin no-cors* request (in which case the reported status is always 0.)

Examples
--------

This code block waits for an `InstallEvent` to fire, then calls `waitUntil()` to handle the install process for the app. This consists of calling `CacheStorage.open` to create a new cache, then using `Cache.add` to add an asset to it.


```js
this.addEventListener("install", (event) => {
  event.waitUntil(caches.open("v1").then((cache) => cache.add("/index.html")));
});
```

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

| Specification |
| --- |
| Service Workers # cache-add |

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

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

See also
--------

* Using Service Workers
* `Cache`
* `caches`
Cache: addAll() method
======================

The **`addAll()`** method of the `Cache` interface takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache. The request objects created during retrieval become keys to the stored response operations.

**Note:** `addAll()` will overwrite any key/value pairs
 previously stored in the cache that match the request, but will fail if a
 resulting `put()` operation would overwrite a previous cache entry stored by the same `addAll()` method.


Syntax
------


```js
addAll(requests)
```

### Parameters

`requests`

An array of requests for the resources you want to add to the cache. These can be `Request` objects or URLs.

These requests are used as parameters to the `Request()` constructor, so URLs follow the same rules as for that constructor. In particular, URLs may be relative to the base URL, which is the document's `baseURI` in a window context, or `WorkerGlobalScope.location` in a worker context.

### Return value

A `Promise` that resolves with `undefined`.

### Exceptions

`TypeError`

The URL scheme is not `http` or `https`.

The Response status is not in the 200 range (i.e., not a successful response.) This occurs if the request does not return successfully, but also if the request is a *cross-origin no-cors* request (in which case the reported status is always 0.)

Examples
--------

 This code block waits for an `InstallEvent` to fire, then runs
 `waitUntil()` to handle the install process for
 the app. This consists of calling `CacheStorage.open` to create a new
 cache, then using `addAll()` to add a series of assets to it.


```js
this.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ]),
      ),
  );
});
```

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

| Specification |
| --- |
| Service Workers # cache-addAll |

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

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

See also
--------

* Using Service Workers
* `Cache`
* `caches`
Cache: matchAll() method
========================

 The **`matchAll()`** method of the `Cache`
 interface returns a `Promise` that resolves to an array of all matching
 responses in the `Cache` object.

Syntax
------


```js
matchAll()
matchAll(request)
matchAll(request, options)
```

### Parameters

`request` Optional

 The `Request` for which you are attempting to find responses in the
 `Cache`. This can be a `Request` object or a URL. If this
 argument is omitted, you will get a copy of all responses in this cache.


`options` Optional

 An options object allowing you to set specific control options for the matching
 performed. The available options are:


`ignoreSearch`

 A boolean value that specifies whether the
 matching process should ignore the query string in the URL. If set to
 `true`, the `?value=bar` part of
 `http://foo.com/?value=bar` would be ignored when performing a match.
 It defaults to `false`.


`ignoreMethod`

 A boolean value that, when set to
 `true`, prevents matching operations from validating the
 `Request` `http` method (normally only `GET`
 and `HEAD` are allowed.) It defaults to `false`.


`ignoreVary`

 A boolean value that when set to
 `true` tells the matching operation not to perform `VARY`
 header matching — i.e. if the URL matches you will get a match regardless of the
 `Response` object having a `VARY` header or not. It
 defaults to `false`.



### Return value

 A `Promise` that resolves to an array of all matching responses in the
 `Cache` object.


**Note:** `Cache.match()` is basically identical to
 `Cache.matchAll()`, except that rather than resolving with an array of all
 matching responses, it resolves with the first matching response only (that is,
 `response[0]`).


Examples
--------

The following example retrieves all responses in the `v1` cache matching the URL `/`, even including potential query parameters. By using `{ ignoreSearch: true }`, using `matchAll` would retrieve `/` as well as `/?value=bar`.

It then logs the number of matching responses.


```js
caches.open("v1").then((cache) => {
  cache.matchAll("/", { ignoreSearch: true }).then((responses) => {
    console.log(`Found ${responses.length} matching responses`);
  });
});
```

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

| Specification |
| --- |
| Service Workers # cache-matchall |

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

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

See also
--------

* Using Service Workers
* `Cache`
* `caches`
SerialPort: open() method
=========================

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

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

The **`open()`** method of the `SerialPort` interface returns a `Promise` that resolves when the port is opened. By default the port is opened with 8 data bits, 1 stop bit and no parity checking. The `baudRate` parameter is required.

Syntax
------


```js
open(options)
```

### Parameters

`options`

An object with any of the following values:

`baudRate`

A positive, non-zero value indicating the baud rate at which serial communication should be established.

`bufferSize` Optional

An unsigned long integer indicating the size of the read and write buffers that are to be established. If not passed, defaults to 255.

`dataBits` Optional

An integer value of 7 or 8 indicating the number of data bits per frame. If not passed, defaults to 8.

`flowControl` Optional

The flow control type, either `"none"` or `"hardware"`. The default value is `"none"`.

`parity` Optional

The parity mode, either `"none"`, `"even"`, or `"odd"`. The default value is `"none"`.

`stopBits` Optional

An integer value of 1 or 2 indicating the number of stop bits at the end of the frame. If not passed, defaults to 1.


### Return value

A `Promise`.

### Exceptions

`InvalidStateError` `DOMException`

Returned if the port is already open.

`NetworkError` `DOMException`

Returned if the attempt to open the port failed.

Examples
--------

Before communicating on a serial port it must be opened. Opening the port allows the site to specify the necessary parameters that control how data is transmitted and received. Developers should check the documentation for the device they are connecting to for the appropriate parameters.


```js
await port.open({ baudRate: 9600 /\* pick your baud rate \*/ });
```

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

| Specification |
| --- |
| Web Serial API # dom-serialport-open |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
SerialPort: getInfo() method
============================

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

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

The **`getInfo()`** method of the `SerialPort` interface returns an object whose properties are the vendor ID and product ID of the device.

Syntax
------


```js
getInfo()
```

### Parameters

None.

### Return value

An object containing the following values.

`usbVendorId`

If the port is part of a USB device, an unsigned short integer that identifies a USB device vendor, otherwise `undefined`.

`usbProductId`

If the port is part of a USB device, an unsigned short integer that identifies a USB device, otherwise `undefined`.

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

| Specification |
| --- |
| Web Serial API # dom-serialport-getinfo |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
SerialPort: writable property
=============================

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

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

The **`writable`** read-only property of the `SerialPort` interface returns a `WritableStream` for sending data to the device connected to the port. Chunks written to this stream must be instances of `ArrayBuffer`, `TypedArray`, or `DataView`. This property is non-null as long as the port is open and has not encountered a fatal error.

Value
-----

A `WritableStream`

Examples
--------

The following example shows how to write a string to a port. A `TextEncoder` converts the string to a `Uint8Array` before transmission.


```js
const encoder = new TextEncoder();
const writer = port.writable.getWriter();
await writer.write(encoder.encode("PING"));
writer.releaseLock();
```

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

| Specification |
| --- |
| Web Serial API # dom-serialport-writable |

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

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