AudioWorkletNode: AudioWorkletNode() constructor - Web APIs

AudioWorkletNode: AudioWorkletNode() constructor
================================================

 The **`AudioWorkletNode()`**
 constructor creates a new `AudioWorkletNode` object, which represents an
 `AudioNode` that uses a JavaScript function to perform custom audio
 processing.

Syntax
------

```js
new AudioWorkletNode(context, name)
new AudioWorkletNode(context, name, options)
```

### Parameters

`context`

The `BaseAudioContext` instance this node will be associated with.

`name`

 A string, which represents the name of the `AudioWorkletProcessor` this
 node will be based on. A processor with the provided name must first be registered
 using the `AudioWorkletGlobalScope.registerProcessor()` method.

`options` Optional

An object containing zero or more of the following optional properties to configure the new node:

**Note:** The result of the structured clone algorithm
 applied to the object is also internally passed into the associated `AudioWorkletProcessor()` constructor
 — this allows custom initialization of an underlying user-defined `AudioWorkletProcessor`.

`numberOfInputs` Optional

The value to initialize the `numberOfInputs` property to. Defaults to 1.

`numberOfOutputs` Optional

The value to initialize the `numberOfOutputs` property to. Defaults to 1.

`outputChannelCount` Optional

An **array** defining the number of channels for each output. For example, *outputChannelCount: [n, m]* specifies the number of channels in the first output to be *n* and the second output to be *m*. The array length must match `numberOfOutputs`.

`parameterData` Optional

An object containing the initial values of custom `AudioParam` objects on this node (in its `parameters` property), with `key` being the name of a custom parameter and `value` being its initial value.

`processorOptions` Optional

Any additional data that can be used for custom initialization of the underlying `AudioWorkletProcessor`.

### Exceptions

`NotSupportedError` `DOMException`

 The specified `options.outputChannelCount` is `0` or larger
 than the current implementation supports.

Both `options.numberOfInputs` and `options.numberOfOutputs` are 0.

`IndexSizeError` `DOMException`

 The length of `options.outputChannelCount` array does not match
 `options.numberOfOutputs`.

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

Different `options` parameter values can have the following effects.

If the number of inputs and number of outputs are both set to 0, a `NotSupportedError` will be thrown and the node construction process aborted. If the length of the `outputChannelCount` array doesn't match `numberOfOutputs`, an `IndexSizeError` `DOMException` will be thrown.

If `outputChannelCount` isn't specified, and `numberOfInputs` and `numberOfOutputs` are both 1, the `AudioWorkletNode`'s initial channel count is set to 1. This has the effect of changing the output channel count to dynamically change to the computed number of channels, based on the input's channel count and the current setting of the `AudioNode` property `channelCountMode`.

Otherwise, if `outputChannelCount` is provided *and* if the values of `numberOfInputs` and `numberOfOutputs` are both 1, the audio worklet node's channel count is set to the value of `outputChannelCount`. Otherwise, the channel count of each channel in the set of output channels is set to match the corresponding value in the `outputChannelCount` array.

Examples
--------

*For a complete example demonstrating user-defined audio processing, see the
`AudioWorkletNode` page.*

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

| Specification |
| --- |
| Web Audio API # dom-audioworkletnode-audioworkletnode |

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

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

See also
--------

* Web Audio API
* Background audio processing using AudioWorklet
* `AudioWorkletNode` interface


AudioWorkletNode: processorerror event - Web APIs

AudioWorkletNode: processorerror event
======================================

The `processorerror` event fires when the underlying `AudioWorkletProcessor` behind the node throws an exception in its constructor, the `process` method, or any user-defined class method.

Once an exception is thrown, the processor (and thus the node) will output silence throughout its lifetime.

Syntax
------

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

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

onprocessorerror = (event) => { }
```

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

A generic `Event`.

Examples
--------

To be informed when the processor throws an exception, you can add a handler to your `AudioWorkletNode` instance using `addEventListener()`, like this:

```js
whiteNoiseNode.addEventListener("processorerror", (event) => {
  console.error("There was an error!");
});
```

Alternatively, you can use the `onprocessorerror` event handler property to establish a handler for the `processorerror` event:

```js
whiteNoiseNode.onprocessorerror = (event) => {
  console.error("There was an error!");
};
```

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

| Specification |
| --- |
| Web Audio API # dom-audioworkletnode-onprocessorerror |

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

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

See also
--------

* Using the Web Audio API


GPUBindGroup: label property - Web APIs

GPUBindGroup: label property
============================

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

 The **`label`** property of the
 `GPUBindGroup` interface provides a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

This can be set by providing a `label` property in the descriptor object passed into the originating `GPUDevice.createBindGroup()` call, or you can get and set it directly on the `GPUBindGroup` object.

Value
-----

A string. If this has not been previously set as described above, it will be an empty string.

Examples
--------

Setting and getting a label via `GPUBindGroup.label`:

```js
// ...

const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
});

bindGroup.label = "mybindgroup";

console.log(bindGroup.label); // "mybindgroup";
```

Setting a label via the originating `GPUDevice.createBindGroup()` call, and then getting it via `GPUBindGroup.label`:

```js
// ...

const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
  label: "mybindgroup",
});

console.log(bindGroup.label); // "mybindgroup";
```

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

| Specification |
| --- |
| WebGPU # dom-gpuobjectbase-label |

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

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

See also
--------

* The WebGPU API


console: warn() static method - Web APIs

console: warn() static method
=============================

The **`console.warn()`** static method outputs a warning message to the console.

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

**Note:** In Chrome and Firefox, warnings have a small exclamation point icon next to them in the console log.

Syntax
------

```js
warn(obj1)
warn(obj1, /\* …, \*/ objN)
warn(msg)
warn(msg, subst1, /\* …, \*/ substN)
```

### Parameters

`obj1` … `objN`

A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console.

`msg`

A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order.

`subst1` … `substN`

JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See Using string substitutions for a description of how substitutions work.

See Outputting text to the console in the documentation of the `console` object for details.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # warn |

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

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

See also
--------

* Microsoft Edge's documentation for `console.warn()`
* Node.JS documentation for `console.warn()`
* Google Chrome's documentation for `console.warn()`


console: info() static method - Web APIs

console: info() static method
=============================

The **`console.info()`** static method outputs an informational message to the console. In Firefox, a small "i" icon is displayed next to these items in the console's log.

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

Syntax
------

```js
info(obj1)
info(obj1, /\* …, \*/ objN)
info(msg)
info(msg, subst1, /\* …, \*/ substN)
```

### Parameters

`obj1` … `objN`

A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console.

`msg`

A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order.

`subst1` … `substN`

JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See Using string substitutions for a description of how substitutions work.

See Outputting text to the console in the documentation of the `console` object for details.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # info |

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

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

See also
--------

* Microsoft Edge's documentation for `console.info()`
* Node.JS documentation for `console.info()`
* Google Chrome's documentation for `console.info()`


console: time() static method - Web APIs

console: time() static method
=============================

The **`console.time()`** static method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call `console.timeEnd()` with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.

See Timers in the `console` documentation for details and examples.

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

Syntax
------

```js
time()
time(label)
```

### Parameters

`label` Optional

A string representing the name to give the new timer. This will identify the timer; use the same name when calling `console.timeEnd()` to stop the timer and get the time output to the console. If omitted, the label `"default"` is used.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # time |

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

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

See also
--------

* `console.timeEnd()`
* `console.timeLog()`
* Microsoft Edge's documentation for `console.time()`
* Node.JS documentation for `console.time()`
* Google Chrome's documentation for `console.time()`


console: groupEnd() static method - Web APIs

console: groupEnd() static method
=================================

The **`console.groupEnd()`** static method exits the current inline group in the console. See Using groups in the console in the `console` documentation for details and examples.

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

Syntax
------

```js
groupEnd()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # groupend |

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

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

See also
--------

* `console.group()`
* `console.groupCollapsed()`
* Microsoft Edge's documentation for `console.groupEnd()`
* Node.JS documentation for `console.groupEnd()`
* Google Chrome's documentation for `console.groupEnd()`


console: timeStamp() static method - Web APIs

console: timeStamp() static method
==================================

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

The **`console.timeStamp()`** static method adds a single marker to the browser's Performance tool (Firefox, Chrome). This lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events.

You can optionally supply an argument to label the timestamp, and this label will then be shown alongside the marker.

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

Syntax
------

```js
timeStamp(label)
```

### Parameters

`label` Optional

Label for the timestamp.

### Return value

None (`undefined`).

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

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

See also
--------

