recursal/MDN huggingface dataset:
StorageManager: getDirectory() method
=====================================

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

The **`getDirectory()`** method of the `StorageManager` interface is used to obtain a reference to a `FileSystemDirectoryHandle` object allowing access to a directory and its contents, stored in the origin private file system (OPFS).

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

Syntax
------


```js
getDirectory()
```

### Parameters

None.

### Return value

A `Promise` that fulfills with a `FileSystemDirectoryHandle` object.

### Exceptions

`SecurityError` `DOMException`

Thrown if the user agent is not able to map the requested directory to the local OPFS.

Examples
--------

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

1. Gets a `FileSystemDirectoryHandle` representing the root of the OPFS using `getDirectory()`, storing it in the `root` variable.
2. Gets a file handle using `FileSystemDirectoryHandle.getFileHandle()`.
3. Creates a synchronous file access handle using `FileSystemFileHandle.createSyncAccessHandle()`.
4. Gets the size of the file and creates an `ArrayBuffer` to contain it.
5. Reads and writes to the file.
6. Persists the changes to disk and closes the synchronous 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();
};
```


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

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

| Specification |
| --- |
| File System Standard # dom-storagemanager-getdirectory |

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

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

See also
--------

* `StorageManager`
* `navigator.storage`
* `FileSystemDirectoryHandle`
StorageManager: persisted() method
==================================

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

The **`persisted()`** method of the `StorageManager` interface returns a `Promise` that resolves to `true` if your site's storage bucket is persistent.

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

Syntax
------


```js
persisted()
```

### Parameters

None.

### Returns

A `Promise` that resolves to a `Boolean`.

### Exceptions

`TypeError`

Thrown if obtaining a local storage shelf failed. For example, if the current origin is an opaque origin or if the user has disabled storage.

Example
-------


```js
if (navigator.storage && navigator.storage.persist) {
  navigator.storage.persisted().then((persistent) => {
    if (persistent) {
      console.log("Storage will not be cleared except by explicit user action");
    } else {
      console.log("Storage may be cleared by the UA under storage pressure.");
    }
  });
}
```

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

| Specification |
| --- |
| Storage Standard # dom-storagemanager-persisted |

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

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

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

The **`persist()`** method of the `StorageManager` interface requests permission to use persistent storage, and returns a `Promise` that resolves to `true` if permission is granted and bucket mode is persistent, and `false` otherwise.

**Note:** This method is not available in Web Workers, though the `StorageManager` interface is.

Syntax
------


```js
persist()
```

### Parameters

None.

### Return value

A `Promise` that resolves to a `Boolean`.

### Exceptions

`TypeError`

Thrown if obtaining a local storage shelf failed. For example, if the current origin is an opaque origin or if the user has disabled storage.

Example
-------


```js
if (navigator.storage && navigator.storage.persist) {
  navigator.storage.persist().then((persistent) => {
    if (persistent) {
      console.log("Storage will not be cleared except by explicit user action");
    } else {
      console.log("Storage may be cleared by the UA under storage pressure.");
    }
  });
}
```

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

| Specification |
| --- |
| Storage Standard # ref-for-dom-storagemanager-persist |

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

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

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

The **`estimate()`** method of the `StorageManager` interface asks the Storage Manager for how much storage the current origin takes up (`usage`), and how much space is available (`quota`).

This method operates asynchronously, so it returns a `Promise` which resolves once the information is available. The promise's fulfillment handler is called with an object containing the usage and quota data.

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

Syntax
------


```js
estimate()
```

### Parameters

None.

### Return value

A `Promise` that resolves to an object with the following properties:

`quota`

A numeric value in bytes which provides a conservative approximation of the total storage the user's device or computer has available for the site origin or Web app. It's possible that there's more than this amount of space available though you can't rely on that being the case.

`usage`

A numeric value in bytes approximating the amount of storage space currently being used by the site or Web app, out of the available space as indicated by `quota`. Unit is byte.

`usageDetails` 
Non-standard

An object containing a breakdown of `usage` by storage system. All included properties will have a `usage` greater than 0 and any storage system with 0 `usage` will be excluded from the object.


**Note:** The returned values are not exact: between compression, deduplication, and obfuscation for security reasons, they will be imprecise.

You may find that the `quota` varies from origin to origin. This variance is based on factors such as:

* How often the user visits
* Public site popularity data
* User engagement signals like bookmarking, adding to homescreen, or accepting push notifications
### Exceptions

`TypeError`

Thrown if obtaining a local storage shelf failed. For example, if the current origin is an opaque origin or if the user has disabled storage.

Examples
--------

In this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user.

### HTML


```html
<label>
  You're currently using about <output id="percent"> </output>% of your
  estimated storage quota (<output id="quota"></output>).