* `console.time()`
* `console.timeLog()`
* `console.timeEnd()`
* Adding markers with the console API


console: log() static method - Web APIs

console: log() static method
============================

The **`console.log()`** static method outputs a message to the console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.

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

Syntax
------

```js
log(obj1)
log(obj1, /\* …, \*/ objN)
log(msg)
log(msg, subst1, /\* …, \*/ substN)
```

### Parameters

`obj1` … `objN`

A list of JavaScript objects to output. Objects are output in the order listed. Please be warned that if you log objects in the latest versions of Chrome and Firefox, what you get logged on the console is a *reference to the object*, which is not necessarily the 'value' of the object at the moment in time you call `console.log()`, but it is the value of the object at the moment you open the console.

`msg`

A JavaScript string containing zero or more substitution strings.

`subst1` … `substN`

JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output.

See Outputting text to the console in the documentation of `console` for details.

### Return value

None (`undefined`).

Logging objects
---------------

Information about an object is lazily retrieved. This means that the log message shows the content of an object at the time when it's first viewed, not when it was logged. For example:

```js
const obj = {};
console.log(obj);
obj.prop = 123;
```

This will output `{}`. However, if you expand the object's details, you will see `prop: 123`.

If you are going to mutate your object and you want to prevent the logged information from being updated, you can deep-clone the object before logging it. A common way is to `JSON.stringify()` and then `JSON.parse()` it:

```js
console.log(JSON.parse(JSON.stringify(obj)));
```

There are other alternatives that work in browsers, such as `structuredClone()`, which are more effective at cloning different types of objects.

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

| Specification |
| --- |
| Console Standard # log |

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

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

See also
--------

* Microsoft Edge's documentation for `console.log()`
* Node.JS documentation for `console.log()`
* Google Chrome's documentation for `console.log()`


console: groupCollapsed() static method - Web APIs

console: groupCollapsed() static method
=======================================

The **`console.groupCollapsed()`** static method creates a new inline group in the console. Unlike `console.group()`, however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group.

Call `console.groupEnd()` to back out to the parent group.

See Using groups in the console in the `console` documentation for details and examples.

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

Syntax
------

```js
groupCollapsed()
groupCollapsed(label)
```

### Parameters

`label` Optional

Label for the group.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # groupcollapsed |

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

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

See also
--------

* `console.group()`
* `console.groupEnd()`
* Microsoft Edge's documentation for `console.groupCollapsed()`
* Node.JS documentation for `console.groupCollapsed()`
* Google Chrome's documentation for `console.groupCollapsed()`


console: dir() static method - Web APIs

console: dir() static method
============================

The **`console.dir()`** static method displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.

In other words, `console.dir()` is the way to see all the properties of a specified JavaScript object in console by which the developer can easily get the properties of the object.

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

![A screenshot of the Firefox console where console.dir(document.location) is run. We can see the URL of the page, followed by a block of properties. If the property is a function or an object, a disclosure triangle is prepended.](/en-US/docs/Web/API/console/dir_static/console-dir.png)

Syntax
------

```js
dir(object)
```

### Parameters

`object`

A JavaScript object whose properties should be output.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # dir |

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

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

See also
--------

* Microsoft Edge's documentation for `console.dir()`
* Node.JS documentation for `console.dir()`
* Google Chrome's documentation for `console.dir()`


console: dirxml() static method - Web APIs

console: dirxml() static method
===============================

The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes.

Syntax
------

```js
dirxml(object)
```

### Parameters

`object`

A JavaScript object whose properties should be output.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # dirxml |

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

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

See also
--------

* Microsoft Edge's documentation for `console.dirxml()`
* Node.JS documentation for `console.dirxml()`
* Google Chrome's documentation for `console.dirxml()`


console: timeLog() static method - Web APIs

console: timeLog() static method
================================

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

The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling `console.time()`.

Syntax
------

```js
timeLog()
timeLog(label)
timeLog(label, val1)
timeLog(label, val1, /\* …, \*/ valN)
```

### Parameters

`label` Optional

The name of the timer to log to the console. If this is omitted the label "default" is used.

`valN` Optional

Additional values to be logged to the console after the timer output.

### Return value

None (`undefined`).

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

The `console.timeLog()` method logs the current value of a timer.

The method can be passed the name of a timer. This will attempt to log the value of a timer created with that name in a previous call to `console.time()`:

```js
console.time("reticulating splines");
reticulateSplines();
console.timeLog("reticulating splines");
// reticulating splines: 650ms
```

If the timer name is omitted, then the timer is named `"default"`:

```js
console.time();
reticulateSplines();
console.timeLog();
// default: 780ms
```

```js
console.time("default");
reticulateSplines();
console.timeLog();
// default: 780ms
```

If there is no corresponding timer, `console.timeLog()` logs a warning like:
```

Timer "timer name" doesn't exist.
```

You can log additional values to the console after the timer output:

```js
console.time();
reticulateSplines();
console.timeLog("default", "Hello", "world");
// default: 780ms Hello world
```

See Timers in the documentation for more details and examples.

Examples
--------

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

The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the cumulative time it took for the user to dismiss both alerts:
```

answer time: 2542ms debugger eval code:3:9
answer time: 4161ms - timer ended
```

Notice that the timer's name is displayed when the timer value is logged using `console.timeLog()` and again when it's stopped. In addition, the call to `console.timeEnd()` has the additional information, "timer ended" to make it obvious that the timer is no longer tracking time.

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

| Specification |
| --- |
| Console Standard # timelog |

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

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

See also
--------

* `console.time()`
* `console.timeEnd()`
* Node.JS documentation for `console.timeLog()`


console: group() static method - Web APIs

console: group() static method
==============================

The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until `console.groupEnd()` is called.

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

Syntax
------

```js
group()
group(label)
```

### Parameters

`label` Optional

Label for the group.

### Return value

None (`undefined`).

Examples
--------

You can use nested groups to help organize your output by visually associating related messages. To create a new nested block, call `console.group()`. The `console.groupCollapsed()` method is similar, but the new block is collapsed and requires clicking a disclosure button to read it.

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

```js
console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");
```

The output looks like this:

![A screenshot of messages nested in the console output.](/en-US/docs/Web/API/console/group_static/nesting.png)

See Using groups in the console in the documentation of `console` for more details.

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

| Specification |
| --- |
| Console Standard # group |

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

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

See also
--------

* `console.groupEnd()`
* `console.groupCollapsed()`
* Microsoft Edge's documentation for `console.group()`
* Node.JS documentation for `console.group()`
* Google Chrome's documentation for `console.group()`


console: profileEnd() static method - Web APIs

console: profileEnd() static method
===================================

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

The **`console.profileEnd()`** static method stops recording a profile previously started with `console.profile()`.

You can optionally supply an argument to name the profile. Doing so enables you to stop only that profile if you have multiple profiles being recorded.

* If `console.profileEnd()` is passed a profile name, and it matches the name of a profile being recorded, then that profile is stopped.
* If `console.profileEnd()` is passed a profile name and it does not match the name of a profile being recorded, no changes will be made.
* If `console.profileEnd()` is not passed a profile name, the most recently started profile is stopped.

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

Syntax
------

```js
profileEnd(profileName)
```

### Parameters

`profileName` Optional

The name to give the profile.

### Return value

None (`undefined`).

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

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

See also
--------

* `console.profile()`


console: table() static method - Web APIs

console: table() static method
==============================

The **`console.table()`** static method displays tabular data as a table.

This function takes one mandatory argument `data`, which must be an array or an object, and one additional optional parameter `columns`.

It logs `data` as a table. Each element in the array (or enumerable property if `data` is an object) will be a row in the table.

The first column in the table will be labeled `(index)`. If `data` is an array, then its values will be the array indices. If `data` is an object, then its values will be the property names. Note that (in Firefox) `console.table` is limited to displaying 1000 rows (first row is the labeled index).

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

### Collections of primitive types

The `data` argument may be an array or an object.

```js
// an array of strings

console.table(["apples", "oranges", "bananas"]);
```

| (index) | Values |
| --- | --- |
| 0 | 'apples' |
| 1 | 'oranges' |
| 2 | 'bananas' |

```js
// an object whose properties are strings

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

const me = new Person("Tyrone", "Jones");

console.table(me);
```

| (index) | Values |
| --- | --- |
| firstName | 'Tyrone' |
| lastName | 'Jones' |

### Collections of compound types

If the elements in the array, or properties in the object, are themselves arrays or objects, then their elements or properties are enumerated in the row, one per column:

```js
// an array of arrays

const people = [
  ["Tyrone", "Jones"],
  ["Janet", "Smith"],
  ["Maria", "Cruz"],
];
console.table(people);
```

| (index) | 0 | 1 |
| --- | --- | --- |
| 0 | 'Tyrone' | 'Jones' |
| 1 | 'Janet' | 'Smith' |
| 2 | 'Maria' | 'Cruz' |

```js
// an array of objects

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

const tyrone = new Person("Tyrone", "Jones");
const janet = new Person("Janet", "Smith");
const maria = new Person("Maria", "Cruz");

console.table([tyrone, janet, maria]);
```

Note that if the array contains objects, then the columns are labeled with the property name.

| (index) | firstName | lastName |
| --- | --- | --- |
| 0 | 'Tyrone' | 'Jones' |
| 1 | 'Janet' | 'Smith' |
| 2 | 'Maria' | 'Cruz' |

```js
// an object whose properties are objects

const family = {};

family.mother = new Person("Janet", "Jones");
family.father = new Person("Tyrone", "Jones");
family.daughter = new Person("Maria", "Jones");

console.table(family);
```

| (index) | firstName | lastName |
| --- | --- | --- |
| daughter | 'Maria' | 'Jones' |
| father | 'Tyrone' | 'Jones' |
| mother | 'Janet' | 'Jones' |

### Restricting the columns displayed

By default, `console.table()` lists all elements in each row. You can use the optional `columns` parameter to select a subset of columns to display:

```js
// an array of objects, logging only firstName

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

const tyrone = new Person("Tyrone", "Jones");
const janet = new Person("Janet", "Smith");
const maria = new Person("Maria", "Cruz");

console.table([tyrone, janet, maria], ["firstName"]);
```

| (index) | firstName |
| --- | --- |
| 0 | 'Tyrone' |
| 1 | 'Janet' |
| 2 | 'Maria' |

### Sorting columns

You can sort the table by a particular column by clicking on that column's label.

Syntax
------

```js
table(data)
table(data, columns)
```

### Parameters

`data`

The data to display. This must be either an array or an object.

`columns`

An array containing the names of columns to include in the output.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # table |

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

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

See also
--------

* Microsoft Edge's documentation for `console.table()`
* Node.JS documentation for `console.table()`
* Google Chrome's documentation for `console.table()`


console: profile() static method - Web APIs

console: profile() static method
================================

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

The **`console.profile()`** static method starts recording a performance profile (for example, the Firefox performance tool).

You can optionally supply an argument to name the profile and this then enables you to stop only that profile if multiple profiles being recorded. See `console.profileEnd()` to see how this argument is interpreted.

To stop recording call `console.profileEnd()`.

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

Syntax
------

```js
profile(profileName)
```

### Parameters

`profileName` Optional

The name to give the profile.

### Return value

None (`undefined`).

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

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

See also
--------

* `console.profileEnd()`


console: countReset() static method - Web APIs

console: countReset() static method
===================================

The **`console.countReset()`** static method resets counter used with `console.count()`.

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

Syntax
------

```js
countReset()
countReset(label)
```

### Parameters

`label` Optional

A string. If supplied, `countReset()` resets the count for that label to 0. If omitted, `countReset()` resets the default counter to 0.

### Return value

None (`undefined`).

Examples
--------

For example, given code like this:

```js
let user = "";

function greet() {
  console.count();
  return `hi ${user}`;
}

user = "bob";
greet();
user = "alice";
greet();
greet();
console.count();
console.countReset();
```

Console output will look something like this:
```

"default: 1"
"default: 2"
"default: 3"
"default: 4"
"default: 0"
```

Note that the call to `console.counterReset()` resets the value of the default counter to zero.

If we pass the `user` variable as the `label` argument with the string "bob" to the first invocation of `console.count()`, and the string "alice" to the second:

```js
let user = "";

function greet() {
  console.count(user);
  return `hi ${user}`;
}

user = "bob";
greet();
user = "alice";
greet();
greet();
console.countReset("bob");
console.count("alice");
```

We will see output like this:
```

"bob: 1"
"alice: 1"
"alice: 2"
"bob: 0"
"alice: 3"
```

Resetting the value of the counter "bob" only changes the value of that counter. The value of "alice" is unchanged.

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

| Specification |
| --- |
| Console Standard # countreset |

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

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

See also
--------

* Microsoft Edge's documentation for `console.countReset()`
* Node.JS documentation for `console.countReset()`
* Google Chrome's documentation for `console.countReset()`


console: error() static method - Web APIs

console: error() static method
==============================

The **`console.error()`** static method outputs an error message to the console.

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

Syntax
------

```js
error(obj1)
error(obj1, /\* …, \*/ objN)
error(msg)
error(msg, subst1, /\* …, \*/ substN)
```

### Parameters

`obj1` … `objN`

A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console.

`msg`

A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order.

`subst1` … `substN`

JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See Using string substitutions for a description of how substitutions work.

See Outputting text to the console in the documentation of the `console` object for details.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # error |

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

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

See also
--------

* Microsoft Edge's documentation for `console.error()`
* Node.JS documentation for `console.error()`
* Google Chrome's documentation for `console.error()`


console: clear() static method - Web APIs

console: clear() static method
==============================

The **`console.clear()`** static method clears the console if the console allows it. A graphical console, like those running on browsers, will allow it; a console displaying on the terminal, like the one running on Node, will not support it, and will have no effect (and no error).

Syntax
------

```js
clear()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # clear |

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

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

See also
--------

* Microsoft Edge's documentation for `console.clear()`
* Node.JS documentation for `console.clear()`
* Google Chrome's documentation for `console.clear()`


console: timeEnd() static method - Web APIs

console: timeEnd() static method
================================

The **`console.timeEnd()`** static method stops a timer that was previously started by calling `console.time()`.

See Timers in the documentation for details and examples.

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

Syntax
------

```js
timeEnd()
timeEnd(label)
```

### Parameters

`label` Optional

A string representing the name of the timer to stop. Once stopped, the elapsed time is automatically displayed in the console along with an indicator that the time has ended. If omitted, the label "default" is used.

### Return value

None (`undefined`).

Examples
--------

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

The output from the example above shows the time taken by the user to dismiss the first alert box, followed by the cumulative time it took for the user to dismiss both alerts:

![Timer output in Firefox console](/en-US/docs/Web/API/console/timeend_static/timer_output.png)

 Notice that the timer's name is displayed when the timer value is logged using `console.timeLog()` and again when it's stopped. In addition, the call to `console.timeEnd()` has the additional information, "timer ended" to make it obvious that the timer is no
 longer tracking time.

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

| Specification |
| --- |
| Console Standard # timeend |

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

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

See also
--------

* `console.time()`
* `console.timeLog()`
* Microsoft Edge's documentation for `console.timeEnd()`
* Node.JS documentation for `console.timeEnd()`
* Google Chrome's documentation for `console.timeEnd()`


console: debug() static method - Web APIs

console: debug() static method
==============================

The **`console.debug()`** static method outputs a message to the console at the "debug" log level. The message is only displayed to the user if the console is configured to display debug output. In most cases, the log level is configured within the console UI. This log level might correspond to the `Debug` or `Verbose` log level.

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

Syntax
------

```js
debug(obj1)
debug(obj1, /\* …, \*/ objN)
debug(msg)
debug(msg, subst1, /\* …, \*/ substN)
```

### Parameters

`obj1` … `objN`

A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output to the console.

`msg`

A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order.

`subst1` … `substN`

JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See Using string substitutions for a description of how substitutions work.

See Outputting text to the console in the documentation of the `console` object for details.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Console Standard # debug |

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

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

See also
--------

* Microsoft Edge's documentation for `console.debug()`
* Node.JS documentation for `console.debug()`
* Google Chrome's documentation for `console.debug()`


console: trace() static method - Web APIs

console: trace() static method
==============================

The **`console.trace()`** static method outputs a stack trace to the console.

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

**Note:** In some browsers, `console.trace()` may also output the sequence of calls and asynchronous events leading to the current `console.trace()` which are not on the call stack — to help identify the origin of the current event evaluation loop.

See Stack traces in the `console` documentation for details and examples.

Syntax
------

```js
trace()
trace(object1, /\* …, \*/ objectN)
```

### Parameters

`objects` Optional

Zero or more objects to be output to console along with the trace. These are assembled and formatted the same way they would be if passed to the `console.log()` method.

### Return value

None (`undefined`).

Examples
--------

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

foo();
```

In the console, the following trace will be displayed:
```

bar
foo
<anonymous>
```

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

| Specification |
| --- |
| Console Standard # trace |

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

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

See also
--------