</label>
```

### JavaScript


```js
navigator.storage.estimate().then((estimate) => {
  document.getElementById("percent").value = (
    (estimate.usage / estimate.quota) \*
    100
  ).toFixed(2);
  document.getElementById("quota").value =
    (estimate.quota / 1024 / 1024).toFixed(2) + "MB";
});
```

### Result

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

| Specification |
| --- |
| Storage Standard # ref-for-dom-storagemanager-estimate |

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

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

See also
--------

* Storage API
* `Storage`, the object returned by `Window.localStorage`
* `StorageManager`
* `navigator.storage`
XRMediaBinding: XRMediaBinding() constructor
============================================

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

The **`XRMediaBinding()`** constructor creates and returns a new `XRMediaBinding` object.

Syntax
------


```js
new XRMediaBinding(session)
```

### Parameters

`session`

An `XRSession` object specifying the WebXR session for which to create the media binding.

### Return value

A newly-created `XRMediaBinding`.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the new `XRMediaBinding` could not be created due to one of a number of possible state errors:

* The `XRSession` specified by `session` has already been stopped.
* The specified `session` is not immersive.

Examples
--------

### Creating a new `XRMediaBinding`

The following example creates a new media binding for a session to create an `XRQuadLayer` to display a video layer in the scene.


```js
const xrMediaBinding = new XRMediaBinding(xrSession);

const video = document.createElement("video");
video.src = "just-fascination.mp4";
const layer = xrMediaBinding.createQuadLayer(video);
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrmediabinding-xrmediabinding |

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

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

See also
--------

* `XRWebGLBinding`
XRMediaBinding: createQuadLayer() method
========================================

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

The **`createQuadLayer()`** method of the `XRMediaBinding` interface returns an `XRQuadLayer` object which is a layer that takes up a flat rectangular space in the virtual environment.

Syntax
------


```js
createQuadLayer(video, options)
```

### Parameters

`video`

An `HTMLVideoElement` to display.

`options`

An object to configure the `XRQuadLayer`. The object can have the following properties and `space` is required:

`height` Optional

A number specifying the height of the layer.

`invertStereo` Optional

A boolean specifying if the natural location of each view in the video should be inverted. By default `false`.

`layout` Optional

A string indicating the layout of the video. Possible values:

`default`

The layer accommodates all views of the session.

`mono`

A single `XRSubImage` is allocated and presented to both eyes.

`stereo`

The user agent decides how it allocates the `XRSubImage` (one or two) and the layout (top/bottom or left/right). It is recommended to use the `texture-array` texture type for `stereo` layouts.

`stereo-left-right`

A single `XRSubImage` is allocated. Left eye gets the left area of the texture, right eye the right. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).

`stereo-top-bottom`

 A single `XRSubImage` is allocated. Left eye gets the top area of the texture, right eye the bottom. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).
 The default value is `mono`.



`space` **Required**

An `XRSpace` object defining the layer's spatial relationship with the user's physical environment.

`transform` Optional

An `XRRigidTransform` object defining the offset and orientation relative to `space`.

`width` Optional

A number specifying the width of the layer.


### Return value

An `XRQuadLayer` object.

Examples
--------

### Creating an `XRQuadLayer` to display a video

Create an `XRMediaBinding` and use an `HTMLVideoElement` that is passed into `createQuadLayer()`. Configure the quad layer using the options listed above and present the layer to the XR device by adding it to the `layers` render state in `XRSession.updateRenderState()`.


```js
function onXRSessionStarted(xrSession) {
  const xrMediaBinding = new XRMediaBinding(xrSession);
  const video = document.createElement("video");
  video.src = "just-fascination.mp4";

  const videoLayer = xrMediaBinding.createQuadLayer(video, {
    space: xrReferenceSpace,
  });

  xrSession.updateRenderState({
    layers: [videoLayer],
  });
}
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrmediabinding-createquadlayer |

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

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

See also
--------

* `XRQuadLayer`
CookieChangeEvent: CookieChangeEvent() constructor
==================================================

**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 **`CookieChangeEvent()`** constructor creates a new `CookieChangeEvent` object
 which is the event type of the `change` event fired at a `CookieStore` when any cookie changes occur.
 This constructor is called by the browser when a change event occurs.

**Note:** This event constructor is generally not needed for production websites. It's primary use is for tests that require an instance of this event.

Syntax
------


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

### Parameters

`type`

A string with the name of the event. It is case-sensitive and browsers always set it to `change`.

`options` Optional

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

`changed`Optional

An array containing the changed cookies.

`deleted`Optional

An array containing the deleted cookies.


### Return value

A new `CookieChangeEvent` object.

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

| Specification |
| --- |
| Cookie Store API # dom-cookiechangeevent-cookiechangeevent |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
CookieChangeEvent: changed 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 **`changed`** read-only property of the `CookieChangeEvent` interface returns an array of the cookies that have been changed.

Value
-----

An array of objects containing the changed cookie(s). Each object contains the following properties:

`name`

A string containing the name of the cookie.

`value`

A string containing the value of the cookie.

`domain`

A string containing the domain of the cookie.

`path`

A string containing the path of the cookie.

`expires`

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

`secure`

A `boolean` indicating whether the cookie is from a site with a secure context (HTTPS rather than HTTP).

`sameSite`

One of the following `SameSite` values:

`"strict"`

Cookies will only be sent in a first-party context and not be sent with requests initiated by third party websites.

`"lax"`

Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating within the origin site (i.e. when following a link).

`"none"`

Cookies will be sent in all contexts.


`partitioned`

A boolean indicating whether the cookie is a partitioned cookie (`true`) or not (`false`). See Cookies Having Independent Partitioned State (CHIPS) for more information.

Examples
--------

In this example, when the cookie is set, the event listener logs the `changed` property to the console. The first item in that array contains an object representing the cookie that has just been set.


```js
cookieStore.addEventListener("change", (event) => {
  console.log(event.changed[0]);
});

const one_day = 24 \* 60 \* 60 \* 1000;
cookieStore.set({
  name: "cookie1",
  value: "cookie1-value",
  expires: Date.now() + one_day,
  domain: "example.com",
});
```

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

| Specification |
| --- |
| Cookie Store API # dom-cookiechangeevent-changed |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
CookieChangeEvent: deleted 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 **`deleted`** read-only property of the `CookieChangeEvent` interface returns an array of the cookies that have been deleted by the given `CookieChangeEvent` instance.

Value
-----

An array of objects containing the deleted cookie(s). Each object contains the following properties:

`name`

A string containing the name of the cookie.

`value`

A string containing the value of the cookie.

`domain`

A string containing the domain of the cookie.

`path`

A string containing the path of the cookie.

`expires`

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

`secure`

A `boolean` indicating whether the cookie is from a site with a secure context (HTTPS rather than HTTP).

`sameSite`

One of the following `SameSite` values:

`"strict"`

Cookies will only be sent in a first-party context and not be sent with requests initiated by third party websites.

`"lax"`

Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating within the origin site (i.e. when following a link).

`"none"`

Cookies will be sent in all contexts.


`partitioned`

A boolean indicating whether the cookie is a partitioned cookie (`true`) or not (`false`). See Cookies Having Independent Partitioned State (CHIPS) for more information.

Examples
--------

In this example, when the cookie is deleted, the event listener logs the first item in the `CookieChangeEvent.deleted` property to the console. It contains an object representing the cookie that has just been deleted.


```js
cookieStore.addEventListener("change", (event) => {
  console.log(event.deleted[0]);
});
```

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

| Specification |
| --- |
| Cookie Store API # dom-cookiechangeevent-deleted |

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

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

The **`replace()`** method of the `CSSStyleSheet` interface asynchronously replaces the content of the stylesheet with the content passed into it. The method returns a promise that resolves with the `CSSStyleSheet` object.

The `replace()` and `CSSStyleSheet.replaceSync()` methods can only be used on a stylesheet created with the `CSSStyleSheet()` constructor.

Syntax
------


```js
replace(text)
```

### Parameters

`text`

A string containing the style rules to replace the content of the stylesheet. If the string does not contain a parseable list of rules, then the value will be set to an empty string.

**Note:** If any of the rules passed in `text` are an external stylesheet imported with the `@import` rule, those rules will be removed, and a warning printed to the console.

### Return value

A `Promise` that resolves with the `CSSStyleSheet`.

### Exceptions

`NotAllowedError` `DOMException`

Thrown if one of these two conditions is met:

* The stylesheet was not created using the `CSSStyleSheet()` constructor.
* The stylesheet is flagged as unmodifiable.

Examples
--------

In the following example a new stylesheet is created and two CSS rules are added using `replace()`. The first rule is then printed to the console, which will return: `body { font-size: 1.4em; }`


```js
const stylesheet = new CSSStyleSheet();

stylesheet
  .replace("body { font-size: 1.4em; } p { color: red; }")
  .then(() => {
    console.log(stylesheet.cssRules[0].cssText);
  })
  .catch((err) => {
    console.error("Failed to replace styles:", err);
  });
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-replace |

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

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

See also
--------

* Constructable Stylesheets (web.dev)
* Using the Shadow DOM
CSSStyleSheet: replaceSync() method
===================================

The **`replaceSync()`** method of the `CSSStyleSheet` interface synchronously replaces the content of the stylesheet with the content passed into it.

The `replaceSync()` and `CSSStyleSheet.replace()` methods can only be used on a stylesheet created with the `CSSStyleSheet()` constructor.

Syntax
------


```js
replaceSync(text)
```

### Parameters

`text`

A string containing the style rules to replace the content of the stylesheet. If the string does not contain a parseable list of rules, then the value will be set to an empty string.

**Note:** If any of the rules passed in `text` are an external stylesheet imported with the `@import` rule, those rules will be removed, and a warning printed to the console.

### Return value

None (`undefined`).

### Exceptions

`NotAllowedError` `DOMException`

Thrown if the stylesheet was not created using the `CSSStyleSheet()` constructor or if the stylesheet is flagged as unmodifiable.

Examples
--------

In the following example a new stylesheet is created and two CSS rules are added using `replaceSync`.


```js
const stylesheet = new CSSStyleSheet();

stylesheet.replaceSync("body { font-size: 1.4em; } p { color: red; }");
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-cssstylesheet-replacesync |

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

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

See also
--------

* Constructable Stylesheets (web.dev)
* Using the Shadow DOM