* Microsoft Edge's documentation for `console.trace()`
* Node.JS documentation for `console.trace()`
* Google Chrome's documentation for `console.trace()`


console: assert() static method - Web APIs

console: assert() static method
===============================

The **`console.assert()`** static method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

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

Syntax
------

```js
assert(assertion)

assert(assertion, obj1)
assert(assertion, obj1, obj2)
assert(assertion, obj1, obj2, /\* …, \*/ objN)

assert(assertion, msg)
assert(assertion, msg, subst1)
assert(assertion, msg, subst1, /\* …, \*/ substN)
```

### Parameters

`assertion`

Any boolean expression. If the assertion is false, a generic message indicating assertion failure is written to the console.

`obj1` … `objN`

A list of JavaScript objects to output. A representation of each of these objects is output to the console after a generic assertion failure message (which may be different from the message output when these objects are not present) in the order given with some type of separation between the message and between each of them. There is a special case if `obj1` is a string, which is described subsequently.

`msg`

A JavaScript string containing zero or more substitution strings, which are replaced with `subst1` through `substN` in consecutive order up to the number of substitution strings. A colon, a space, and then the substituted string are appended to the generic assertion message to form a detailed assertion message, and the result is output to the console.

`subst1` … `substN`

JavaScript objects with which to replace substitution strings within `msg`. This gives you additional control over the format of the output. See Using string substitutions for a description of how substitutions work. If there are more substutition objects than there are substitution strings, the extra objects are themselves written to the console after the detailed assertion message in the same manner as described for objects written after a generic assertion message.

### Return value

None (`undefined`).

Examples
--------

The following code example demonstrates the use of a JavaScript object following the assertion:

```js
const errorMsg = "the # is not even";
for (let number = 2; number <= 5; number++) {
  console.log(`the # is ${number}`);
  console.assert(number % 2 === 0, "%o", { number, errorMsg });
}
// output:
// the # is 2
// the # is 3
// Assertion failed: {number: 3, errorMsg: "the # is not even"}
// the # is 4
// the # is 5
// Assertion failed: {number: 5, errorMsg: "the # is not even"}
```

See Using string substitutions in the documentation of `console` for further details.

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

| Specification |
| --- |
| Console Standard # assert |

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

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

See also
--------

* Microsoft Edge's documentation for `console.assert()`
* Node.JS documentation for `console.assert()`
* Google Chrome's documentation for `console.dir()`


console: count() static method - Web APIs

console: count() static method
==============================

The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called.

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

Syntax
------

```js
count()
count(label)
```

### Parameters

`label` Optional

A string. If supplied, `count()` outputs the number of times it has been called with that label. If omitted, `count()` behaves as though it was called with the "default" label.

### Return value

None (`undefined`).

Examples
--------

For example, given code like this:

```js
let user = "";

function greet() {
  console.count();
  return `hi ${user}`;
}

user = "bob";
greet();
user = "alice";
greet();
greet();
console.count();
```

Console output will look something like this:
```

"default: 1"
"default: 2"
"default: 3"
"default: 4"
```

The label is displayed as `default` because no explicit label was supplied.

If we pass the `user` variable as the `label` argument to the first invocation of `console.count()`, and the string "alice" to the second:

```js
let user = "";

function greet() {
  console.count(user);
  return `hi ${user}`;
}

user = "bob";
greet();
user = "alice";
greet();
greet();
console.count("alice");
```

We will see output like this:
```

"bob: 1"
"alice: 1"
"alice: 2"
"alice: 3"
```

We're now maintaining separate counts based only on the value of `label`.

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

| Specification |
| --- |
| Console Standard # count |

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

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

See also
--------

* Microsoft Edge's documentation for `console.count()`
* Node.JS documentation for `console.count()`
* Google Chrome's documentation for `console.count()`


MediaList: item() method - Web APIs

MediaList: item() method
========================

The **`item()`** method of the `MediaList` interface returns the media query at the specified `index`, or `null` if the specified `index` doesn't exist.

Syntax
------

```js
item(index)
[index]
```

**Note:** The bracket (`[]`) syntax can be used instead of the `item()` syntax.

### Parameters

`index`

An integer.

### Return value

If the bracket (`[]`) syntax is used and there is no entry for the given index, `undefined` is returned.

Examples
--------

 The following would log to the console each media query stored in the
 `MediaList` associated with the first stylesheet applied to the current document.

```js
const stylesheet = document.styleSheets[0];
console.log(stylesheet.media.length);
console.log(stylesheet.media.item(0)); // Returns a string like "print"
console.log(stylesheet.media.item(5)); // Returns null if there is no 5th entry
console.log(stylesheet.media[1]); // Returns a string like "print"
console.log(stylesheet.media[5]); // Returns undefined if there is no 5th entry
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-medialist-item |

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

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


MediaList: mediaText property - Web APIs

MediaList: mediaText property
=============================

 The **`mediaText`** property of the `MediaList`
 interface is a stringifier that returns a string representing the
 `MediaList` as text, and also allows you to set a new `MediaList`.

Value
-----

 A string representing the media queries of a stylesheet. Each one is
 separated by a comma, for example
 `screen and (min-width: 480px), print`.

 If you wish to set new media queries on the document, the string value must have the
 different queries separated by commas, e.g. `screen, print`. Note that the
 `MediaList` is a live list; updating the list via
 `mediaText` will immediately update the behavior of the
 document.

 Also note that is you try to set
 `mediaText` to `null`, it will be treated as an empty
 string, i.e. the value will be set to
 `""`.

Examples
--------

 The following would log to the console a textual representation of the
 `MediaList` of the first stylesheet applied to the current document.

```js
const stylesheets = document.styleSheets;
let stylesheet = stylesheets[0];
console.log(stylesheet.media.mediaText);
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-medialist-mediatext |

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

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


MediaList: length property - Web APIs

MediaList: length property
==========================

The read-only **`length`** property of the `MediaList` interface returns the number of media queries in the list.

Value
-----

A positive integer.

Examples
--------

 The following would log to the console the number of media queries stored in the
 `MediaList` associated with the first stylesheet applied to the current document.

```js
const stylesheets = document.styleSheets;
const stylesheet = stylesheets[0];
console.log(stylesheet.media.length);
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-medialist-length |

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

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


MediaList: appendMedium() method - Web APIs

MediaList: appendMedium() method
================================

The `appendMedium()` method of the `MediaList` interface adds a media query to the list. If the media query is already in the collection, this method does nothing.

Syntax
------

```js
appendMedium(medium)
```

### Parameters

`medium`

A string containing the media query to add.

### Return value

None (undefined).

Examples
--------

 The following adds the media query `print` into the
 `MediaList` associated with the first stylesheet applied to the current document.

```js
const stylesheet = document.styleSheets[0];
stylesheet.media.appendMedium("print");
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-medialist-appendmedium |

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

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


MediaList: deleteMedium() method - Web APIs

MediaList: deleteMedium() method
================================

The `deleteMedium()` method of the `MediaList` interface removes from this `MediaList` the given media query.

Syntax
------

```js
deleteMedium(medium)
```

### Parameters

`medium`

A string containing the media query to remove from the list.

### Return value

None (undefined).

### Exceptions

`NotFoundError` `DOMException`

Thrown when the media query to remove is not in the list.

Examples
--------

 The following removes the media query `print` from the
 `MediaList` associated with the first stylesheet applied to the current document.

```js
const stylesheet = document.styleSheets[0];
stylesheet.media.removeMedium("print");
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-medialist-deletemedium |

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

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


TextFormat: rangeStart property - Web APIs

TextFormat: rangeStart property
===============================

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

The **`rangeStart`** property of the `TextFormat` interface indicates the start position of the text range that needs to be formatted with the given text format.

Value
-----

A `Number`.

Examples
--------

### Reading the range of text that needs to be formatted

The following example shows how to use the `textformatupdate` event's `rangeStart` and `rangeEnd` properties to determine the range of text that needs to be formatted. Note that the event listener callback in this example is only called when using an IME window to compose text.

```html
<div id="editor" style="height:200px;background:#eee;"></div>
```

```js
const editorEl = document.getElementById("editor");
const editContext = new EditContext(editorEl);
editorEl.editContext = editContext;

editContext.addEventListener("textformatupdate", (e) => {
  const formats = e.getTextFormats();

  for (const format of formats) {
    console.log(
      `IME wants to apply formatting between ${format.rangeStart} and ${format.rangeEnd}.`,
    );
  }
});
```

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

| Specification |
| --- |
| EditContext API # dom-textformat-rangestart |

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

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

See also
--------

* The `TextFormat` interface it belongs to.


TextFormat: underlineThickness property - Web APIs

TextFormat: underlineThickness property
=======================================

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

The **`underlineThickness`** property of the `TextFormat` interface indicates the thickness of the underline that needs to be applied to the text range that is being formatted.

Value
-----

A `String` that is one of the following values:

* `"none"`: No underline.
* `"thin"`: A thin underline.
* `"thick"`: A thick underline.
Examples
--------

### Reading the underline thickness that needs to be applied

The following example shows how to use the `textformatupdate` event's `underlineThickness` property to determine the underline thickness that needs to be applied to the text being formatted. Note that the event listener callback in this example is only called when using an IME window to compose text.

```html
<div id="editor" style="height:200px;background:#eee;"></div>
```

```js
const editorEl = document.getElementById("editor");
const editContext = new EditContext(editorEl);
editorEl.editContext = editContext;

editContext.addEventListener("textformatupdate", (e) => {
  const formats = e.getTextFormats();

  for (const format of formats) {
    console.log(
      `IME wants to apply a ${format.underlineThickness} underline between ${format.rangeStart} and ${format.rangeEnd}.`,
    );
  }
});
```

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

| Specification |
| --- |
| EditContext API # dom-textformat-underlinethickness |

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

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

See also
--------

* The `TextFormat` interface it belongs to.


TextFormat: rangeEnd property - Web APIs

TextFormat: rangeEnd property
=============================

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

The **`rangeEnd`** property of the `TextFormat` interface indicates the end position of the text range that needs to be formatted with the given text format.

Value
-----

A `Number`.

Examples
--------

### Reading the range of text that needs to be formatted

The following example shows how to use the `textformatupdate` event's `rangeStart` and `rangeEnd` properties to determine the range of text that needs to be formatted. Note that the event listener callback in this example is only called when using an IME window to compose text.

```html
<div id="editor" style="height:200px;background:#eee;"></div>
```

```js
const editorEl = document.getElementById("editor");
const editContext = new EditContext(editorEl);
editorEl.editContext = editContext;

editContext.addEventListener("textformatupdate", (e) => {
  const formats = e.getTextFormats();

  for (const format of formats) {
    console.log(
      `IME wants to apply formatting between ${format.rangeStart} and ${format.rangeEnd}.`,
    );
  }
});
```

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

| Specification |
| --- |
| EditContext API # dom-textformat-rangeend |

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

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

See also
--------

* The `TextFormat` interface it belongs to.


TextFormat: TextFormat() constructor - Web APIs

TextFormat: TextFormat() constructor
====================================

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

The **`TextFormat()`** constructor returns a new `TextFormat` object.

Syntax
------

```js
new TextFormat()
new TextFormat(options)
```

### Parameters

`options` Optional

An optional object with the following properties:

`rangeStart`

A number representing the start position of the text range that needs to be formatted.

`rangeEnd`

A number representing the end position of the text range that needs to be formatted.

`underlineStyle`

A string representing the underline style of the text range that needs to be formatted.

`underlinerThickness`

A string representing the underline thickness of the text range that needs to be formatted.

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

| Specification |
| --- |
| EditContext API # dom-textformat-constructor |

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

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

See also
--------

* The `TextFormat` interface it belongs to.


TextFormat: underlineStyle property - Web APIs

TextFormat: underlineStyle property
===================================

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

The **`underlineStyle`** property of the `TextFormat` interface indicates the style of the underline that needs to be applied to the text range that is being formatted.

Value
-----

A `String` that is one of the following values:

* `"none"`: No underline.
* `"solid"`: A solid underline.
* `"double"`: A double underline.
* `"dotted"`: A dotted underline.
* `"dashed"`: A dashed underline.
* `"wavy"`: A wavy underline.
Examples
--------

### Reading the underline style that needs to be applied

The following example shows how to use the `textformatupdate` event's `underlineStyle` property to determine the underline style that needs to be applied to the text being formatted. Note that the event listener callback in this example is only called when using an IME window to compose text.

```html
<div id="editor" style="height:200px;background:#eee;"></div>
```

```js
const editorEl = document.getElementById("editor");
const editContext = new EditContext(editorEl);
editorEl.editContext = editContext;

editContext.addEventListener("textformatupdate", (e) => {
  const formats = e.getTextFormats();

  for (const format of formats) {
    console.log(
      `IME wants to apply a ${format.underlineStyle} underline between ${format.rangeStart} and ${format.rangeEnd}.`,
    );
  }
});
```

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

| Specification |
| --- |
| EditContext API # dom-textformat-underlinestyle |

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

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

See also
--------

* The `TextFormat` interface it belongs to.


Using the Window Management API - Web APIs

Using the Window Management API
===============================

This guide explains how to use the Window Management API. The example code seen below is taken from our Multi-window learning environment example (see the source code).

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

You can feature detect the Window Management API by checking for the existence of `getScreenDetails` in the current `window` instance. For example, you might want to provide a button to open a multi-window display if the API is supported, or a different experience such as creating links to the different pages if it isn't:

```js
if ("getScreenDetails" in window) {
  // The Window Management API is supported
  createButton();
} else {
  // The Window Management API is not supported
  createLinks(sites);
}
```

Basic usage
-----------

The core of the Windows Management API is the `Window.getScreenDetails()` method, which returns an object containing details of all the screens available to the user's system:

```js
const screenDetails = await window.getScreenDetails();

// Return the number of screens
const noOfScreens = screenDetails.screens.length;
```

When `getScreenDetails()` is invoked, the user will be asked for permission to manage windows on all their displays (the status of this permission can be checked using `Permissions.query()` to query `window-management`). If the user grants permission, a `ScreenDetails` object is returned. This object contains the following properties:

* `screens`: An array of `ScreenDetailed` objects, each one containing detailed information about a separate screen available to the system (see below). This array is also useful for determining the number of available screens, via `screens.length`.
* `currentScreen`: A single `ScreenDetailed` object containing detailed information about the screen that the current browser window is displayed in.

`ScreenDetailed` objects inherit the properties of the `Screen` interface, and contain useful information for placing windows on specific screens.

**Note:** You can gate functionality based on whether the user has more than one screen available using the `Window.screen.isExtended` property. This returns `true` if the device has multiple screens, and `false` if not.

### Opening windows

You'll still need to use `Window.open()` to open and manage windows, but the above provides you with better information for doing so in a multi-screen environment. For example, a utility function might look like so:

```js
// Array to hold references to the currently open windows
let windowRefs = [];

// ...

function openWindow(left, top, width, height, url) {
  const windowFeatures = `left=${left},top=${top},width=${width},height=${height}`;
  const windowRef = window.open(
    url,
    "\_blank", // needed for it to open in a new window
    windowFeatures,
  );

  if (windowRef === null) {
    // If the browser is blocking new windows, close any windows that were
    // able to open and display instructions to help the user fix this problem
    closeAllWindows();
    popoverElem.showPopover();
  } else {
    // Store a reference to the window in the windowRefs array
    windowRefs.push(windowRef);
  }
}
```

You would then invoke this function and open windows on specific screens like this:

```js
const screen1 = screenDetails.screens[0];
const screen2 = screenDetails.screens[1];
// Windows will be a third the width and the full height of the screen
// The available width of screen1, minus 3 times the horizontal browser chrome
// width, divided by 3
const windowWidth = Math.floor((screen1.availWidth - 3 \* WINDOW\_CHROME\_X) / 3);
// The available height of screen1, minus the vertical browser chrome width
const windowHeight = Math.floor(screen1.availHeight - WINDOW\_CHROME\_Y);

// Open a window a third of the width and the entire height of the primary screen
openWindow(
  screen1.availLeft,
  screen1.availTop,
  windowWidth,
  windowHeight,
  sites[1].url,
);

// ...
```

### Closing all windows

After opening each window, we add a reference to the `windowRefs` array. This allows you to, for example, close them all when one window is closed:

```js
function closeAllWindows() {
  // Loop through all window refs and close each one
  windowRefs.forEach((windowRef) => {
    windowRef.close();
  });
  windowRefs = [];
}

// Check whether one of our popup windows has been closed
// If so, close them all

closeMonitor = setInterval(checkWindowClose, 250);

function checkWindowClose() {
  if (windowRefs.some((windowRef) => windowRef.closed)) {
    closeAllWindows();
    clearInterval(closeMonitor);
  }
}
```

**Note:** In our experiments, the `setInterval()` polling method shown above seemed to work best for detecting window closure in the case of multiple windows. Using events such as `beforeunload`, `pagehide`, or `visibilitychange` proved unreliable because, when opening multiple windows at the same time, the rapid shift in focus/visibility seemed to fire the handler function prematurely.

**Note:** One concern with the above example is that it uses constant values to represent the size of the Chrome window UI portions in the calculations — `WINDOW_CHROME_X` and `WINDOW_CHROME_Y` — to get the window size calculations correct. To create precisely-sized windows on other future implementations of the API, you'd need to keep a small library of browser chrome sizes, and employ browser detection to discover which browser is rendering your app and choose the correct size for calculations. Or you can rely on less precise window sizes.

### Handling browser popup blockers

In modern browsers, a separate user gesture event is required for each `Window.open()` call, for security purposes. This prevents sites from spamming users with lots of windows. However, this poses an issue for multi-window applications. To work around this limitation, you can design your applications to:

* Open no more than one new window at once.
* Reuse existing windows to display different pages.
* Advise users on how to update their browser settings to allow multiple windows.

In our demo application, we have gone for the third option. Our `openWindow()` function contains the following section:

```js
// ...

if (windowRef === null) {
  // If the browser is blocking new windows, close any windows that were
  // able to open and display instructions to help the user fix this problem
  closeAllWindows();
  popoverElem.showPopover();
} else {
  // Store a reference to the window in the windowRefs array
  windowRefs.push(windowRef);
}

// ...
```

If the browser blocks a new window, the resulting `windowRef` will be `null`. In this case we run our `closeAllWindows()` function to close any windows that *did* manage to open before the blocking started, and show a popover element that explains how to disable the popup blocker.

Simple single-window per display case
-------------------------------------

If you want to open a single window on each available display that is the full width and height of the display, you could use a pattern like this:

```js
// Open a window on each screen of the device
for (const screen of screenDetails.screens) {
  openWindow(
    screen.availLeft,
    screen.availTop,
    screen.availWidth,
    screen.availHeight,
    url,
  );
}
```

Window management events
------------------------

The Window Management API provides some events for responding to changes in the available screens:

The `ScreenDetails` `screenschange` event

Fired when screens are connected to or disconnected from the system.

The `ScreenDetails` `currentscreenchange` event

Fired when the window's current screen changes in some way.

The `Screen` `change` event

Fired on a specific screen when it changes in some way.

So for example, you could use the `screenschange` event to detect when the available screens have changed (perhaps when a screen is plugged in or unplugged), report the change, close all windows, and update window arrangements to suit the new configuration:

```js
screenDetails.addEventListener("screenschange", () => {
  // If the new number of screens is different to the old number of screens,
  // report the difference
  if (screenDetails.screens.length !== noOfScreens) {
    console.log(
      `The screen count changed from ${noOfScreens} to ${screenDetails.screens.length}`,
    );
  }

  // If the windows are open, close them and then open them again
  // So that they fit with the new screen configuration
  if (windowRefs.length > 0) {
    closeAllWindows();
    openWindows();
  }
});
```

requestFullscreen() screen option
---------------------------------

The Window Management API adds a new `screen` option to the `requestFullscreen()` method that allows you to specify on which screen you want to put the element in fullscreen mode. For example, if you want to make it fullscreen on the primary OS screen:

```js
try {
  const primaryScreen = (await getScreenDetails()).screens.find(
    (screen) => screen.isPrimary,
  );
  await document.body.requestFullscreen({ screen: primaryScreen });
} catch (err) {
  console.error(err.name, err.message);
}
```


Multi-screen origin - Web APIs

Multi-screen origin
===================

The Window Management API introduces the concept of the **multi-screen origin** — this is the (0,0) coordinate of the host operating system (OS)'s virtual screen arrangement, around which all available screens and windows are positioned. The multi-screen origin is the top-left corner of the OS primary screen by convention, although the spec stipulates that it could be any arbitrary point within the virtual screen arrangement.

The primary screen can usually be specified by the user via OS settings, and generally contains OS UI features such as the taskbar/icon dock.

**Note:** Positive coordinate values are to the right and downwards on the screen arrangement, while negative ones are to the left and upwards.

Effects on existing web platform features
-----------------------------------------

The multi-screen origin is relevant to the following APIs:

* The values of `ScreenDetailed.left`, `ScreenDetailed.top`, `ScreenDetailed.availLeft`, and `ScreenDetailed.availTop` for each available screen are reported relative to the multi-screen origin.
* The values of `Window.screenLeft`, `Window.screenTop`, `Window.screenX`, `Window.screenY` for each window are reported relative to the multi-screen origin.
* When using `Window.moveTo()` and `Window.open()`, windows are positioned relative to the multi-screen origin.

**Note:** Not all browsers officially support multi-screen origin, but some have their own non-standard implementations. You are advised to check the browser compatibility information of the above features for the behavior in each browser.

Visual examples
---------------

Say we have an external monitor of resolution 1920 x 1080 set as the primary monitor, and an internal laptop display of resolution 1440 x 900 set as a secondary monitor. Let's also say that the OS UI takes up 25px at the top of the screen, and is only drawn on the primary screen.

If the secondary screen was positioned directly to the right of the primary screen, top screen edges in line:

* The primary screen `left`/`top` values would be (0,0) while its `availLeft`/`availTop` values would be (0,25) — the OS UI thickness is added on.
* The secondary screen `left`/`top` values would be (1920,0) while its `availLeft`/`availTop` values would also be (1920,0) — the OS UI is not drawn on the secondary screen.

![Two rectangles representing the primary screen with the secondary screen positioned to the right, as described above](/en-US/docs/Web/API/Window_Management_API/Multi-screen_origin/primary-screen-left.png)

However, if the secondary screen was positioned directly to the left of the primary screen, top screen edges in line:

* The primary screen `left`/`top` values would still be (0,0) while its `availLeft`/`availTop` values would be (0,25).
* The secondary screen `left`/`top` values would be (-1440,0) while its `availLeft`/`availTop` values would also be (-1440,0).

![Two rectangles representing the primary screen with the secondary screen positioned to the left, as described above](/en-US/docs/Web/API/Window_Management_API/Multi-screen_origin/primary-screen-right.png)


HighlightRegistry: entries() method - Web APIs

HighlightRegistry: entries() method
===================================

The **`entries()`** method of the `HighlightRegistry` interface returns a new Iterator object that contains the `[name, highlight]` pairs for each element in the `HighlightRegistry` object, in insertion order.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.entries()`.

Syntax
------

```js
entries()
```

### Return value

A new iterator object that contains an array of `[name, highlight]` for each `Highlight` object in the `HighlightRegistry`, in insertion order.

Examples
--------

The code snippet below creates and registers two new highlights, and then logs the highlights and their names by using the iterator returned by the `entries()` method:

```js
const myHighlight1 = new Highlight();
const myHighlight2 = new Highlight();

CSS.highlights.set("first-highlight", myHighlight1);
CSS.highlights.set("second-highlight", myHighlight2);

const iter = CSS.highlights.entries();

console.log(iter.next().value); // ['first-highlight', Highlight]
console.log(iter.next().value); // ['second-highlight', Highlight]
```

The following code example shows how to iterate over the highlights in the registry by using a `for...of` loop:

```js
const myHighlight1 = new Highlight();
const myHighlight2 = new Highlight();

CSS.highlights.set("first-highlight", myHighlight1);
CSS.highlights.set("second-highlight", myHighlight2);

for (const [name, highlight] of CSS.highlights.entries()) {
  console.log(`Highlight ${name}`, highlight);
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.entries |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: delete() method - Web APIs

HighlightRegistry: delete() method
==================================

The **`delete()`** method of the `HighlightRegistry` interface removes a the named `Highlight` object from the `HighlightRegistry`.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.delete()`.

Syntax
------

```js
delete(customHighlightName)
```

### Parameters

`customHighlightName`

The name, as a `String`, of the `Highlight` object to remove from the `HighlightRegistry`.

### Return value

Returns `true` if a `Highlight` object under the provided name was in the `HighlightRegistry`; otherwise `false`.

Examples
--------

The following code sample registers a highlight in the registry, and then deletes it:

```js
const myHighlight = new Highlight(range1, range2);

CSS.highlights.set("my-highlight", myHighlight);

CSS.highlights.delete("foo"); // false
CSS.highlights.delete("my-highlight"); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.delete |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: clear() method - Web APIs

HighlightRegistry: clear() method
=================================

The **`clear()`** method of the `HighlightRegistry` interface removes all the `Highlight` objects registered in the `HighlightRegistry`.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.clear()`.

Syntax
------

```js
clear()
```

### Return value

None (`undefined`).

Examples
--------

The code snippet below registers two highlight objects in the registry and then clears the registry:

```js
const customHighlight1 = new Highlight(range1, range2);
const customHighlight2 = new Highlight(range3, range4, range5);

CSS.highlights.set("custom-highlight-1", customHighlight1);
CSS.highlights.set("custom-highlight-2", customHighlight2);

console.log(CSS.highlights.size); // 2

CSS.highlights.clear();
console.log(CSS.highlights.size); // 0
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.clear |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: has() method - Web APIs

HighlightRegistry: has() method
===============================

The **`has()`** method of the `HighlightRegistry` interface returns a boolean indicating whether or not a `Highlight` object with the specified name exists in the registry.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.has()`.

Syntax
------

```js
has(name)
```

### Parameters

`name`

The name of the `Highlight` object to test for presence in the registry.

### Return value

Returns `true` if a highlight with the specified name exists in the registry; otherwise `false`.

Examples
--------

```js
const fooHighlight = new Highlight();
CSS.highlights.set("foo", fooHighlight);

myHighlight.has("foo"); // true
myHighlight.has("bar"); // false
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.has |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: get() method - Web APIs

HighlightRegistry: get() method
===============================

The **`get()`** method of the `HighlightRegistry` interface returns the named `Highlight` object from the registry.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.get()`.

Syntax
------

```js
get(name)
```

### Parameters

`name`

The name of the `Highlight` object to return from the registry. The name must be a `String`.

### Return value

The `Highlight` object associated with the specified name, or `undefined` if the name can't be found in the `HighlightRegistry`.

Examples
--------

The following code sample demonstrates how to create a new `Highlight`, add it to the registry, and retrieve it by its name using the `get()` method:

```js
const fooHighlight = new Highlight();
CSS.highlights.set("foo", fooHighlight);

console.log(CSS.highlights.get("foo")); // Returns the fooHighlight object.
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.get |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: keys() method - Web APIs

HighlightRegistry: keys() method
================================

The **`keys()`** method of the `HighlightRegistry` interface returns a new Iterator object that contains the keys for each `Highlight` object in the `HighlightRegistry` object in insertion order.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.keys()`.

Syntax
------

```js
keys()
```

### Return value

A new iterator object containing the names of each `Highlight` object in the registry, in insertion order.

Examples
--------

The following code snippet shows how to create and register three `Highlight` objects, and use the iterator returned by the `keys()` method to log their names:

```js
const fooHighlight = new Highlight();
const barHighlight = new Highlight();
const bazHighlight = new Highlight();

CSS.highlights.set("foo", fooHighlight);
CSS.highlights.set("bar", barHighlight);
CSS.highlights.set("baz", bazHighlight);

const iter = CSS.highlights.keys();

console.log(iter.next().value); // "foo"
console.log(iter.next().value); // "bar"
console.log(iter.next().value); // "baz"
```

The following code example shows how to iterate over the highlights in the registry by using a `for...of` loop:

```js
const fooHighlight = new Highlight();
const barHighlight = new Highlight();
const bazHighlight = new Highlight();

CSS.highlights.set("foo", fooHighlight);
CSS.highlights.set("bar", barHighlight);
CSS.highlights.set("baz", bazHighlight);

for (const name of CSS.highlights.keys()) {
  console.log(name);
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.keys |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: set() method - Web APIs

HighlightRegistry: set() method
===============================

The **`set()`** method of the `HighlightRegistry` interface adds or updates a `Highlight` object in the registry with the specified name.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.set()`.

Syntax
------

```js
set(name, highlight)
```

### Parameters

`name`

The name of the `Highlight` object to add or update. The name must be a `String`.

`highlight`

The `Highlight` object to add or update. This must be a `Highlight` interface instance.

### Return value

The `HighlightRegistry` object.

Examples
--------

### Using set()

```js
const fooHighlight = new Highlight();
CSS.highlights.set("foo", fooHighlight);
```

### Using set() with chaining

Since the `set()` method returns back the registry, you can chain the method call like below:

```js
const fooHighlight = new Highlight();
const barHighlight = new Highlight();
const bazHighlight = new Highlight();

CSS.highlights
  .set("foo", fooHighlight)
  .set("bar", barHighlight)
  .set("baz", bazHighlight);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.set |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: values() method - Web APIs

HighlightRegistry: values() method
==================================

The **`values()`** method of the `HighlightRegistry` interface returns a new Iterator object that contains the values for each `Highlight` object in the `HighlightRegistry` object in insertion order.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.values()`.

Syntax
------

```js
values()
```

### Return value

A new iterator object containing each `Highlight` object in the registry, in insertion order.

Examples
--------

The following code snippet shows how to create and register three `Highlight` objects, and use the iterator returned by the `values()` method to log the highlights:

```js
const fooHighlight = new Highlight();
const barHighlight = new Highlight();
const bazHighlight = new Highlight();

CSS.highlights.set("foo", fooHighlight);
CSS.highlights.set("bar", barHighlight);
CSS.highlights.set("baz", bazHighlight);

const iter = CSS.highlights.values();

console.log(iter.next().value); // Highlight
console.log(iter.next().value); // Highlight
console.log(iter.next().value); // Highlight
```

The following code example shows how to iterate over the highlights in the registry by using a `for...of` loop:

```js
const fooHighlight = new Highlight();
const barHighlight = new Highlight();
const bazHighlight = new Highlight();

CSS.highlights.set("foo", fooHighlight);
CSS.highlights.set("bar", barHighlight);
CSS.highlights.set("baz", bazHighlight);

for (const highlight of CSS.highlights.values()) {
  console.log(highlight); // Highlight
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.values |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: size property - Web APIs

HighlightRegistry: size property
================================

The **`size`** property returns the number of `Highlight` objects in the `HighlightRegistry`.

Value
-----

A read-only integer indicating how many `Highlight` objects the registry contains.

Examples
--------

### Using size

```js
const highlight1 = new Highlight();
const highlight2 = new Highlight();

CSS.highlights.set("highlight-1", highlight1);
CSS.highlights.set("highlight-2", highlight2);

console.log(CSS.highlights.size); // 2
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-map.prototype.size |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


HighlightRegistry: forEach() method - Web APIs

HighlightRegistry: forEach() method
===================================

The **`forEach()`** method of the `HighlightRegistry` interface executes a provided function once for each `Highlight` object in the registry, in insertion order.

`HighlightRegistry` is a `Map`-like object, so this is similar to using `Map.forEach()`.

Syntax
------

```js
forEach(callbackFn)
forEach(callbackFn, thisArg)
```

### Parameters

`callback`

Function to execute for each `Highlight` object, taking three arguments:

`highlight`

The current highlight.

`name`

The highlight name.

`registry`

The registry object which `forEach()` was called upon.

`thisArg`

Value to use as `this` when executing `callbackFn`.

### Return value

None (`undefined`).

Examples
--------

The code snippet below shows how create a new highlight with two ranges, and then log the ranges by using the `forEach()` method:

```js
function logAllHighlights(highlight, name) {
  console.log(`Highlight ${name} exists in the registry`, highlight);
}

const customHighlight1 = new Highlight();
const customHighlight2 = new Highlight();
const customHighlight3 = new Highlight();

CSS.highlights.set("custom-highlight-1", customHighlight1);
CSS.highlights.set("custom-highlight-2", customHighlight2);
CSS.highlights.set("custom-highlight-3", customHighlight3);

CSS.highlights.forEach(logAllHighlights);
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.foreach |

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

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

See also
--------

* The CSS Custom Highlight API
* CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web


CSSKeyframeRule: keyText property - Web APIs

CSSKeyframeRule: keyText property
=================================

The **`keyText`** property of the `CSSKeyframeRule` interface represents the keyframe selector as a comma-separated list of percentage values. The from and to keywords map to 0% and 100%, respectively.

Value
-----

A string.

### Exceptions

`SyntaxError`

Thrown if `keyText` is updated with an invalid keyframe selector, in which case `keyText` remains untouched.

Examples
--------

 The CSS includes a keyframes at-rule. This will be the first `CSSRule` returned by `document.styleSheets[0].cssRules`.
 `myRules[0]` returns a `CSSKeyframesRule` object, which will contain individual `CSSKeyFrameRule` objects for each keyframe.

```css
@keyframes slidein {
  from {
    transform: translateX(0%);
  }

  to {
    transform: translateX(100%);
  }
}
```

```js
let myRules = document.styleSheets[0].cssRules;
let keyframes = myRules[0]; // a CSSKeyframesRule
console.log(keyframes[0].keyText); // a string containing 0%
```

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

| Specification |
| --- |
| CSS Animations Level 1 # dom-csskeyframerule-keytext |

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

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


TaskSignal: priority property - Web APIs

TaskSignal: priority property
=============================

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 read-only **`priority`** property of the `TaskSignal` interface indicates the signal priority.

 The initial value is set in the associated `TaskController` by specifying it as an argument to the `TaskController` constructor (by default it is `"user-visible"`).
 The priority of the signal can be changed by calling `TaskController.setPriority()` on the associated controller.

 For tasks with a mutable priority, this value is used to set the initial task priority and later to change it.
 Tasks with an immutable priority will ignore the value.

Value
-----

 A string indicating the signal priority.
 This will be one of: `"user-blocking"`, `"user-visible"`, `"background"`.

Examples
--------

 The `priority` is most commonly used by developers to determine the new priority following `prioritychange` events.
 See TaskSignal: prioritychange event for a live example.

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

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

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

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


TaskSignal: any() static method - Web APIs

TaskSignal: any() static method
===============================

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

The **`TaskSignal.any()`** static method takes an iterable of `AbortSignal` objects and returns a `TaskSignal`. The returned task signal is aborted when any of the abort signals is aborted.

When the task signal is aborted, its `reason` property will be set to the reason of the first signal that is aborted.

Syntax
------

```js
TaskSignal.any(signals)
TaskSignal.any(signals, init)
```

### Parameters

`signals`

An iterable (such as an `Array`) of abort signals.

`init` Optional

Contains optional configuration parameters. Currently only one property is defined:

`priority` Optional

One of the following:

* A string which is one of `user-blocking`, `user-visible` and `background`.
* A `TaskSignal`.

### Return value

A `TaskSignal` instance. It will be aborted when the first signal passed into `signals` is aborted. When this happens:

* Its `reason` property will be set to the reason of the signal that caused this signal to abort.
* Its `priority` property will be determined by the `priority` parameter:
    + If the `priority` parameter was a string, it will be the value of the string.
    + If the `priority` parameter was a `TaskSignal`, it will be the value of that signal's `priority`.
Examples
--------

### Using `TaskSignal.any()`

This example demonstrates combining both a signal from a `TaskController`, and a timeout signal from `TaskSignal.timeout()`.

```js
const cancelDownloadButton = document.getElementById("cancelDownloadButton");

const userCancelController = new TaskController({
  priority: "user-visible",
});

cancelDownloadButton.addEventListener("click", () => {
  userCancelController.abort();
});

// Timeout after 5 minutes
const timeoutSignal = TaskSignal.timeout(1\_000 \* 60 \* 5);

// This signal will abort when either the user clicks the cancel button or 5 minutes is up whichever is sooner
const combinedSignal = TaskSignal.any([
  userCancelController.signal,
  timeoutSignal,
]);

try {
  const res = await fetch(someUrlToDownload, {
    // Stop the fetch when any of the
    signal: combinedSignal,
  });
  const body = await res.blob();
  // Do something with downloaded content
  // ...
} catch (e) {
  if (e.name === "AbortError") {
    // Cancelled by the user
  } else if (e.name === "TimeoutError") {
    // Show user that download timed out
  } else {
    // Other error, e.g. network error
  }
}
```

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

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

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

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

See also
--------

* `AbortSignal.any()`


TaskSignal: prioritychange event - Web APIs

TaskSignal: prioritychange event
================================

The **`prioritychange`** event is sent to a `TaskSignal` if its priority is changed.

Syntax
------

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

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

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

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

A `TaskPriorityChangeEvent`. Inherits from `Event`.

Event

TaskPriorityChangeEventEvent properties
----------------

`TaskPriorityChangeEvent.previousPriority`

 Indicates the previous priority of the task (before it was changed).
 The new/updated priority is read from `event.target.priority` (`TaskSignal.priority`).

Examples
--------

The example below shows how to listen for the `prioritychange` event on a `TaskSignal`.
```

<textarea id="log" style="min-height: 70px; width: 95%"></textarea>
```

```
let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}
```

 First we create a controller, and add an event listener to its signal.
 When handling the event we use `previousPriority` on the event to get the original priority and `TaskSignal.priority` on the event target to get the new/current priority.

The task is then posted, passing in the signal, and then we immediately change the priority.

```js
if ("scheduler" in this) {
  // Declare a TaskController, setting its signal priority to 'user-blocking'
  const controller = new TaskController({ priority: "user-blocking" });

  // Listen for 'prioritychange' events on the controller's signal.
  controller.signal.addEventListener("prioritychange", (event) => {
    const previousPriority = event.previousPriority;
    const newPriority = event.target.priority;
    mylog(`Priority changed from ${previousPriority} to ${newPriority}.`);
  });

  // Post task using the controller's signal.
  // The signal priority sets the initial priority of the task
  scheduler.postTask(
    () => {
      mylog("Task 1");
    },
    { signal: controller.signal },
  );

  // Change the priority to 'background' using the controller
  controller.setPriority("background");
}
```

**Note:** The code above uses a custom logging function `mylog()` to log to the text area below.
 This is hidden as it isn't relevant to the example.

 The output below demonstrates shows that the task's priority changed from `user-blocking` to `background`.
 This happens before the task is executed, but could also happen when the task is running.

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

| Specification |
| --- |
| Prioritized Task Scheduling # ref-for-eventdef-tasksignal-prioritychange |
| Prioritized Task Scheduling # dom-tasksignal-onprioritychange |

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

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


CaptureController: CaptureController() constructor - Web APIs

CaptureController: CaptureController() constructor
==================================================

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

The `CaptureController` constructor creates a new `CaptureController` object instance.

Syntax
------

```js
CaptureController()
```

### Parameters

None.

Examples
--------

```js
// Create a new CaptureController instance
const controller = new CaptureController();

// Prompt the user to share a tab, window, or screen.
const stream = await navigator.mediaDevices.getDisplayMedia({ controller });

// Query the displaySurface value of the captured video track
const [track] = stream.getVideoTracks();
const displaySurface = track.getSettings().displaySurface;

if (displaySurface == "browser") {
  // Focus the captured tab.
  controller.setFocusBehavior("focus-captured-surface");
} else if (displaySurface == "window") {
  // Do not move focus to the captured window.
  // Keep the capturing page focused.
  controller.setFocusBehavior("no-focus-change");
}
```

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

| Specification |
| --- |
| Screen Capture # dom-capturecontroller-setfocusbehavior |

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

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

See also
--------

* Screen Capture API
* `MediaDevices.getDisplayMedia()`
* Better screen sharing with Conditional Focus


CaptureController: setFocusBehavior() method - Web APIs

CaptureController: setFocusBehavior() method
============================================

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

The `CaptureController` interface's **`setFocusBehavior()`** method controls whether the captured tab or window will be focused when an associated `MediaDevices.getDisplayMedia()` `Promise` fulfills, or whether the focus will remain with the tab containing the capturing app.

You can set this behavior multiple times before the `MediaDevices.getDisplayMedia()` call, or once immediately after its `Promise` resolves. After that, the focus behavior is said to be finalized, and can't be changed.

Syntax
------

```js
setFocusBehavior(focusBehavior)
```

### Parameters

`focusBehavior`

An enumerated value that describes whether the user agent should transfer focus to the captured display surface, or keep the capturing app focused. Possible values are `focus-captured-surface` (transfer focus) and `no-focus-change` (keep focus on the capturing app).

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if:

* The capture stream has been stopped.
* The user chose to share a screen (`displaySurface` type `monitor`) rather than a `browser` tab or `window` — you can't focus a monitor. In this case the exception is thrown after the `MediaDevices.getDisplayMedia()` `Promise` resolves.
* Enough time has elapsed after the `MediaDevices.getDisplayMedia()` `Promise` fulfills that the focus behavior has been finalized.

Examples
--------

```js
// Create a new CaptureController instance
const controller = new CaptureController();

// Prompt the user to share a tab, window, or screen.
const stream = await navigator.mediaDevices.getDisplayMedia({ controller });

// Query the displaySurface value of the captured video track
const [track] = stream.getVideoTracks();
const displaySurface = track.getSettings().displaySurface;

if (displaySurface == "browser") {
  // Focus the captured tab.
  controller.setFocusBehavior("focus-captured-surface");
} else if (displaySurface == "window") {
  // Do not move focus to the captured window.
  // Keep the capturing page focused.
  controller.setFocusBehavior("no-focus-change");
}
```

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

| Specification |
| --- |
| Screen Capture # dom-capturecontroller-setfocusbehavior |

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

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

See also
--------

* Screen Capture API
* `MediaDevices.getDisplayMedia()`
* Better screen sharing with Conditional Focus