repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/connection/index.md
--- title: "WorkerNavigator: connection property" short-title: connection slug: Web/API/WorkerNavigator/connection page-type: web-api-instance-property browser-compat: api.WorkerNavigator.connection --- {{APIRef("Network Information API")}} The **`WorkerNavigator.connection`** read-only property returns a {{domxref("NetworkInformation")}} object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered. This could be used to select high definition content or low definition content based on the user's connection. ## Value A {{domxref("NetworkInformation")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Online and offline events](/en-US/docs/Web/API/Navigator/onLine) - [Network Information API](/en-US/docs/Web/API/Network_Information_API)
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/locks/index.md
--- title: "WorkerNavigator: locks property" short-title: locks slug: Web/API/WorkerNavigator/locks page-type: web-api-instance-property browser-compat: api.WorkerNavigator.locks --- {{APIRef("Web Locks API")}}{{securecontext_header}} The **`locks`** read-only property of the {{domxref("WorkerNavigator")}} interface returns a {{domxref("LockManager")}} object which provides methods for requesting a new {{domxref('Lock')}} object and querying for an existing `Lock` object. ## Value A {{domxref("LockManager")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/permissions/index.md
--- title: "WorkerNavigator: permissions property" short-title: permissions slug: Web/API/WorkerNavigator/permissions page-type: web-api-instance-property browser-compat: api.WorkerNavigator.permissions --- {{APIRef("Web Workers API")}} The **`WorkerNavigator.permissions`** read-only property returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the [Permissions API](/en-US/docs/Web/API/Permissions_API). ## Value A {{domxref("Permissions")}} object. ## Examples ```js navigator.permissions.query({ name: "notifications" }).then((result) => { if (result.state === "granted") { showNotification(); } else if (result.state === "prompt") { requestNotificationPermission(); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Permissions API](/en-US/docs/Web/API/Permissions_API) - [Web Worker API](/en-US/docs/Web/API/Web_Workers_API)
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/storage/index.md
--- title: "WorkerNavigator: storage property" short-title: storage slug: Web/API/WorkerNavigator/storage page-type: web-api-instance-property browser-compat: api.WorkerNavigator.storage --- {{securecontext_header}}{{APIRef("Storage")}} The **`storage`** read-only property of the {{domxref("WorkerNavigator")}} interface returns the singleton {{domxref("StorageManager")}} object used to access the overall storage capabilities of the browser for the current site or app. The returned object lets you examine and configure persistence of data stores and learn approximately how much more space your browser has available for local storage use. ## Value A {{domxref("StorageManager")}} object you can use to maintain persistence for stored data, as well as to determine roughly how much room there is for data to be stored. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("StorageManager")}} - {{domxref("WorkerNavigator")}}
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/globalprivacycontrol/index.md
--- title: "WorkerNavigator: globalPrivacyControl property" short-title: globalPrivacyControl slug: Web/API/WorkerNavigator/globalPrivacyControl page-type: web-api-instance-property status: - experimental - non-standard browser-compat: api.WorkerNavigator.globalPrivacyControl --- {{APIRef("DOM")}}{{SeeCompatTable}}{{non-standard_header}} The **`WorkerNavigator.globalPrivacyControl`** read-only property returns the user's Global Privacy Control setting for the current website. This setting indicates whether the user consents to the website or service selling or sharing their personal information with third parties. The value of the property reflects that of the {{httpheader("Sec-GPC")}} HTTP header. ## Value `true` if the user explicitly _does not_ grant consent to sell or share their data. `false` if the user either grants consent, or has not indicated a preference. ## Example ```js console.log(navigator.globalPrivacyControl); // "true" if the user has specifically indicated they do not want their data shared or sold, otherwise "false". ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("Sec-GPC")}} header - [globalprivacycontrol.org](https://globalprivacycontrol.org/) - [Global Privacy Control Spec](https://privacycg.github.io/gpc-spec/) - [Do Not Track on Wikipedia](https://en.wikipedia.org/wiki/Do_Not_Track)
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/devicememory/index.md
--- title: "WorkerNavigator: deviceMemory property" short-title: deviceMemory slug: Web/API/WorkerNavigator/deviceMemory page-type: web-api-instance-property browser-compat: api.WorkerNavigator.deviceMemory --- {{APIRef("Device Memory API")}}{{securecontext_header}} The **`deviceMemory`** read-only property of the {{domxref("WorkerNavigator")}} interface returns the approximate amount of device memory in gigabytes. The reported value is imprecise to curtail {{glossary("fingerprinting")}}. It's approximated by rounding down to the nearest power of 2, then dividing that number by 1024. It is then clamped within lower and upper bounds to protect the privacy of owners of very low-memory or high-memory devices. ## Value A floating point number; one of `0.25`, `0.5`, `1`, `2`, `4`, `8`. ## Examples The following code can be run in a worker: ```js const memory = navigator.deviceMemory; console.log(`This device has at least ${memory}GiB of RAM.`); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("Device-Memory")}} HTTP header
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/clearappbadge/index.md
--- title: "WorkerNavigator: clearAppBadge() method" short-title: clearAppBadge() slug: Web/API/WorkerNavigator/clearAppBadge page-type: web-api-instance-method browser-compat: api.WorkerNavigator.clearAppBadge --- {{APIRef("Badging API")}}{{securecontext_header}} The **`clearAppBadge()`** method of the {{domxref("WorkerNavigator")}} interface clears a badge on the current app's icon by setting it to `nothing`. The value `nothing` indicates that no badge is currently set, and the status of the badge is _cleared_. ## Syntax ```js-nolint clearAppBadge() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the document is not fully active. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the call was blocked by the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy). - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if {{domxref('PermissionStatus.state')}} is not `granted`. ## Examples Once all messages in an application have been read, call `clearAppBadge()` to clear the badge and remove the notification. ```js navigator.clearAppBadge(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Badging for app icons](https://developer.chrome.com/docs/capabilities/web-apis/badging-api/)
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/usb/index.md
--- title: "WorkerNavigator: usb property" short-title: usb slug: Web/API/WorkerNavigator/usb page-type: web-api-instance-property browser-compat: api.WorkerNavigator.usb --- {{APIRef("WebUSB API")}}{{SecureContext_Header}} The **`usb`** read-only property of the {{domxref("WorkerNavigator")}} interface returns a {{domxref("USB")}} object for the current document, providing access to [WebUSB API](/en-US/docs/Web/API/WebUSB_API) functionality. ## Value A {{domxref('USB')}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebUSB API](/en-US/docs/Web/API/WebUSB_API)
0
data/mdn-content/files/en-us/web/api/workernavigator
data/mdn-content/files/en-us/web/api/workernavigator/online/index.md
--- title: "WorkerNavigator: onLine property" short-title: onLine slug: Web/API/WorkerNavigator/onLine page-type: web-api-instance-property browser-compat: api.WorkerNavigator.onLine --- {{ApiRef("HTML DOM")}} Returns the online status of the browser. The property returns a boolean value, with `true` meaning online and `false` meaning offline. The property sends updates whenever the browser's ability to connect to the network changes. The update occurs when the user follows links or when a script requests a remote page. For example, the property should return `false` when users click links soon after they lose internet connection. Browsers implement this property differently. In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return `true`. So while you can assume that the browser is offline when it returns a `false` value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. To learn more, see the 2011 article, [Working Off the Grid](https://developer.chrome.com/docs/workbox/service-worker-overview/). In Firefox, switching the browser to offline mode sends a `false` value. ## Value `online` is a boolean `true` or `false`. ## Examples ### Basic usage To check if you are online in a worker, query `navigator.onLine`, as in the following example: ```js if (navigator.onLine) { console.log("online"); } else { console.log("offline"); } ``` If the browser doesn't support `navigator.onLine` the above example will always come out as `false`/`undefined`. ### Listening for changes in network status To see changes in the network state, use [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) to listen for the events on `online` and `offline`, as in the following example: ```js addEventListener("offline", (e) => { console.log("offline"); }); addEventListener("online", (e) => { console.log("online"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpudevice/index.md
--- title: GPUDevice slug: Web/API/GPUDevice page-type: web-api-interface status: - experimental browser-compat: api.GPUDevice --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPUDevice`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a logical GPU device. This is the main interface through which the majority of WebGPU functionality is accessed. A `GPUDevice` object is requested using the {{domxref("GPUAdapter.requestDevice()")}} method. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("GPUDevice.features", "features")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A {{domxref("GPUSupportedFeatures")}} object that describes additional functionality supported by the device. - {{domxref("GPUDevice.label", "label")}} {{Experimental_Inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - {{domxref("GPUDevice.limits", "limits")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A {{domxref("GPUSupportedLimits")}} object that describes the limits supported by the device. - {{domxref("GPUDevice.lost", "lost")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : Contains a {{jsxref("Promise")}} that remains pending throughout the device's lifetime and resolves with a {{domxref("GPUDeviceLostInfo")}} object when the device is lost. - {{domxref("GPUDevice.queue", "queue")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : Returns the primary {{domxref("GPUQueue")}} for the device. ## Instance methods _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("GPUDevice.createBindGroup", "createBindGroup()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUBindGroup")}} based on a {{domxref("GPUBindGroupLayout")}} that defines a set of resources to be bound together in a group and how those resources are used in shader stages. - {{domxref("GPUDevice.createBindGroupLayout", "createBindGroupLayout()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUBindGroupLayout")}} that defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating {{domxref("GPUBindGroup")}}s. - {{domxref("GPUDevice.createBuffer", "createBuffer()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUBuffer")}} in which to store raw data to use in GPU operations. - {{domxref("GPUDevice.createCommandEncoder", "createCommandEncoder()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUCommandEncoder")}}, which is used to encode commands to be issued to the GPU. - {{domxref("GPUDevice.createComputePipeline", "createComputePipeline()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUComputePipeline")}} that can control the compute shader stage and be used in a {{domxref("GPUComputePassEncoder")}}. - {{domxref("GPUDevice.createComputePipelineAsync", "createComputePipelineAsync()")}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUComputePipeline")}}, which can control the compute shader stage and be used in a {{domxref("GPUComputePassEncoder")}}, once the pipeline can be used without any stalling. - {{domxref("GPUDevice.createPipelineLayout", "createPipelineLayout()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUPipelineLayout")}} that defines the {{domxref("GPUBindGroupLayout")}}s used by a pipeline. {{domxref("GPUBindGroup")}}s used with the pipeline during command encoding must have compatible {{domxref("GPUBindGroupLayout")}}s. - {{domxref("GPUDevice.createQuerySet", "createQuerySet()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUQuerySet")}} that can be used to record the results of queries on passes, such as occlusion or timestamp queries. - {{domxref("GPUDevice.createRenderBundleEncoder", "createRenderBundleEncoder()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPURenderBundleEncoder")}} that can be used to pre-record bundles of commands. These can be reused in {{domxref("GPURenderPassEncoder")}}s via the {{domxref("GPURenderPassEncoder.executeBundles", "executeBundles()")}} method, as many times as required. - {{domxref("GPUDevice.createRenderPipeline", "createRenderPipeline()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPURenderPipeline")}} that can control the vertex and fragment shader stages and be used in a {{domxref("GPURenderPassEncoder")}} or {{domxref("GPURenderBundleEncoder")}}. - {{domxref("GPUDevice.createRenderPipelineAsync", "createRenderPipelineAsync()")}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPURenderPipeline")}}, which can control the vertex and fragment shader stages and be used in a {{domxref("GPURenderPassEncoder")}} or {{domxref("GPURenderBundleEncoder")}}, once the pipeline can be used without any stalling. - {{domxref("GPUDevice.createSampler", "createSampler()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUSampler")}}, which controls how shaders transform and filter texture resource data. - {{domxref("GPUDevice.createShaderModule", "createShaderModule()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUShaderModule")}} from a string of WGSL source code. - {{domxref("GPUDevice.createTexture", "createTexture()")}} {{Experimental_Inline}} - : Creates a {{domxref("GPUTexture")}} in which to store texture data to use in GPU rendering operations. - {{domxref("GPUDevice.destroy", "destroy()")}} {{Experimental_Inline}} - : Destroys the device, preventing further operations on it. - {{domxref("GPUDevice.importExternalTexture", "importExternalTexture()")}} {{Experimental_Inline}} - : Takes an {{domxref("HTMLVideoElement")}} as an input and returns a {{domxref("GPUExternalTexture")}} wrapper object containing a snapshot of the video that can be used in GPU rendering operations. - {{domxref("GPUDevice.popErrorScope", "popErrorScope()")}} {{Experimental_Inline}} - : Pops an existing GPU error scope from the error scope stack and returns a {{jsxref("Promise")}} that resolves to an object ({{domxref("GPUInternalError")}}, {{domxref("GPUOutOfMemoryError")}}, or {{domxref("GPUValidationError")}}) describing the first error captured in the scope, or `null` if no error occurred. - {{domxref("GPUDevice.pushErrorScope", "pushErrorScope()")}} {{Experimental_Inline}} - : Pushes a new GPU error scope onto the device's error scope stack, allowing you to capture errors of a particular type. ## Events - {{domxref("GPUDevice.uncapturederror_event", "uncapturederror")}} {{Experimental_Inline}} - : Fired when an error is thrown that has not been observed by a GPU error scope, to provide a way to report unexpected errors. Known error cases should be handled using {{domxref("GPUDevice.pushErrorScope", "pushErrorScope()")}} and {{domxref("GPUDevice.popErrorScope", "popErrorScope()")}}. ## Examples ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const device = await adapter.requestDevice(); const shaderModule = device.createShaderModule({ code: shaders, }); //... } ``` See the individual member pages listed above and the following demo sites for a lot more examples of `GPUDevice` usage: - [Basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/) - [Basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/) - [WebGPU samples](https://webgpu.github.io/webgpu-samples/) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createbindgroup/index.md
--- title: "GPUDevice: createBindGroup() method" short-title: createBindGroup() slug: Web/API/GPUDevice/createBindGroup page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createBindGroup --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createBindGroup()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUBindGroup")}} based on a {{domxref("GPUBindGroupLayout")}} that defines a set of resources to be bound together in a group and how those resources are used in shader stages. ## Syntax ```js-nolint createBindGroup(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `entries` - : An array of entry objects describing the resources to expose to the shader. There will be one for each corresponding entry described by the {{domxref("GPUBindGroupLayout")}} referenced in `layout`. Each entry object has the following properties: - `binding` - : A number representing a unique identifier for this resource binding, which matches the `binding` value of a corresponding {{domxref("GPUBindGroupLayout")}} entry. In addition, it matches the `n` index value of the corresponding [`@binding(n)`](https://gpuweb.github.io/gpuweb/wgsl/#attribute-binding) attribute in the shader ({{domxref("GPUShaderModule")}}) used in the related pipeline. - `resource` - : The resource to bind. This can be one of the following: - `GPUBufferBinding` (which wraps a {{domxref("GPUBuffer")}}; see [GPUBufferBinding objects](#gpubufferbinding_objects) for a definition) - {{domxref("GPUExternalTexture")}} - {{domxref("GPUSampler")}} - {{domxref("GPUTextureView")}} - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `layout` - : The {{domxref("GPUBindGroupLayout")}} that the `entries` of this bind group will conform to. ### GPUBufferBinding objects A `GPUBufferBinding` object can contain the following properties: - `buffer` - : The {{domxref("GPUBuffer")}} object you want to bind. - `offset` {{optional_inline}} - : The offset, in bytes, from the beginning of the `buffer` to the beginning of the range exposed to the shader by the buffer binding. If omitted, `offset` defaults to 0. - `size` {{optional_inline}} - : The size, in bytes, of the buffer binding. If omitted, `size` will be the range starting at `offset` and ending at the end of the `buffer`. If both `offset` and `size` are omitted, the entire buffer is exposed to the shader. ### Return value A {{domxref("GPUBindGroup")}} object instance. ### Validation The following criteria must be met when calling **`createBindGroup()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUBindGroup")}} object is returned: - The number of entries in the `layout` {{domxref("GPUBindGroupLayout")}} equals the number of entry objects in `entries`. - For each entry in the `layout` {{domxref("GPUBindGroupLayout")}}, the corresponding entry object in `entries` binds the correct resource type. For example, a `buffer` resource layout object has a `GPUBufferBinding` object specified in the corresponding binding. - If the resource layout object is a `buffer`: - The corresponding bound {{domxref("GPUBuffer")}}: - Has its bound part (as specified by `offset` and `size`) contained inside it completely, with a non-zero size. - Has a size bigger than the `buffer` resource layout's `minBindingSize`. - If the resource layout object `type` is `"uniform"`: - The bound {{domxref("GPUBuffer")}} has a `usage` that includes `GPUBufferUsage.UNIFORM`. - The effective size of the bound buffer segment is less than or equal to the {{domxref("GPUDevice")}}'s `maxUniformBufferBindingSize` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The specified `GPUBufferBinding` `offset` is a multiple of the {{domxref("GPUDevice")}}'s `minUniformBufferOffsetAlignment` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - If the resource layout object `type` is `"storage"` or `"read-only-storage"`: - The bound {{domxref("GPUBuffer")}} has a `usage` that includes `GPUBufferUsage.STORAGE`. - The effective size of the bound buffer segment is less than or equal to the {{domxref("GPUDevice")}}'s `maxStorageBufferBindingSize` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The effective size of the bound buffer segment is a multiple of 4. - The specified `GPUBufferBinding` `offset` is a multiple of the {{domxref("GPUDevice")}}'s `minStorageBufferOffsetAlignment` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - If the resource layout object is a `storageTexture`, the corresponding bound {{domxref("GPUTextureView")}}: - Has a `dimension` equal to the resource layout object's `viewDimension` (see {{domxref("GPUTexture.createView()")}} for more details of a texture view's settings). - Has a `format` equal to the resource layout object's `sampleType`. - Has a `mipLevelCount` equal to 1. - Is a view of a {{domxref("GPUTexture")}} with a `usage` that includes `GPUTextureUsage.STORAGE_BINDING`. - If the resource layout object is a `texture`, the corresponding bound {{domxref("GPUTextureView")}}: - Has a `dimension` equal to the resource layout object's `viewDimension` (see {{domxref("GPUTexture.createView()")}} for more details of a texture view's settings). - Has a `format` compatible with the resource layout object's `sampleType`. - Is a view of a {{domxref("GPUTexture")}} with a `usage` that includes `GPUTextureUsage.TEXTURE_BINDING`. - is a view of a {{domxref("GPUTexture")}} with a `sampleCount` greater than 1 if the resource layout object's `multisampled` property is `true`, or equal to 1 if it is `false`. ## Examples > **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples. ### Basic example Our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/) shows an example of creating a bind group layout and then using that as a template when creating a bind group. ```js // ... const bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage", }, }, ], }); const bindGroup = device.createBindGroup({ layout: bindGroupLayout, entries: [ { binding: 0, resource: { buffer: output, }, }, ], }); // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/limits/index.md
--- title: "GPUDevice: limits property" short-title: limits slug: Web/API/GPUDevice/limits page-type: web-api-instance-property status: - experimental browser-compat: api.GPUDevice.limits --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`limits`** read-only property of the {{domxref("GPUDevice")}} interface returns a {{domxref("GPUSupportedLimits")}} object that describes the limits supported by the device. All limit values will be included, and the limits requested during the creation of the device (i.e. when {{domxref("GPUAdapter.requestDevice()")}} is called) will be reflected in those values. > **Note:** Not all limits will be reported as expected, even if they are supported by the underlying hardware. See {{domxref("GPUAdapter.limits")}} for more details. ## Value A {{domxref("GPUSupportedLimits")}} object instance. ## Examples In the following code we query the `GPUAdapter.limits` value of `maxBindGroups` to see if it is equal to or greater than 6. Our theoretical example app ideally needs 6 bind groups, so if the returned value is >= 6, we add a maximum limit of 6 to the `requiredLimits` object. We then check that the expected limit has been set on the resulting device by logging its value to the console. ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const requiredLimits = {}; // App ideally needs 6 bind groups, so we'll try to request what the app needs if (adapter.limits.maxBindGroups >= 6) { requiredLimits.maxBindGroups = 6; } const device = await adapter.requestDevice({ requiredLimits, }); console.log(device.limits.maxBindGroups); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createrenderbundleencoder/index.md
--- title: "GPUDevice: createRenderBundleEncoder() method" short-title: createRenderBundleEncoder() slug: Web/API/GPUDevice/createRenderBundleEncoder page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createRenderBundleEncoder --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createRenderBundleEncoder()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPURenderBundleEncoder")}} that can be used to pre-record bundles of commands. These can be reused in {{domxref("GPURenderPassEncoder")}}s via the {{domxref("GPURenderPassEncoder.executeBundles", "executeBundles()")}} method, as many times as required. ## Syntax ```js-nolint createRenderBundleEncoder(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `colorFormats` - : An array of enumerated values specifying the expected color formats for render targets. For possible values, see the [`GPUTextureFormat` definition](https://gpuweb.github.io/gpuweb/#depth-or-stencil-format) in the spec. - `depthReadOnly` {{optional_inline}} - : A boolean. If `true`, specifies that executing any {{domxref("GPURenderBundle")}} created by the {{domxref("GPURenderBundleEncoder")}} will not modify the depth component of the `depthStencilFormat` when executed. If omitted, `depthReadOnly` will default to `false`. - `depthStencilFormat` {{optional_inline}} - : An enumerated value that specifies the expected depth-or-stencil format for render targets. For possible values, see the [Depth-stencil formats](https://gpuweb.github.io/gpuweb/#depth-or-stencil-format) section of the spec. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `sampleCount` {{optional_inline}} - : A number representing the expected sample count for render targets. - `stencilReadOnly` {{optional_inline}} - : A boolean. If `true`, specifies that executing any {{domxref("GPURenderBundle")}} created by the {{domxref("GPURenderBundleEncoder")}} will not modify the stencil component of the `depthStencilFormat` when executed. If omitted, `stencilReadOnly` will default to `false`. ### Return value A {{domxref("GPURenderBundleEncoder")}} object instance. ## Examples In the WebGPU Samples [Animometer example](https://webgpu.github.io/webgpu-samples/samples/animometer), numerous similar operations are done on many different objects simultaneously. A bundle of commands is encoded using the following function: ```js function recordRenderPass( passEncoder: GPURenderBundleEncoder | GPURenderPassEncoder ) { if (settings.dynamicOffsets) { passEncoder.setPipeline(dynamicPipeline); } else { passEncoder.setPipeline(pipeline); } passEncoder.setVertexBuffer(0, vertexBuffer); passEncoder.setBindGroup(0, timeBindGroup); const dynamicOffsets = [0]; for (let i = 0; i < numTriangles; ++i) { if (settings.dynamicOffsets) { dynamicOffsets[0] = i * alignedUniformBytes; passEncoder.setBindGroup(1, dynamicBindGroup, dynamicOffsets); } else { passEncoder.setBindGroup(1, bindGroups[i]); } passEncoder.draw(3, 1, 0, 0); } } ``` Later on, a {{domxref("GPURenderBundleEncoder")}} is created using `createRenderBundleEncoder()`, the function is invoked, and the command bundle is recorded into a {{domxref("GPURenderBundle")}} using {{domxref("GPURenderBundleEncoder.finish()")}}: ```js const renderBundleEncoder = device.createRenderBundleEncoder({ colorFormats: [presentationFormat], }); recordRenderPass(renderBundleEncoder); const renderBundle = renderBundleEncoder.finish(); ``` {{domxref("GPURenderPassEncoder.executeBundles()")}} is then used to reuse the work across multiple render passes to improve performance. Study the example code listing for the full context. ```js // ... return function doDraw(timestamp) { if (startTime === undefined) { startTime = timestamp; } uniformTime[0] = (timestamp - startTime) / 1000; device.queue.writeBuffer(uniformBuffer, timeOffset, uniformTime.buffer); renderPassDescriptor.colorAttachments[0].view = context .getCurrentTexture() .createView(); const commandEncoder = device.createCommandEncoder(); const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); if (settings.renderBundles) { passEncoder.executeBundles([renderBundle]); } else { recordRenderPass(passEncoder); } passEncoder.end(); device.queue.submit([commandEncoder.finish()]); }; // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/uncapturederror_event/index.md
--- title: "GPUDevice: uncapturederror event" short-title: uncapturederror slug: Web/API/GPUDevice/uncapturederror_event page-type: web-api-event status: - experimental browser-compat: api.GPUDevice.uncapturederror_event --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`uncapturederror`** event of the {{domxref("GPUDevice")}} interface is fired when an error is thrown that has not been observed by a GPU error scope, to provide a way to report unexpected errors. Known error cases should be handled using {{domxref("GPUDevice.pushErrorScope", "pushErrorScope()")}} and {{domxref("GPUDevice.popErrorScope", "popErrorScope()")}}. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("uncapturederror", (event) => {}); onuncapturederror = (event) => {}; ``` ## Event type An {{domxref("GPUUncapturedErrorEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("GPUUncapturedErrorEvent")}} ## Examples You could use something like the following as a global mechanism to pick up any errors that aren't handled by error scopes and capture them. ```js device.addEventListener("uncapturederror", (event) => { // Re-surface the error. console.error("A WebGPU error was not captured:", event.error); reportErrorToServer({ type: event.error.constructor.name, message: event.error.message, }); }); ``` See [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling) for more examples and information. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createsampler/index.md
--- title: "GPUDevice: createSampler() method" short-title: createSampler() slug: Web/API/GPUDevice/createSampler page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createSampler --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createSampler()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUSampler")}}, which controls how shaders transform and filter texture resource data. ## Syntax ```js-nolint createSampler() createSampler(descriptor) ``` ### Parameters - `descriptor` {{optional_inline}} - : An object containing the following properties: - `addressModeU` {{optional_inline}} - : An enumerated value specifying the behavior of the sampler when the sample footprint width extends beyond the width of the texture. Possible values are: - `"clamp-to-edge"`: The texture coordinates are clamped between 0.0 and 1.0, inclusive. - `"repeat"`: The texture coordinates wrap to the other side of the texture. - `"mirror-repeat"`: The texture coordinates wrap to the other side of the texture, but the texture is flipped when the integer part of the coordinate is odd. If omitted, `addressModeU` defaults to `"clamp-to-edge"`. - `addressModeV` {{optional_inline}} - : An enumerated value specifying the behavior of the sampler when the sample footprint height extends beyond the height of the texture. Possible and default values are the same as for `addressModeU`. - `addressModeW` {{optional_inline}} - : An enumerated value specifying the behavior of the sampler when the sample footprint depth extends beyond the depth of the texture. Possible and default values are the same as for `addressModeU`. - `compare` {{optional_inline}} - : If specified, the sampler will be a comparison sampler of the specified type. Possible (enumerated) values are: - `"never"`: Comparison tests never pass. - `"less"`: A provided value passes the comparison test if it is less than the sampled value. - `"equal"`: A provided value passes the comparison test if it is equal to the sampled value. - `"less-equal"`: A provided value passes the comparison test if it is less than or equal to the sampled value. - `"greater"`: A provided value passes the comparison test if it is greater than the sampled value. - `"not-equal"`: A provided value passes the comparison test if it is not equal to the sampled value. - `"greater-equal"`: A provided value passes the comparison test if it is greater than or equal to the sampled value. - `"always"`: Comparison tests always pass. Comparison samplers may use filtering, but the sampling results will be implementation-dependent and may differ from the normal filtering rules. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `lodMinClamp` {{optional_inline}} - : A number specifying the minimum level of detail used internally when sampling a texture. If omitted, `lodMinClamp` defaults to 0. - `lodMaxClamp` {{optional_inline}} - : A number specifying the maximum level of detail used internally when sampling a texture. If omitted, `lodMaxClamp` defaults to 32. - `maxAnisotropy` {{optional_inline}} - : Specifies the maximum anisotropy value clamp used by the sampler. If omitted, `maxAnisotropy` defaults to 1. Most implementations support `maxAnisotropy` values in a range between 1 and 16, inclusive. The value used will be clamped to the maximum value that the underlying platform supports. - `magFilter` {{optional_inline}} - : An enumerated value specifying the sampling behavior when the sample footprint is smaller than or equal to one texel. Possible values are: - `"nearest"`: Return the value of the texel nearest to the texture coordinates. - `"linear"`: Select two texels in each dimension and return a linear interpolation between their values. If omitted, `magFilter` defaults to `"nearest"`. - `minFilter` {{optional_inline}} - : An enumerated value specifying the sampling behavior when the sample footprint is larger than one texel. Possible and default values are the same as for `magFilter`. - `mipmapFilter` {{optional_inline}} - : An enumerated value specifying the behavior when sampling between mipmap levels. Possible and default values are the same as for `magFilter`. ### Return value A {{domxref("GPUSampler")}} object instance. ### Validation The following criteria must be met when calling **`createSampler()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUSampler")}} object is returned: - `lodMinClamp` is equal to or more than 0. - `lodMaxClamp` is equal to or more than `lodMinClamp`. - `maxAnisotropy` is equal to or more than 1. - If `maxAnisotropy` is more than 1, `magFilter`, `minFilter`, and `mipmapFilter` are `"linear"`. ## Examples The following snippet creates a `GPUSampler` that does trilinear filtering and repeats texture coordinates: ```js // ... const sampler = device.createSampler({ addressModeU: "repeat", addressModeV: "repeat", magFilter: "linear", minFilter: "linear", mipmapFilter: "linear", }); ``` The WebGPU samples [Shadow Mapping sample](https://webgpu.github.io/webgpu-samples/samples/shadowMapping) uses comparison samplers to sample from a depth texture to render shadows. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createbuffer/index.md
--- title: "GPUDevice: createBuffer() method" short-title: createBuffer() slug: Web/API/GPUDevice/createBuffer page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createBuffer --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createBuffer()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUBuffer")}} in which to store raw data to use in GPU operations. ## Syntax ```js-nolint createBuffer(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `mappedAtCreation` {{optional_inline}} - : A boolean. If set to `true`, the buffer will be mapped upon creation, meaning that you can set the values inside the buffer immediately by calling {{domxref("GPUBuffer.getMappedRange()")}}. The default value is `false`. Note that it is valid to set `mappedAtCreation: true` so you can set the buffer's initial data, even if the `GPUBufferUsage.MAP_READ` or `GPUBufferUsage.MAP_WRITE` usage flags are not set. - `size` - : A number representing the size of the buffer, in bytes. - `usage` - : The {{glossary("Bitwise flags", "bitwise flags")}} representing the allowed usages for the `GPUBuffer`. The possible values are in the [`GPUBuffer.usage` value table](/en-US/docs/Web/API/GPUBuffer/usage#value). Note that multiple possible usages can be specified by separating values with pipe symbols, for example: ```js usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.MAP_WRITE; ``` ### Return value A {{domxref("GPUBuffer")}} object instance. ### Validation The following criteria must be met when calling **`createBuffer()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUBuffer")}} object is returned: - A valid `usage` is specified. - `GPUBufferUsage.MAP_READ` is specified, and no additional flags are specified other than `GPUBufferUsage.COPY_DST`. - `GPUBufferUsage.MAP_WRITE` is specified, and no additional flags are specified other than `GPUBufferUsage.COPY_SRC`. - `mappedAtCreation: true` is specified, and the specified `size` is a multiple of 4. > **Note:** If the buffer allocation fails without any specific side-effects, a {{domxref("GPUOutOfMemoryError")}} object is generated. ## Examples In our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/), we create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access. ```js const output = device.createBuffer({ size: BUFFER_SIZE, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC, }); const stagingBuffer = device.createBuffer({ size: BUFFER_SIZE, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/features/index.md
--- title: "GPUDevice: features property" short-title: features slug: Web/API/GPUDevice/features page-type: web-api-instance-property status: - experimental browser-compat: api.GPUDevice.features --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`features`** read-only property of the {{domxref("GPUDevice")}} interface returns a {{domxref("GPUSupportedFeatures")}} object that describes additional functionality supported by the device. Only features requested during the creation of the device (i.e. when {{domxref("GPUAdapter.requestDevice()")}} is called) are included. > **Note:** Not all features will be available to WebGPU in all browsers that support it, even if the features are supported by the underlying hardware. See {{domxref("GPUAdapter.features")}} for more details. ## Value A {{domxref("GPUSupportedFeatures")}} object instance. This is a [setlike](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) object. ## Examples In the following code we check whether a {{domxref("GPUAdapter")}} has the `texture-compression-astc` feature available. If so, we push it into the array of `requiredFeatures`, and request a device with that feature requirement using {{domxref("GPUAdapter.requestDevice()")}}. We then log all items in the `GPUDevice.features` set to the console. This set should only contain a single item — `texture-compression-astc` — as that was the only feature requested when the device was created. ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } const requiredFeatures = []; if (adapter.features.has("texture-compression-astc")) { requiredFeatures.push("texture-compression-astc"); } const device = await adapter.requestDevice({ requiredFeatures, }); device.features.forEach((value) => { console.log(value); }); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/lost/index.md
--- title: "GPUDevice: lost property" short-title: lost slug: Web/API/GPUDevice/lost page-type: web-api-instance-property status: - experimental browser-compat: api.GPUDevice.lost --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`lost`** read-only property of the {{domxref("GPUDevice")}} interface contains a {{jsxref("Promise")}} that remains pending throughout the device's lifetime and resolves with a {{domxref("GPUDeviceLostInfo")}} object when the device is lost. {{domxref("GPUAdapter.requestDevice()")}} will never return `null`, and it will reject only if the request is invalid, i.e. it exceeds the capabilities of the {{domxref("GPUAdapter")}}. If a valid device request can't be fulfilled for some reason however it may resolve to a device that has already been lost. Additionally, devices can be lost at any time after creation for a variety of reasons (such as browser resource management or driver updates), so it's a good idea to always handle lost devices gracefully. Many causes for lost devices are transient, so you should try getting a new device once a previous one has been lost unless the loss was caused by the application intentionally destroying the device (i.e. with {{domxref("GPUDevice.destroy()")}}). Note that any WebGPU resources created with a previous device (buffers, textures, etc.) will need to be re-created with the new one. > **Note:** Also bear in mind that a `GPUAdapter` may become unavailable, e.g. if the physical GPU is unplugged from the system or disabled to save power. From then on, the adapter can no longer return valid devices, and will always return already-lost devices. ## Value A promise that resolves with a {{domxref("GPUDeviceLostInfo")}} object when the device is lost. ## Examples ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } // Create a GPUDevice let device = await adapter.requestDevice(descriptor); // Use lost to handle lost devices device.lost.then((info) => { console.error(`WebGPU device was lost: ${info.message}`); device = null; if (info.reason !== "destroyed") { init(); } }); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/queue/index.md
--- title: "GPUDevice: queue property" short-title: queue slug: Web/API/GPUDevice/queue page-type: web-api-instance-property status: - experimental browser-compat: api.GPUDevice.queue --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`queue`** read-only property of the {{domxref("GPUDevice")}} interface returns the primary {{domxref("GPUQueue")}} for the device. ## Value A {{domxref("GPUQueue")}} object instance. ## Examples Basic {{domxref("GPUQueue")}} access: ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } // Create a GPUDevice const device = await adapter.requestDevice(); // ... // Common queue use — end current frame by passing array of // command buffers to queue for execution device.queue.submit([commandEncoder.finish()]); // ... } ``` > **Note:** For more queue examples, see the {{domxref("GPUQueue")}} reference pages. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createtexture/index.md
--- title: "GPUDevice: createTexture() method" short-title: createTexture() slug: Web/API/GPUDevice/createTexture page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createTexture --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createTexture()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUTexture")}} in which to store 1D, 2D, or 3D arrays of data, such as images, to use in GPU rendering operations. ## Syntax ```js-nolint createTexture(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `dimension` {{optional_inline}} - : An enumerated value indicating the dimension level of the texture. Possible values are: - `"1d"`: The texture is one-dimensional. - `"2d"`: The texture is two-dimensional or an array of two-dimensional layers. - `"3d"`: The texture is three-dimensional. `dimension` defaults to `"2d"` if the value is omitted. - `format` - : An enumerated value specifying the format of the texture. See the [Texture formats](https://gpuweb.github.io/gpuweb/#enumdef-gputextureformat) section of the specification for all the possible values. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `mipLevelCount` {{optional_inline}} - : A number specifying the number of mip levels the texture will contain. If omitted, this defaults to 1. - `sampleCount` {{optional_inline}} - : A number specifying the texture's sample count. To be valid, the value must be 1 or 4. If omitted, this defaults to 1. A value higher than 1 indicates a multi-sampled texture. - `size` - : An object or array specifying the width, height, and depth/array layer count of the texture. The width value must always be specified, while the height and depth/array layer count values are optional and will default to 1 if omitted. What follows is a sample `size` array: ```js size: [16, 16, 2]; ``` The object equivalent would look like this: ```js size: { width: 16, height: 16, depthOrArrayLayers: 2 } ``` - `usage` - : The {{glossary("Bitwise_flags", "bitwise flags")}} representing the allowed usages for the `GPUTexture`. The possible values are in the [`GPUTexture.usage` value table](/en-US/docs/Web/API/GPUTexture/usage#value). Note that multiple possible usages can be specified by separating values with pipe symbols, for example: ```js usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT; ``` - `viewFormats` {{optional_inline}} - : An array of enumerated values specifying other [texture formats](https://gpuweb.github.io/gpuweb/#enumdef-gputextureformat) permitted when calling {{domxref("GPUTexture.createView()")}} on this texture, in addition to the texture format specified in its `format` value. ### Return value A {{domxref("GPUTexture")}} object instance. ### Validation The following criteria must be met when calling **`createTexture()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUTexture")}} object is returned: - A valid `usage` is specified. - The values specified in `size` (width, height, or depth/array layer count) are greater than 0. - `mipLevelCount` is greater than 0. - `sampleCount` is equal to 1 or 4. - If `dimension` is set to `"1d"`: - The `size` width value is less than or equal to the {{domxref("GPUDevice")}}'s `maxTextureDimension1D` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The `size` height and depth/array layer count values are equal to 1. - The `sampleCount` is equal to 1. - The `format` is not equal to a [compressed format](https://gpuweb.github.io/gpuweb/#compressed-format) or [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#depth-or-stencil-format). - If `dimension` is set to `"2d"`: - The `size` width and height values are less than or equal to the {{domxref("GPUDevice")}}'s `maxTextureDimension2D` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The `size` depth/array layer count value is less than or equal to the {{domxref("GPUDevice")}}'s `maxTextureArrayLayers` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - If `dimension` is set to `"3d"`: - The `size` width, and height, and depth/array layer count values are less than or equal to the {{domxref("GPUDevice")}}'s `maxTextureDimension3D` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The `sampleCount` value is equal to 1. - The `format` is not equal to a [compressed format](https://gpuweb.github.io/gpuweb/#compressed-format) or [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#depth-or-stencil-format). - The `size` width value is a multiple of the [texel block width](https://gpuweb.github.io/gpuweb/#texel-block-width). - The `size` height value is a multiple of the [texel block height](https://gpuweb.github.io/gpuweb/#texel-block-height). - If `sampleCount` is greater than 1: - `mipLevelCount` is equal to 1. - The `size` depth/array layer count value is equal to 1. - `usage` includes the `GPUTextureUsage.RENDER_ATTACHMENT` flag. - `usage` does not include the `GPUTextureUsage.STORAGE_BINDING` flag. - The specified format supports multi-sampling. - The `mipLevelCount` value is less than or equal to the [maximum miplevel count](https://gpuweb.github.io/gpuweb/#abstract-opdef-maximum-miplevel-count). - The formats specified in `format` and `viewFormats` are [compatible](https://gpuweb.github.io/gpuweb/#texture-view-format-compatible) with one another. - If `usage` includes the `GPUTextureUsage.RENDER_ATTACHMENT` flag: - `format` is a renderable format (meaning a color renderable format, or a [depth-or-stencil format](https://gpuweb.github.io/gpuweb/#depth-or-stencil-format)). - `dimension` is set to `"2d"`. - If `usage` includes the `GPUTextureUsage.STORAGE_BINDING` flag: - The specified `format` includes the `STORAGE_BINDING` capability (see the [Plain color formats](https://gpuweb.github.io/gpuweb/#plain-color-formats) table for reference). ## Examples In the WebGPU samples [Textured Cube sample](https://webgpu.github.io/webgpu-samples/samples/texturedCube), a texture to use on the faces of a cube is created by: - Loading the image into an {{domxref("HTMLImageElement")}} and creating an image bitmap using {{domxref("createImageBitmap()")}}. - Creating a new texture using `createTexture()`. - Copying the image bitmap into the texture using {{domxref("GPUQueue.copyExternalImageToTexture()")}}. ```js //... let cubeTexture; { const img = document.createElement("img"); img.src = new URL( "../../../assets/img/Di-3d.png", import.meta.url, ).toString(); await img.decode(); const imageBitmap = await createImageBitmap(img); cubeTexture = device.createTexture({ size: [imageBitmap.width, imageBitmap.height, 1], format: "rgba8unorm", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT, }); device.queue.copyExternalImageToTexture( { source: imageBitmap }, { texture: cubeTexture }, [imageBitmap.width, imageBitmap.height], ); } //... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createcomputepipeline/index.md
--- title: "GPUDevice: createComputePipeline() method" short-title: createComputePipeline() slug: Web/API/GPUDevice/createComputePipeline page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createComputePipeline --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createComputePipeline()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUComputePipeline")}} that can control the compute shader stage and be used in a {{domxref("GPUComputePassEncoder")}}. ## Syntax ```js-nolint createComputePipeline(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `compute` - : An object describing the compute shader entry point of the pipeline. This object can contain the following properties: - `constants` {{optional_inline}} - : A sequence of record types, with the structure `(id, value)`, representing override values for [WGSL constants that can be overridden in the pipeline](https://gpuweb.github.io/gpuweb/#typedefdef-gpupipelineconstantvalue). These behave like [ordered maps](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). In each case, the `id` is a key used to identify or select the record, and the `constant` is an enumerated value representing a WGSL. Depending on which constant you want to override, the `id` may take the form of the numeric ID of the constant, if one is specified, or otherwise the constant's identifier name. A code snippet providing override values for several overridable constants might look like this: ```js { // ... constants: { 0: false, 1200: 3.0, 1300: 2.0, width: 20, depth: -1, height: 15, } } ``` - `entryPoint` - : The name of the function in the `module` that this stage will use to perform its work. The corresponding shader function must have the `@compute` attribute to be identified as this entry point. See [Entry Point Declaration](https://gpuweb.github.io/gpuweb/wgsl/#entry-point-decl) for more information. - `module` - : A {{domxref("GPUShaderModule")}} object containing the [WGSL](https://gpuweb.github.io/gpuweb/wgsl/) code that this programmable stage will execute. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `layout` - : Defines the layout (structure, purpose, and type) of all the GPU resources (buffers, textures, etc.) used during the execution of the pipeline. Possible values are: - A {{domxref("GPUPipelineLayout")}} object, created using {{domxref("GPUDevice.createPipelineLayout()")}}, which allows the GPU to figure out how to run the pipeline most efficiently ahead of time. - A string of `"auto"`, which causes the pipeline to generate an implicit bind group layout based on any bindings defined in the shader code. If `"auto"` is used, the generated bind group layouts may only be used with the current pipeline. ### Return value A {{domxref("GPUComputePipeline")}} object instance. ### Validation The following criteria must be met when calling **`createComputePipeline()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUComputePipeline")}} object is returned: - The workgroup storage size used by the `module` referenced inside the `compute` property is less than or equal to the {{domxref("GPUDevice")}}'s `maxComputeWorkgroupStorageSize` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The `module` uses a number of compute invocations per workgroup less than or equal to the {{domxref("GPUDevice")}}'s `maxComputeInvocationsPerWorkgroup` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The `module`'s workgroup size is less than or equal to the {{domxref("GPUDevice")}}'s corresponding `maxComputeWorkgroupSizeX`, `maxComputeWorkgroupSizeY`, or `maxComputeWorkgroupSizeZ` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. ## Examples > **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples. ### Basic example Our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/) shows a process of: - Creating a bind group layout with {{domxref("GPUDevice.createBindGroupLayout()")}}. - Feeding the `bindGroupLayout` into {{domxref("GPUDevice.createPipelineLayout()")}} to create a {{domxref("GPUPipelineLayout")}}. - Using that value immediately in a `createComputePipeline()` call to create a {{domxref("GPUComputePipeline")}}. ```js // ... const bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage", }, }, ], }); const computePipeline = device.createComputePipeline({ layout: device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout], }), compute: { module: shaderModule, entryPoint: "main", }, }); // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createcommandencoder/index.md
--- title: "GPUDevice: createCommandEncoder() method" short-title: createCommandEncoder() slug: Web/API/GPUDevice/createCommandEncoder page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createCommandEncoder --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createCommandEncoder()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUCommandEncoder")}}, used to encode commands to be issued to the GPU. ## Syntax ```js-nolint createCommandEncoder() createCommandEncoder(descriptor) ``` ### Parameters - `descriptor` {{optional_inline}} - : An object containing the following properties: - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. ### Return value A {{domxref("GPUCommandEncoder")}} object instance. ## Examples In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a {{domxref("GPUCommandEncoder")}} created via `createCommandEncoder()`: ```js // ... // Create GPUCommandEncoder const commandEncoder = device.createCommandEncoder(); // Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass const renderPassDescriptor = { colorAttachments: [ { clearValue: clearColor, loadOp: "clear", storeOp: "store", view: context.getCurrentTexture().createView(), }, ], }; const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); // Draw a triangle passEncoder.setPipeline(renderPipeline); passEncoder.setVertexBuffer(0, vertexBuffer); passEncoder.draw(3); // End the render pass passEncoder.end(); // ... ``` The commands encoded by the {{domxref("GPUCommandEncoder")}} are recoded into a {{domxref("GPUCommandBuffer")}} using the {{domxref("GPUCommandEncoder.finish()")}} method. The command buffer is then passed into the queue via a {{domxref("GPUQueue.submit", "submit()")}} call, ready to be processed by the GPU. ```js device.queue.submit([commandEncoder.finish()]); ``` > **Note:** Study the [WebGPU samples](https://webgpu.github.io/webgpu-samples/) to find more command encoding examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/destroy/index.md
--- title: "GPUDevice: destroy() method" short-title: destroy() slug: Web/API/GPUDevice/destroy page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.destroy --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`destroy()`** method of the {{domxref("GPUDevice")}} interface destroys the device, preventing further operations on it. Note that: - Any commands currently enqueued on the device's {{domxref("GPUQueue")}} will be executed before the device is destroyed. - Any WebGPU resources created using the device (buffers, textures, etc.) are also destroyed. - Any mapped buffers created using the device will be unmapped. ## Syntax ```js-nolint destroy() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } let device = await adapter.requestDevice(); // Some time later device.destroy(); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/pusherrorscope/index.md
--- title: "GPUDevice: pushErrorScope() method" short-title: pushErrorScope() slug: Web/API/GPUDevice/pushErrorScope page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.pushErrorScope --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`pushErrorScope()`** method of the {{domxref("GPUDevice")}} interface pushes a new GPU error scope onto the device's error scope stack, allowing you to capture errors of a particular type. Once you are done capturing errors, you can end capture by invoking {{domxref("GPUDevice.popErrorScope()")}}. This pops the scope from the stack and returns a {{jsxref("Promise")}} that resolves to an object describing the first error captured in the scope, or `null` if no errors were captured. ## Syntax ```js-nolint pushErrorScope(filter) ``` ### Parameters - `filter` - : An enumerated value that specifies what type of error will be caught in this particular error scope. Possible values are: - `"internal"` - : The error scope will catch a {{domxref("GPUInternalError")}}. - `"out-of-memory"` - : The error scope will catch a {{domxref("GPUOutOfMemoryError")}}. - `"validation"` - : The error scope will catch a {{domxref("GPUValidationError")}}. ### Return value None ({{jsxref("Undefined")}}). ## Examples The following example uses an error scope to capture a suspected validation error, logging it to the console. ```js device.pushErrorScope("validation"); let sampler = device.createSampler({ maxAnisotropy: 0, // Invalid, maxAnisotropy must be at least 1. }); device.popErrorScope().then((error) => { if (error) { sampler = null; console.error(`An error occurred while creating sampler: ${error.message}`); } }); ``` See [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling) for a lot more examples and information. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/label/index.md
--- title: "GPUDevice: label property" short-title: label slug: Web/API/GPUDevice/label page-type: web-api-instance-property status: - experimental browser-compat: api.GPUDevice.label --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`label`** read-only property of the {{domxref("GPUDevice")}} interface is a string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. ## Value A string. If no label value has previously been set, getting the label returns an empty string. ## Examples ```js async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } // Create a GPUDevice const device = await adapter.requestDevice(); // Set a label device.label = "mylabel"; // Get a label console.log(device.label); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createbindgrouplayout/index.md
--- title: "GPUDevice: createBindGroupLayout() method" short-title: createBindGroupLayout() slug: Web/API/GPUDevice/createBindGroupLayout page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createBindGroupLayout --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createBindGroupLayout()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUBindGroupLayout")}} that defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating {{domxref("GPUBindGroup")}}s. ## Syntax ```js-nolint createBindGroupLayout(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `entries` - : An array of [entry objects](#entry_objects), each one of which describes a single shader resource binding to be included in the {{domxref("GPUBindGroupLayout")}}. Each entry will correspond to an entry defined in a {{domxref("GPUBindGroup")}} (created via a {{domxref("GPUDevice.createBindGroup()")}} call) that uses this {{domxref("GPUBindGroupLayout")}} object as a template. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. ### Entry objects An entry object includes the following properties: - `binding` - : A number representing a unique identifier for this particular entry, which matches the `binding` value of a corresponding {{domxref("GPUBindGroup")}} entry. In addition, it matches the `n` index value of the corresponding [`@binding(n)`](https://gpuweb.github.io/gpuweb/wgsl/#attribute-binding) attribute in the shader ({{domxref("GPUShaderModule")}}) used in the related pipeline. - `visibility` - : One or more {{glossary("Bitwise_flags", "bitwise flags")}} defining the shader stages that a {{domxref("GPUBindGroup")}} entry corresponding to this entry will be visible to. Possible values are: - `GPUShaderStage.COMPUTE`: The bind group entry will be accessible to compute shaders. - `GPUShaderStage.FRAGMENT`: The bind group entry will be accessible to fragment shaders. - `GPUShaderStage.VERTEX`: The bind group entry will be accessible to vertex shaders. Note that multiple stages can be specified by separating values with pipe symbols, for example: ```js visibility: GPUShaderStage.FRAGMENT | GPUShaderStage.VERTEX; ``` - "Resource layout object" - : An object that defines the required binding resource type and structure of the {{domxref("GPUBindGroup")}} entry corresponding to this entry. This property can be one of `buffer`, `externalTexture`, `sampler`, `storageTexture`, or `texture`, the object structures of which are described in the next section. ### Resource layout objects The resource layout object can be one of the following (see also {{domxref("GPUDevice.createBindGroup()")}} for details of how the required resources for each entry are structured): - `buffer`: Indicates that the corresponding {{domxref("GPUBindGroup")}} entry will be a `GPUBufferBinding` object, which contains a {{domxref("GPUBuffer")}} plus `offset` and `size` values. A `buffer` resource layout object can contain the following properties: - `hasDynamicOffset` {{optional_inline}} - : A boolean. If set to `true`, it indicates that this binding requires a dynamic offset, for example as set during a {{domxref("GPURenderPassEncoder.setBindGroup()")}} call. If omitted, `hasDynamicOffset` defaults to `false`. - `minBindingSize` {{optional_inline}} - : A number indicating the minimum allowed size, in bytes, of bound buffers. If omitted, `minBindingSize` defaults to 0. If the value is 0, minimum buffer size is ignored during pipeline creation and is instead validated by issued draw/dispatch commands. - `type` {{optional_inline}} - : An enumerated value specifying the required type for {{domxref("GPUBuffer")}}s bound to this binding (see {{domxref("GPUDevice.createBuffer()")}} for more information on buffer types). Possible values are: - `"read-only-storage"`: A read-only buffer created with a `usage` of `GPUBufferUsage.STORAGE`. - `"storage"`: A writable buffer created with a `usage` of `GPUBufferUsage.STORAGE`. - `"uniform"`: A buffer created with a `usage` of `GPUBufferUsage.UNIFORM`. If omitted, `type` defaults to `"uniform"`. - `externalTexture`: Indicates that the corresponding {{domxref("GPUBindGroup")}} entry will be a {{domxref("GPUExternalTexture")}} object. An `externalTexture` resource layout object is empty — `{}`. - `sampler`: Indicates that the corresponding {{domxref("GPUBindGroup")}} entry will be a {{domxref("GPUSampler")}} object. A `sampler` resource layout object can contain the following properties: - `type` {{optional_inline}} - : An enumerated value specifying the required type for {{domxref("GPUSampler")}}s bound to this binding (see {{domxref("GPUDevice.createSampler()")}} for more information on sampler types). Possible values are: - `"comparison"`: A comparison sampler. - `"filtering"`: A filtering sampler. - `"non-filtering"`: A non-filtering sampler. If omitted, `type` defaults to `"filtering"`. - `storageTexture`: Indicates that the corresponding {{domxref("GPUBindGroup")}} entry will be a {{domxref("GPUTextureView")}} object. A `storageTexture` resource layout object can contain the following properties: - `access` {{optional_inline}} - : An enumerated value specifying whether texture views bound to this binding will be bound for read and/or write access. Possible values are currently `"write-only"` and `undefined`, with the intention to add more access modes in the future. If omitted, the default value is `"write-only"`. - `format` - : An enumerated value specifying the required format of texture views bound to this binding. See the specification's [Texture Formats](https://gpuweb.github.io/gpuweb/#enumdef-gputextureformat) section for all the available `format` values. - `viewDimension` {{optional_inline}} - : An enumerated value specifying the required dimension for texture views bound to this binding. Possible values are: - `"1d"`: The texture is viewed as a one-dimensional image. - `"2d"`: The texture is viewed as a single two-dimensional image. - `"2d-array"`: The texture is viewed as an array of two-dimensional images. - `"cube"`: The texture is viewed as a cubemap. The view has 6 array layers, corresponding to the `[+X, -X, +Y, -Y, +Z, -Z]` faces of the cube. Sampling is done seamlessly across the faces of the cubemap. - `"cube-array"`: The texture is viewed as a packed array of `n` cubemaps, each with 6 array layers corresponding to the `[+X, -X, +Y, -Y, +Z, -Z]` faces of the cube. Sampling is done seamlessly across the faces of the cubemaps. - `"3d"`: The texture is viewed as a three-dimensional image. If omitted, `viewDimension` defaults to `"2d"`. - `texture`: Indicates that the corresponding {{domxref("GPUBindGroup")}} entry will be a {{domxref("GPUTextureView")}} object. A `texture` resource layout object can contain the following properties: - `multisampled` {{optional_inline}} - : A boolean. A value of `true` indicates that texture views bound to this binding must be multi-sampled. If omitted, `multisampled` defaults to `false`. - `sampleType` {{optional_inline}} - : An enumerated value specifying the sample type required for texture views bound to this binding (see {{domxref("GPUDevice.createTexture()")}} for more information on texture view types). Possible values are: - `"depth"` - `"float"` - `"sint"` - `"uint"` - `"unfilterable-float"` If omitted, `sampleType` defaults to `"float"`. - `viewDimension` {{optional_inline}} - : An enumerated value specifying the required dimension for texture views bound to this binding. Possible and default values are the same as for `storageTexture` resource layout objects — see above. ### Return value A {{domxref("GPUBindGroupLayout")}} object instance. ### Validation The following criteria must be met when calling **`createBindGroupLayout()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUBindGroupLayout")}} object is returned: - Each entry's `binding` value is unique. - Each entry's `binding` value is less than the {{domxref("GPUDevice")}}'s `maxBindingsPerBindGroup` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The number of entries does not exceed the [binding slot limits](https://gpuweb.github.io/gpuweb/#exceeds-the-binding-slot-limits). - Only 1 resource layout object is defined per entry. - If an entry's `visibility` includes `GPUShaderStage.VERTEX`: - If its resource layout object is a `buffer`, its `type` is not `"storage"`. - Its resource layout object is not a `storageTexture`. - If an entry's resource layout object is a `texture`, and its `multisampled` value is `true`: - Its `viewDimension` is `"2d"`. - Its `sampleType` is not `"float"`. - If an entry's resource layout object is a `storageTexture`: - Its `viewDimension` is not `"cube"` or `"cube-array"`. - Its `format` is a format that supports storage usage. ## Examples > **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples. ### Basic example Our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/) shows an example of creating a bind group layout and then using that as a template when creating a bind group. ```js // ... const bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage", }, }, ], }); const bindGroup = device.createBindGroup({ layout: bindGroupLayout, entries: [ { binding: 0, resource: { buffer: output, }, }, ], }); // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/poperrorscope/index.md
--- title: "GPUDevice: popErrorScope() method" short-title: popErrorScope() slug: Web/API/GPUDevice/popErrorScope page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.popErrorScope --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`popErrorScope()`** method of the {{domxref("GPUDevice")}} interface pops an existing GPU error scope from the error scope stack (originally pushed using {{domxref("GPUDevice.pushErrorScope()")}}) and returns a {{jsxref("Promise")}} that resolves to an object describing the first error captured in the scope, or `null` if no error occurred. ## Syntax ```js-nolint popErrorScope() ``` ### Parameters None. ### Return value a {{jsxref("Promise")}} that resolves to an object describing the first error captured in the scope. This can be of type: - {{domxref("GPUInternalError")}} - {{domxref("GPUOutOfMemoryError")}} - {{domxref("GPUValidationError")}} If no error occurred, it resolves to `null`. ## Examples The following example uses an error scope to capture a suspected validation error, logging it to the console. ```js device.pushErrorScope("validation"); let sampler = device.createSampler({ maxAnisotropy: 0, // Invalid, maxAnisotropy must be at least 1. }); device.popErrorScope().then((error) => { if (error) { sampler = null; console.error(`An error occurred while creating sampler: ${error.message}`); } }); ``` See [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling) for a lot more examples and information. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createrenderpipeline/index.md
--- title: "GPUDevice: createRenderPipeline() method" short-title: createRenderPipeline() slug: Web/API/GPUDevice/createRenderPipeline page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createRenderPipeline --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createRenderPipeline()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPURenderPipeline")}} that can control the vertex and fragment shader stages and be used in a {{domxref("GPURenderPassEncoder")}} or {{domxref("GPURenderBundleEncoder")}}. ## Syntax ```js-nolint createRenderPipeline(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `depthStencil` {{optional_inline}} - : An object (see [`depthStencil` object structure](#depthstencil_object_structure)) describing depth-stencil properties including testing, operations, and bias. - `fragment` {{optional_inline}} - : An object (see [`fragment` object structure](#fragment_object_structure)) describing the fragment shader entry point of the pipeline and its output colors. If no fragment shader entry point is defined, the pipeline will not produce any color attachment outputs, but it still performs rasterization and produces depth values based on the vertex position output. Depth testing and stencil operations can still be used. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `layout` - : Defines the layout (structure, purpose, and type) of all the GPU resources (buffers, textures, etc.) used during the execution of the pipeline. Possible values are: - A {{domxref("GPUPipelineLayout")}} object, created using {{domxref("GPUDevice.createPipelineLayout()")}}, which allows the GPU to figure out how to run the pipeline most efficiently ahead of time. - A string of `"auto"`, which causes the pipeline to generate an implicit bind group layout based on any bindings defined in the shader code. If `"auto"` is used, the generated bind group layouts may only be used with the current pipeline. - `multisample` {{optional_inline}} - : An object (see [`multisample` object structure](#multisample_object_structure)) describing how the pipeline interacts with a render pass's multisampled attachments. - `primitive` {{optional_inline}} - : An object (see [`primitive` object structure](#primitive_object_structure)) describing how a pipeline constructs and rasterizes primitives from its vertex inputs. - `vertex` - : An object (see [`vertex` object structure](#vertex_object_structure)) describing the vertex shader entry point of the pipeline and its input buffer layouts. ### `depthStencil` object structure The `depthStencil` object can contain the following properties: - `depthBias` {{optional_inline}} - : A number representing a constant depth bias that is added to each fragment. If omitted, `depthBias` defaults to 0. - `depthBiasClamp` {{optional_inline}} - : A number representing the maximum depth bias of a fragment. If omitted, `depthBiasClamp` defaults to 0. - `depthBiasSlopeScale` {{optional_inline}} - : A number representing a depth bias that scales with the fragment's slope. If omitted, `depthBiasSlopeScale` defaults to 0. - `depthCompare` - : An enumerated value specifying the comparison operation used to test fragment depths against `depthStencilAttachment` depth values. Possible values are: - `"never"`: Comparison tests never pass. - `"less"`: A provided value passes the comparison test if it is less than the sampled value. - `"equal"`: A provided value passes the comparison test if it is equal to the sampled value. - `"less-equal"`: A provided value passes the comparison test if it is less than or equal to the sampled value. - `"greater"`: A provided value passes the comparison test if it is greater than the sampled value. - `"not-equal"`: A provided value passes the comparison test if it is not equal to the sampled value. - `"greater-equal"`: A provided value passes the comparison test if it is greater than or equal to the sampled value. - `"always"`: Comparison tests always pass. - `depthWriteEnabled` - : A boolean. A value of `true` specifies that the {{domxref("GPURenderPipeline")}} can modify `depthStencilAttachment` depth values after creation. Setting it to `false` means it cannot. - `format` - : An enumerated value specifying the `depthStencilAttachment` format that the {{domxref("GPURenderPipeline")}} will be compatible with. See the specification's [Texture Formats](https://gpuweb.github.io/gpuweb/#enumdef-gputextureformat) section for all the available `format` values. - `stencilBack` {{optional_inline}} - : An object that defines how stencil comparisons and operations are performed for back-facing primitives. Its properties can include: - `compare` {{optional_inline}} - : An enumerated value specifying the comparison operation used when testing fragments against `depthStencilAttachment` stencil values. Possible values are the same as for the `depthCompare` property; see above. If omitted, `compare` defaults to `"always"`. - `depthFailOp` {{optional_inline}} - : An enumerated value specifying the stencil operation performed if the fragment depth comparison described by `depthCompare` fails. Possible values are: - `"decrement-clamp"`: Decrement the current render state stencil value, clamping it to 0. - `"decrement-wrap"`: Decrement the current render state stencil value, wrapping it to the maximum representable value of the `depthStencilAttachment`'s stencil aspect if the value goes below 0. - `"invert"`: Bitwise-invert the current render state stencil value. - `"increment-clamp"`: Increments the current render state stencil value, clamping it to the maximum representable value of the `depthStencilAttachment`'s stencil aspect. - `"increment-wrap"`: Increments the current render state stencil value, wrapping it to zero if the value exceeds the maximum representable value of the `depthStencilAttachment`'s stencil aspect. - `"keep"`: Keep the current stencil value. - `"replace"`: Set the stencil value to the current render state stencil value. - `"zero"`: Set the stencil value to 0. If omitted, `depthFailOp` defaults to `"keep"`. > **Note:**: The render state stencil value is initialized to 0 at the start of a render pass. - `failOp` {{optional_inline}} - : An enumerated value specifying the stencil operation performed if the fragment stencil comparison test described by `compare` fails. Possible and default values are the same as for `depthFailOp`. - `passOp` {{optional_inline}} - : An enumerated value specifying the stencil operation performed if the fragment stencil comparison test described by `compare` passes. Possible and default values are the same as for `depthFailOp`. - `stencilFront` {{optional_inline}} - : An object that defines how stencil comparisons and operations are performed for front-facing primitives. Its properties are the same as for `stencilBack`. - `stencilReadMask` {{optional_inline}} - : A bitmask controlling which `depthStencilAttachment` stencil value bits are read when performing stencil comparison tests. If omitted, `stencilReadMask` defaults to `0xFFFFFFFF`. - `stencilWriteMask` {{optional_inline}} - : A bitmask controlling which `depthStencilAttachment` stencil value bits are written to when performing stencil operations. If omitted, `stencilWriteMask` defaults to `0xFFFFFFFF`. > **Note:** `depthStencilAttachment` values are specified during {{domxref("GPUCommandEncoder.beginRenderPass()")}} calls, when the {{domxref("GPURenderPipeline")}} is actually used to perform a render pass. ### `fragment` object structure The `fragment` object contains an array of objects, each of which can contain the following properties: - `constants` {{optional_inline}} - : A sequence of record types, with the structure `(id, value)`, representing override values for [WGSL constants that can be overridden in the pipeline](https://gpuweb.github.io/gpuweb/#typedefdef-gpupipelineconstantvalue). These behave like [ordered maps](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). In each case, the `id` is a key used to identify or select the record, and the `constant` is an enumerated value representing a WGSL. Depending on which constant you want to override, the `id` may take the form of the numeric ID of the constant, if one is specified, or otherwise the constant's identifier name. A code snippet providing override values for several overridable constants might look like this: ```js { // ... constants: { 0: false, 1200: 3.0, 1300: 2.0, width: 20, depth: -1, height: 15, } } ``` - `entryPoint` - : The name of the function in the `module` that this stage will use to perform its work. The corresponding shader function must have the `@fragment` attribute to be identified as this entry point. See [Entry Point Declaration](https://gpuweb.github.io/gpuweb/wgsl/#entry-point-decl) for more information. - `module` - : A {{domxref("GPUShaderModule")}} object containing the [WGSL](https://gpuweb.github.io/gpuweb/wgsl/) code that this programmable stage will execute. - `targets` - : an array of objects representing color states that represent configuration details for the colors output by the fragment shader stage. These objects can include the following properties: - `blend` {{optional_inline}} - : A object that describes a blend mode to be applied to the output color. `blend` has two properties: - `alpha` - : Describes the alpha channel value. - `color` - : Describes the color value. `alpha` and `color` both take an object as a value that can include the following properties: - `dstFactor` {{optional_inline}} - : An enumerated value that defines the blend factor operation to be performed on values from the target attachment. Possible values are: - `"constant"` - `"dst"` - `"dst-alpha"` - `"one"` - `"one-minus-dst"` - `"one-minus-src"` - `"one-minus-src-alpha"` - `"one-minus-dst-alpha"` - `"one-minus-constant"` - `"src"` - `"src-alpha"` - `"src-alpha-saturated"` - `"zero"` If omitted, `dstFactor` defaults to `"zero"`. - `operation` {{optional_inline}} - : An enumerated value that defines the algorithm used to combine source and destination blend factors, to calculate the final values written to the target attachment components. Possible values are: - `"add"` - `"max"` - `"min"` - `"reverse-subtract"` - `"subtract"` If omitted, `operation` defaults to `"add"`. - `srcFactor` {{optional_inline}} - : An enumerated value that defines the blend factor operation to be performed on values from the fragment shader. Possible values are the same as for `dstFactor`. If omitted, `srcFactor` defaults to `"one"`. > **Note:** For a detailed explanation of the algorithms defined by each `dstFactor`/`srcFactor` and `operation` enumerated value, see the [Blend State](https://gpuweb.github.io/gpuweb/#blend-state) section of the specification. - `format` - : An enumerated value specifying the required format for output colors. See the specification's [Texture Formats](https://gpuweb.github.io/gpuweb/#enumdef-gputextureformat) section for all the available `format` values. - `writeMask` {{optional_inline}} - : One or more {{glossary("bitwise flags")}} defining the write mask to apply to the color target state. Possible flag values are: - `GPUFlagsConstant.RED` - `GPUFlagsConstant.GREEN` - `GPUFlagsConstant.BLUE` - `GPUFlagsConstant.ALPHA` - `GPUFlagsConstant.ALL` If omitted, `writeMask` defaults to `GPUFlagsConstant.ALL`. Note that multiple flags can be specified by separating values with pipe symbols, for example: ```js writeMask: GPUFlagsConstant.RED | GPUFlagsConstant.ALPHA; ``` ### `multisample` object structure The `multisample` object can contain the following properties: - `alphaToCoverageEnabled` {{optional_inline}} - : A boolean. A value of `true` indicates that a fragment's alpha channel should be used to generate a sample coverage mask. If omitted, `alphaToCoverageEnabled` defaults to `false`. - `count` {{optional_inline}} - : A number that defines the number of samples per pixel. The pipeline will be compatible only with attachment textures (`colorAttachment`s and `depthStencilAttachment`s) with matching `sampleCounts` (see {{domxref("GPUTexture")}}). If omitted, `count` defaults to 1. - `mask` {{optional_inline}} - : A bitmask that determines which samples are written to. If omitted, `mask` defaults to `0xFFFFFFFF`. > **Note:** `colorAttachment` and `depthStencilAttachment` values are specified during {{domxref("GPUCommandEncoder.beginRenderPass()")}} calls, when the {{domxref("GPURenderPipeline")}} is actually used to perform a render pass. ### `primitive` object structure The `primitive` object can contain the following properties: - `cullMode` {{optional_inline}} - : An enumerated value that defines which polygon orientation will be culled, if any. Possible values are: - `"back"`: Back-facing polygons are culled. - `"front"`: Front-facing polygons are culled. - `"none"`: No polygons are culled. If omitted, `cullMode` defaults to `"none"`. - `frontFace` {{optional_inline}} - : An enumerated value that defines which polygons are considered front-facing. Possible values are: - `"ccw"`: Polygons with vertices whose framebuffer coordinates are given in counter-clockwise order. - `"cw"`: Polygons with vertices whose framebuffer coordinates are given in clockwise order. If omitted, `frontFace` defaults to `"ccw"`. - `stripIndexFormat` {{optional_inline}} - : An enumerated value that determines the index buffer format and primitive restart value in the case of pipelines with strip topologies (`"line-strip"` or `"triangle-strip"`). The primitive restart value specifies which index value indicates that a new primitive should be started rather than continuing to construct the strip with the prior indexed vertices. Possible values are: - `"uint16"`: Indicates a byte size of 2 and a primitive restart value of `0xFFFF`. - `"uint32"`: Indicates a byte size of 4 and a primitive restart value of `0xFFFFFFFF`. GPU primitive states that specify a strip primitive topology must specify a strip index format if they are used for indexed draws (for example, via {{domxref("GPURenderPassEncoder.drawIndexed()")}}) so that the primitive restart value that will be used is known at pipeline creation time. Pipelines with list primitive topologies (`"line-list"`, `"point-list"`, or `"triangle-list"`) should not specify a `stripIndexFormat` value. They will instead use the index format passed to, for example, {{domxref("GPURenderPassEncoder.setIndexBuffer()")}} when doing indexed rendering. - `topology` {{optional_inline}} - : An enumerated value that defines the type of primitive to be constructed from the specified `vertex` inputs. Possible values are: - `"line-list"`: Each consecutive pair of two vertices defines a line primitive. - `"line-strip"`: Each vertex after the first defines a line primitive between it and the previous vertex. - `"point-list"`: Each vertex defines a point primitive. - `"triangle-list"`: Each consecutive triplet of three vertices defines a triangle primitive. - `"triangle-strip"`: Each vertex after the first two defines a triangle primitive between it and the previous two vertices. If omitted, `topology` defaults to `"triangle-list"`. - `unclippedDepth` {{optional_inline}} - : A boolean. A value of `true` indicates that depth clipping is disabled. If omitted, `unclippedDepth` defaults to `false`. Note that to control depth clipping, the `depth-clip-control` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} must be enabled in the {{domxref("GPUDevice")}}. > **Note:** `frontFace` and `cullMode` have no effect on `"point-list"`, `"line-list"`, or `"line-strip"` topologies. ### `vertex` object structure The `vertex` object can contain the following properties: - `constants` {{optional_inline}} - : A sequence of record types, with the structure `(id, value)`, representing override values for [WGSL constants that can be overridden in the pipeline](https://gpuweb.github.io/gpuweb/#typedefdef-gpupipelineconstantvalue). These behave like [ordered maps](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). In each case, the `id` is a key used to identify or select the record, and the `constant` is an enumerated value representing a WGSL. Depending on which constant you want to override, the `id` may take the form of the numeric ID of the constant, if one is specified, or otherwise the constant's identifier name. A code snippet providing override values for several overridable constants might look like this: ```js { // ... constants: { 0: false, 1200: 3.0, 1300: 2.0, width: 20, depth: -1, height: 15, } } ``` - `entryPoint` - : The name of the function in the `module` that this stage will use to perform its work. The corresponding shader function must have the `@vertex` attribute to be identified as this entry point. See [Entry Point Declaration](https://gpuweb.github.io/gpuweb/wgsl/#entry-point-decl) for more information. - `module` - : A {{domxref("GPUShaderModule")}} object containing the [WGSL](https://gpuweb.github.io/gpuweb/wgsl/) code that this programmable stage will execute. - `buffers` {{optional_inline}} - : An array of objects, each representing the expected layout of a vertex buffer used in the pipeline. Each object can contain the following properties: - `arrayStride` - : A number representing the stride, in bytes, between the different structures (e.g. vertices) inside the buffer. - `attributes` - : An array of objects defining the layout of the vertex attributes within each structure. Each object has the following properties: - `format` - : An enumerated value that specifies the format of the vertex. For all the available values, see the [`GPUVertexFormat`](https://gpuweb.github.io/gpuweb/#enumdef-gpuvertexformat) definition in the specification. - `offset` - : A number specifying the offset, in bytes, from the beginning of the structure to the data for the attribute. - `shaderLocation` - : The numeric location associated with this attribute, which will correspond with a [`@location`](https://gpuweb.github.io/gpuweb/wgsl/#input-output-locations) attribute declared in the WGSL code of the associated {{domxref("GPUShaderModule")}} referenced in the `vertex` object's `module` property. - `stepMode` {{optional_inline}} - : An enumerated value that defines whether the separate structures inside the buffer represent vertices or instances. Possible values are: - `"instance"`: Each structure is an instance — the address is advanced by `arrayStride` for each instance. - `"vertex"`: Each structure is a vertex — the address is advanced by `arrayStride` for each vertex, and reset between instances. If omitted, `stepMode` defaults to `"vertex"`. ### Return value A {{domxref("GPURenderPipeline")}} object instance. ### Validation The following criteria must be met when calling **`createRenderPipeline()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPURenderPipeline")}} object is returned: - For `depthStencil` objects: - `format` is a [`depth-or-stencil`](https://gpuweb.github.io/gpuweb/#depth-or-stencil-format) format. - If `depthWriteEnabled` is `true` or `depthCompare` is not `"always"`, `format` has a depth component. - If `stencilFront` or `stencilBack`'s properties are not at their default values, `format` has a stencil component. - For `fragment` objects: - `targets.length` is less than or equal to the {{domxref("GPUDevice")}}'s `maxColorAttachments` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - For each `target`, `writeMask`'s numeric equivalent is less than 16. - If any of the used blend factor operations use the source alpha channel (for example `"src-alpha-saturated"`), the output has an alpha channel (that is, it must be a `vec4`). ## Examples > **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples. ### Basic example Our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/) provides a simple example of the construction of a valid render pipeline descriptor object, which is then used to create a {{domxref("GPURenderPipeline")}} via a `createRenderPipeline()` call. ```js // ... const vertexBuffers = [ { attributes: [ { shaderLocation: 0, // position offset: 0, format: "float32x4", }, { shaderLocation: 1, // color offset: 16, format: "float32x4", }, ], arrayStride: 32, stepMode: "vertex", }, ]; const pipelineDescriptor = { vertex: { module: shaderModule, entryPoint: "vertex_main", buffers: vertexBuffers, }, fragment: { module: shaderModule, entryPoint: "fragment_main", targets: [ { format: navigator.gpu.getPreferredCanvasFormat(), }, ], }, primitive: { topology: "triangle-list", }, layout: "auto", }; const renderPipeline = device.createRenderPipeline(pipelineDescriptor); // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/importexternaltexture/index.md
--- title: "GPUDevice: importExternalTexture() method" short-title: importExternalTexture() slug: Web/API/GPUDevice/importExternalTexture page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.importExternalTexture --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`importExternalTexture()`** method of the {{domxref("GPUDevice")}} interface takes an {{domxref("HTMLVideoElement")}} or a {{domxref("VideoFrame")}} object as an input and returns a {{domxref("GPUExternalTexture")}} wrapper object containing a snapshot of the video that can be used as a frame in GPU rendering operations. ## Syntax ```js-nolint importExternalTexture(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `colorSpace` {{optional_inline}} - : An enumerated value specifying the color space to use for the video frame. Possible values are `"srgb"` and `"display-p3"`. If omitted, `colorSpace` defaults to `"srgb"`. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `source` - : The {{domxref("HTMLVideoElement")}} or {{domxref("VideoFrame")}} source of the video snapshot. ### Return value A {{domxref("GPUExternalTexture")}} object instance. Note that the moment when the {{domxref("GPUExternalTexture")}} object expires (is destroyed) depends on what its source is: - {{domxref("GPUExternalTexture")}} objects with an {{domxref("HTMLVideoElement")}} source expire as soon as they are used (for example in a bind group). - {{domxref("GPUExternalTexture")}} objects with an {{domxref("VideoFrame")}} source expire only when the `VideoFrame` is closed, for example via a {{domxref("VideoFrame.close()")}} call. ### Validation The following criteria must be met when calling **`importExternalTexture()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUExternalTexture")}} object is returned: - The video snapshot is usable (e.g. the video source is loaded properly, and doesn't have a width or height of 0). ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the video source data is cross-origin. ## Examples In the WebGPU samples [Video Uploading sample](https://webgpu.github.io/webgpu-samples/samples/videoUploading), an `importExternalTexture()` call is used as the value of a bind group entry `resource`, specified when creating a {{domxref("GPUBindGroup")}} via a {{domxref("GPUDevice.createBindGroup()")}} call: ```js //... const uniformBindGroup = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [ { binding: 1, resource: sampler, }, { binding: 2, resource: device.importExternalTexture({ source: video, }), }, ], }); //... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createcomputepipelineasync/index.md
--- title: "GPUDevice: createComputePipelineAsync() method" short-title: createComputePipelineAsync() slug: Web/API/GPUDevice/createComputePipelineAsync page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createComputePipelineAsync --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createComputePipelineAsync()`** method of the {{domxref("GPUDevice")}} interface returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUComputePipeline")}}, which can control the compute shader stage and be used in a {{domxref("GPUComputePassEncoder")}}, once the pipeline can be used without any stalling. > **Note:** It is generally preferable to use this method over {{domxref("GPUDevice.createComputePipeline()")}} whenever possible, as it prevents blocking of GPU operation execution on pipeline compilation. ## Syntax ```js-nolint createComputePipeline(descriptor) ``` ### Parameters - `descriptor` - : See the descriptor definition for the [`GPUDevice.createComputePipeline()`](/en-US/docs/Web/API/GPUDevice/createComputePipeline#syntax) method. ### Return value A {{jsxref("Promise")}} that fulfills with a {{domxref("GPUComputePipeline")}} object instance when the created pipeline is ready to be used without additional delay. ### Validation If pipeline creation fails and the resulting pipeline becomes invalid as a result, the returned promise rejects with a {{domxref("GPUPipelineError")}}: - If this is due to an internal error, the {{domxref("GPUPipelineError")}} will have a `reason` of `"internal"`. - If this is due to a validation error, the {{domxref("GPUPipelineError")}} will have a `reason` of `"validation"`. A validation error can occur if any of the following are false: - The workgroup storage size used by the `module` referenced inside the `compute` property is less than or equal to the {{domxref("GPUDevice")}}'s `maxComputeWorkgroupStorageSize` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The `module` uses a number of compute invocations per workgroup less than or equal to the {{domxref("GPUDevice")}}'s `maxComputeInvocationsPerWorkgroup` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - The `module`'s workgroup size is less than or equal to the {{domxref("GPUDevice")}}'s corresponding `maxComputeWorkgroupSizeX`, `maxComputeWorkgroupSizeY`, or `maxComputeWorkgroupSizeZ` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. ## Examples > **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples. ### Basic example The following example shows a process of: - Creating a bind group layout with {{domxref("GPUDevice.createBindGroupLayout()")}}. - Feeding the `bindGroupLayout` into {{domxref("GPUDevice.createPipelineLayout()")}} to create a {{domxref("GPUPipelineLayout")}}. - Using that value immediately in a `createComputePipelineAsync()` call to create a {{domxref("GPUComputePipeline")}}. ```js async function init() { // ... const bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage", }, }, ], }); const computePipeline = await device.createComputePipelineAsync({ layout: device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout], }), compute: { module: shaderModule, entryPoint: "main", }, }); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createrenderpipelineasync/index.md
--- title: "GPUDevice: createRenderPipelineAsync() method" short-title: createRenderPipelineAsync() slug: Web/API/GPUDevice/createRenderPipelineAsync page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createRenderPipelineAsync --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createRenderPipelineAsync()`** method of the {{domxref("GPUDevice")}} interface returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPURenderPipeline")}}, which can control the vertex and fragment shader stages and be used in a {{domxref("GPURenderPassEncoder")}} or {{domxref("GPURenderBundleEncoder")}}, once the pipeline can be used without any stalling. > **Note:** It is generally preferable to use this method over {{domxref("GPUDevice.createRenderPipeline()")}} whenever possible, as it prevents blocking of GPU operation execution on pipeline compilation. ## Syntax ```js-nolint createRenderPipelineAsync(descriptor) ``` ### Parameters - `descriptor` - : See the descriptor definition for the [`GPUDevice.createRenderPipeline()`](/en-US/docs/Web/API/GPUDevice/createRenderPipeline#syntax) method. ### Return value A {{jsxref("Promise")}} that fulfills with a {{domxref("GPURenderPipeline")}} object instance when the created pipeline is ready to be used without additional delay. ### Validation If pipeline creation fails and the resulting pipeline becomes invalid as a result, the returned promise rejects with a {{domxref("GPUPipelineError")}}: - If this is due to an internal error, the {{domxref("GPUPipelineError")}} will have a `reason` of `"internal"`. - If this is due to a validation error, the {{domxref("GPUPipelineError")}} will have a `reason` of `"validation"`. A validation error can occur if any of the following are false: - For `depthStencil` objects: - `format` is a [`depth-or-stencil`](https://gpuweb.github.io/gpuweb/#depth-or-stencil-format) format. - If `depthWriteEnabled` is `true` or `depthCompare` is not `"always"`, `format` has a depth component. - If `stencilFront` or `stencilBack`'s properties are not at their default values, `format` has a stencil component. - For `fragment` objects: - `targets.length` is less than or equal to the {{domxref("GPUDevice")}}'s `maxColorAttachments` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. - For each `target`, `writeMask`'s numeric equivalent is less than 16. - If any of the used blend factor operations use the source alpha channel (for example `"src-alpha-saturated"`), the output has an alpha channel (that is, it must be a `vec4`). ## Examples > **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples. ### Basic example The following example shows a basic example of the construction of a valid render pipeline descriptor object, which is then used to create a {{domxref("GPURenderPipeline")}} via a `createRenderPipelineAsync()` call. ```js async function init() { // ... const vertexBuffers = [ { attributes: [ { shaderLocation: 0, // position offset: 0, format: "float32x4", }, { shaderLocation: 1, // color offset: 16, format: "float32x4", }, ], arrayStride: 32, stepMode: "vertex", }, ]; const pipelineDescriptor = { vertex: { module: shaderModule, entryPoint: "vertex_main", buffers: vertexBuffers, }, fragment: { module: shaderModule, entryPoint: "fragment_main", targets: [ { format: navigator.gpu.getPreferredCanvasFormat(), }, ], }, primitive: { topology: "triangle-list", }, layout: "auto", }; const renderPipeline = await device.createRenderPipelineAsync(pipelineDescriptor); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createshadermodule/index.md
--- title: "GPUDevice: createShaderModule() method" short-title: createShaderModule() slug: Web/API/GPUDevice/createShaderModule page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createShaderModule --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createShaderModule()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUShaderModule")}} from a string of [WGSL](https://gpuweb.github.io/gpuweb/wgsl/) source code. ## Syntax ```js-nolint createShaderModule(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `code` - : A string representing the WGSL source code for the shader module. - `hints` {{optional_inline}} - : A sequence of record types, with the structure `("string", compilationHint)`. These behave like [ordered maps](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). In each case, the `"string"` is a key used to identify or select the record, and the `compilationHint` is either a {{domxref("GPUPipelineLayout")}} object instance or an enumerated value of `"auto"`. The point of `hints` is to provide information about the pipeline layout as early as possible to improve performance. The idea is to maximize the amount of compilation that can be done once by `createShaderModule()`, rather than multiple times in multiple calls to {{domxref("GPUDevice.createComputePipeline()")}} and {{domxref("GPUDevice.createRenderPipeline()")}}. > **Note:** Different implementations may handle `hints` in different ways, including possibly ignoring them entirely. Providing hints does not guarantee improved shader compilation performance on all browsers/systems. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `sourceMap` {{optional_inline}} - : A source map definition to provide developer tool integration such as source-language debugging. WGSL names (identifiers) in source maps should follow the rules defined in [WGSL identifier comparison](https://gpuweb.github.io/gpuweb/wgsl/#identifier-comparison). If defined, the source map may be interpreted as a [source-map-v3 format](https://sourcemaps.info/spec.html). > **Note:** Different implementations may handle `sourceMap`s in different ways, including possibly ignoring them entirely. ### Return value A {{domxref("GPUShaderModule")}} object instance. ## Examples In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), our shader module is created using the following code: ```js const shaders = ` struct VertexOut { @builtin(position) position : vec4f, @location(0) color : vec4f } @vertex fn vertex_main(@location(0) position: vec4f, @location(1) color: vec4f) -> VertexOut { var output : VertexOut; output.position = position; output.color = color; return output; } @fragment fn fragment_main(fragData: VertexOut) -> @location(0) vec4f { return fragData.color; } `; async function init() { if (!navigator.gpu) { throw Error("WebGPU not supported."); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw Error("Couldn't request WebGPU adapter."); } let device = await adapter.requestDevice(); // ... // later on const shaderModule = device.createShaderModule({ code: shaders, }); // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API) - The [WebGPU Shading Language specification](https://gpuweb.github.io/gpuweb/wgsl/)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createpipelinelayout/index.md
--- title: "GPUDevice: createPipelineLayout() method" short-title: createPipelineLayout() slug: Web/API/GPUDevice/createPipelineLayout page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createPipelineLayout --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createPipelineLayout()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUPipelineLayout")}} that defines the {{domxref("GPUBindGroupLayout")}}s used by a pipeline. {{domxref("GPUBindGroup")}}s used with the pipeline during command encoding must have compatible {{domxref("GPUBindGroupLayout")}}s. ## Syntax ```js-nolint createPipelineLayout(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `bindGroupLayouts` - : An array of {{domxref("GPUBindGroupLayout")}} objects (which are in turn created via calls to {{domxref("GPUDevice.createBindGroupLayout()")}}). Each one corresponds to a [`@group`](https://gpuweb.github.io/gpuweb/wgsl/#attribute-binding) attribute in the shader code contained in the {{domxref("GPUShaderModule")}} used in a related pipeline. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. ### Return value A {{domxref("GPUPipelineLayout")}} object instance. ### Validation The following criteria must be met when calling **`createPipelineLayout()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUPipelineLayout")}} object is returned: - The {{domxref("GPUBindGroupLayout")}} objects in `bindGroupLayouts` are valid. - The number of {{domxref("GPUBindGroupLayout")}} objects in `bindGroupLayouts` is less than the {{domxref("GPUDevice")}}'s `maxBindGroups` {{domxref("GPUSupportedLimits", "limit", "", "nocode")}}. ## Examples > **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples. ### Multiple bind group layouts, bind group, and pipeline layout The following snippet: - Creates a {{domxref("GPUBindGroupLayout")}} that describes a binding with a buffer, a texture, and a sampler. - Creates a {{domxref("GPUPipelineLayout")}} based on the {{domxref("GPUBindGroupLayout")}}. ```js // ... const bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: {}, }, { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: {}, }, { binding: 2, visibility: GPUShaderStage.FRAGMENT, sampler: {}, }, ], }); const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout], }); // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpudevice
data/mdn-content/files/en-us/web/api/gpudevice/createqueryset/index.md
--- title: "GPUDevice: createQuerySet() method" short-title: createQuerySet() slug: Web/API/GPUDevice/createQuerySet page-type: web-api-instance-method status: - experimental browser-compat: api.GPUDevice.createQuerySet --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`createQuerySet()`** method of the {{domxref("GPUDevice")}} interface creates a {{domxref("GPUQuerySet")}} that can be used to record the results of queries on passes, such as occlusion or timestamp queries. ## Syntax ```js-nolint createQuerySet(descriptor) ``` ### Parameters - `descriptor` - : An object containing the following properties: - `count` - : A number specifying the number of queries to be managed by the resulting {{domxref("GPUQuerySet")}}. - `label` {{optional_inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - `type` - : An enumerated value specifying the type of queries to be managed by the resulting {{domxref("GPUQuerySet")}}. Possible values are: - `"occlusion"` - : Occlusion queries are available on render passes to query the number of fragment samples that pass all the per-fragment tests for a set of drawing commands (including scissor, sample mask, alpha to coverage, stencil, and depth tests). To run an occlusion query, an appropriate {{domxref("GPUQuerySet")}} must be provided as the value of the `occlusionQuerySet` descriptor property when invoking {{domxref("GPUCommandEncoder.beginRenderPass()")}} to run a render pass. - `"timestamp"` - : Timestamp queries allow applications to write timestamps to a {{domxref("GPUQuerySet")}}. To run a timestamp query, appropriate {{domxref("GPUQuerySet")}}s must be provided inside the value of the `timestampWrites` descriptor property when invoking {{domxref("GPUCommandEncoder.beginRenderPass()")}} to run a render pass, or {{domxref("GPUCommandEncoder.beginComputePass()")}} to run a compute pass. Alternatively, you can run a single timestamp query at any time by invoking {{domxref("GPUCommandEncoder.writeTimeStamp()")}} with an appropriate {{domxref("GPUQuerySet")}} as a parameter. To use timestamp queries, the `timestamp-query` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} must be enabled in the {{domxref("GPUDevice")}}. ### Return value A {{domxref("GPUQuerySet")}} object instance. ### Validation The following criteria must be met when calling **`createQuerySet()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUQuerySet")}} object is returned: - `count` is less than or equal to 4096. ## Examples The following snippet creates a {{domxref("GPUQuerySet")}} that holds 32 occlusion query results: ```js const querySet = device.createQuerySet({ type: "occlusion", count: 32, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/client/index.md
--- title: Client slug: Web/API/Client page-type: web-api-interface browser-compat: api.Client --- {{APIRef("Service Workers API")}} The `Client` interface represents an executable context such as a {{domxref("Worker")}}, or a {{domxref("SharedWorker")}}. {{domxref("Window")}} clients are represented by the more-specific {{domxref("WindowClient")}}. You can get `Client`/`WindowClient` objects from methods such as {{domxref("Clients.matchAll","Clients.matchAll()")}} and {{domxref("Clients.get","Clients.get()")}}. ## Instance methods - {{domxref("Client.postMessage()")}} - : Sends a message to the client. ## Instance properties - {{domxref("Client.frameType")}} {{ReadOnlyInline}} - : The client's frame type as a string. It can be `"auxiliary"`, `"top-level"`, `"nested"`, or `"none"`. - {{domxref("Client.id")}} {{ReadOnlyInline}} - : The universally unique identifier of the client as a string. - {{domxref("Client.type")}} {{ReadOnlyInline}} - : The client's type as a string. It can be `"window"`, `"worker"`, or `"sharedworker"`. - {{domxref("Client.url")}} {{ReadOnlyInline}} - : The URL of the client as a string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
0
data/mdn-content/files/en-us/web/api/client
data/mdn-content/files/en-us/web/api/client/url/index.md
--- title: "Client: url property" short-title: url slug: Web/API/Client/url page-type: web-api-instance-property browser-compat: api.Client.url --- {{APIRef("Service Workers API")}} The **`url`** read-only property of the {{domxref("Client")}} interface returns the URL of the current service worker client. ## Value A string. ## Examples ```js self.addEventListener("notificationclick", (event) => { console.log("On notification click: ", event.notification.tag); event.notification.close(); // This looks to see if the current is already open and // focuses if it is event.waitUntil( clients .matchAll({ type: "window", }) .then((clientList) => { for (const client of clientList) { if (client.url === "/" && "focus" in client) { return client.focus(); } } if (clients.openWindow) { return clients.openWindow("/"); } }), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/client
data/mdn-content/files/en-us/web/api/client/id/index.md
--- title: "Client: id property" short-title: id slug: Web/API/Client/id page-type: web-api-instance-property browser-compat: api.Client.id --- {{APIRef("Service Workers API")}} The **`id`** read-only property of the {{domxref("Client")}} interface returns the universally unique identifier of the {{domxref("Client")}} object. ## Value A string uniquely identifying the object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/client
data/mdn-content/files/en-us/web/api/client/postmessage/index.md
--- title: "Client: postMessage() method" short-title: postMessage() slug: Web/API/Client/postMessage page-type: web-api-instance-method browser-compat: api.Client.postMessage --- {{APIRef("Service Worker API")}} The **`postMessage()`** method of the {{domxref("Client")}} interface allows a service worker to send a message to a client (a {{domxref("Window")}}, {{domxref("Worker")}}, or {{domxref("SharedWorker")}}). The message is received in the "`message`" event on {{domxref("ServiceWorkerContainer", "navigator.serviceWorker")}}. ## Syntax ```js-nolint postMessage(message) postMessage(message, options) postMessage(message, transferables) ``` ### Parameters - `message` - : The message to send to the client. This can be any [structured-cloneable type](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - `options` {{optional_inline}} - : An optional object containing a `transfer` field with an [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) to transfer ownership of. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. - `transferables` {{optional_inline}} - : An optional [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) to transfer ownership of. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. ### Return value None ({{jsxref("undefined")}}). ## Examples The code below sends a message from a service worker to a client. The client is fetched using the {{domxref("Clients.get()", "get()")}} method on {{domxref("ServiceWorkerGlobalScope.clients", "clients")}}, which is a global in service worker scope. ```js addEventListener("fetch", (event) => { event.waitUntil( (async () => { // Exit early if we don't have access to the client. // Eg, if it's cross-origin. if (!event.clientId) return; // Get the client. const client = await self.clients.get(event.clientId); // Exit early if we don't get the client. // Eg, if it closed. if (!client) return; // Send a message to the client. client.postMessage({ msg: "Hey I just got a fetch from you!", url: event.request.url, }); })(), ); }); ``` Receiving that message: ```js navigator.serviceWorker.addEventListener("message", (event) => { console.log(event.data.msg, event.data.url); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/client
data/mdn-content/files/en-us/web/api/client/type/index.md
--- title: "Client: type property" short-title: type slug: Web/API/Client/type page-type: web-api-instance-property browser-compat: api.Client.type --- {{APIRef("Service Workers API")}} The **`type`** read-only property of the {{domxref("Client")}} interface indicates the type of client the service worker is controlling. ## Value A string, representing the client type. The value can be one of - `"window"` - `"worker"` - `"sharedworker"` ## Examples ```js // service worker client (e.g. a document) function sendMessage(message) { return new Promise((resolve, reject) => { // note that this is the ServiceWorker.postMessage version navigator.serviceWorker.controller.postMessage(message); window.serviceWorker.onMessage = (e) => { resolve(e.data); }; }); } // controlling service worker self.addEventListener("message", (e) => { // e.source is a client object e.source.postMessage(`Hello! Your message was: ${e.data}`); // Let's also post the type value back to the client e.source.postMessage(e.source.type); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/client
data/mdn-content/files/en-us/web/api/client/frametype/index.md
--- title: "Client: frameType property" short-title: frameType slug: Web/API/Client/frameType page-type: web-api-instance-property browser-compat: api.Client.frameType --- {{APIRef("Service Workers API")}} The **`frameType`** read-only property of the {{domxref("Client")}} interface indicates the type of browsing context of the current {{domxref("Client")}}. This value can be one of `"auxiliary"`, `"top-level"`, `"nested"`, or `"none"`. ## Value One of these four strings: `"auxiliary"`, `"top-level"`, `"nested"`, or `"none"`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/scriptprocessornode/index.md
--- title: ScriptProcessorNode slug: Web/API/ScriptProcessorNode page-type: web-api-interface status: - deprecated browser-compat: api.ScriptProcessorNode --- {{APIRef("Web Audio API")}}{{Deprecated_Header}} The `ScriptProcessorNode` interface allows the generation, processing, or analyzing of audio using JavaScript. {{InheritanceDiagram}} > **Note:** This feature was replaced by [AudioWorklets](/en-US/docs/Web/API/AudioWorklet) and the {{domxref("AudioWorkletNode")}} interface. The `ScriptProcessorNode` interface is an {{domxref("AudioNode")}} audio-processing module that is linked to two buffers, one containing the input audio data, one containing the processed output audio data. An event, implementing the {{domxref("AudioProcessingEvent")}} interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data. ![The ScriptProcessorNode stores the input in a buffer, send the audioprocess event. The EventHandler takes the input buffer and fill the output buffer which is sent to the output by the ScriptProcessorNode.](webaudioscriptprocessingnode.png) The size of the input and output buffer are defined at the creation time, when the {{domxref("BaseAudioContext.createScriptProcessor")}} method is called (both are defined by {{domxref("BaseAudioContext.createScriptProcessor")}}'s `bufferSize` parameter). The buffer size must be a power of 2 between `256` and `16384`, that is `256`, `512`, `1024`, `2048`, `4096`, `8192` or `16384`. Small numbers lower the _latency_, but large number may be necessary to avoid audio breakup and glitches. If the buffer size is not defined, which is recommended, the browser will pick one that its heuristic deems appropriate. <table class="properties"> <tbody> <tr> <th scope="row">Number of inputs</th> <td><code>1</code></td> </tr> <tr> <th scope="row">Number of outputs</th> <td><code>1</code></td> </tr> <tr> <th scope="row">Channel count mode</th> <td><code>"max"</code></td> </tr> <tr> <th scope="row">Channel count</th> <td><code>2</code> (not used in the default count mode)</td> </tr> <tr> <th scope="row">Channel interpretation</th> <td><code>"speakers"</code></td> </tr> </tbody> </table> ## Instance properties _Inherits properties from its parent, {{domxref("AudioNode")}}_. - {{domxref("ScriptProcessorNode.bufferSize")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Returns an integer representing both the input and output buffer size. Its value can be a power of 2 value in the range `256` – `16384`. ## Instance methods _No specific methods; inherits methods from its parent, {{domxref("AudioNode")}}_. ## Events Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the `oneventname` property of this interface: - [`audioprocess`](/en-US/docs/Web/API/ScriptProcessorNode/audioprocess_event) {{Deprecated_Inline}} - : Fired when an input buffer of a `ScriptProcessorNode` is ready to be processed. Also available via the `onaudioprocess` event handler property. ## Examples See [`BaseAudioContext.createScriptProcessor()`](/en-US/docs/Web/API/BaseAudioContext/createScriptProcessor#examples) for example code. ## Specifications Since the August 29, 2014 [Web Audio API specification](https://www.w3.org/TR/webaudio/#ScriptProcessorNode) publication, this feature has been deprecated. It is no longer on track to become a standard. It was replaced by [AudioWorklets](/en-US/docs/Web/API/AudioWorklet) and the {{domxref("AudioWorkletNode")}} interface. ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/scriptprocessornode
data/mdn-content/files/en-us/web/api/scriptprocessornode/audioprocess_event/index.md
--- title: "ScriptProcessorNode: audioprocess event" short-title: audioprocess slug: Web/API/ScriptProcessorNode/audioprocess_event page-type: web-api-event status: - deprecated browser-compat: api.ScriptProcessorNode.audioprocess_event --- {{APIRef("Web Audio API")}}{{Deprecated_Header}} The `audioprocess` event of the {{domxref("ScriptProcessorNode")}} interface is fired when an input buffer of a script processor is ready to be processed. > **Note:** This feature was replaced by [AudioWorklets](/en-US/docs/Web/API/AudioWorklet) and the {{domxref("AudioWorkletNode")}} interface. This event is not cancelable and does not bubble. ## Event type An {{domxref("AudioProcessingEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("AudioProcessingEvent")}} ## Event properties _Also implements the properties inherited from its parent, {{domxref("Event")}}._ - `playbackTime` {{ReadOnlyInline}} - : A double representing the time when the audio will be played, as defined by the time of {{domxref("BaseAudioContext/currentTime", "AudioContext.currentTime")}}. - `inputBuffer` {{ReadOnlyInline}} - : An {{domxref("AudioBuffer")}} that is the buffer containing the input audio data to be processed. The number of channels is defined as a parameter `numberOfInputChannels`, of the factory method {{domxref("BaseAudioContext/createScriptProcessor", "AudioContext.createScriptProcessor()")}}. Note that the returned <code>AudioBuffer</code> is only valid in the scope of the event handler. - `outputBuffer` {{ReadOnlyInline}} - : An {{domxref("AudioBuffer")}} that is the buffer where the output audio data should be written. The number of channels is defined as a parameter, <code>numberOfOutputChannels</code>, of the factory method {{domxref("BaseAudioContext/createScriptProcessor", "AudioContext.createScriptProcessor()")}}. Note that the returned <code>AudioBuffer</code> is only valid in the scope of the event handler. ## Examples ```js scriptNode.addEventListener("audioprocess", (audioProcessingEvent) => { // The input buffer is a song we loaded earlier const inputBuffer = audioProcessingEvent.inputBuffer; // The output buffer contains the samples that will be modified and played const outputBuffer = audioProcessingEvent.outputBuffer; // Loop through the output channels (in this case there is only one) for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) { const inputData = inputBuffer.getChannelData(channel); const outputData = outputBuffer.getChannelData(channel); // Loop through the 4096 samples for (let sample = 0; sample < inputBuffer.length; sample++) { // make output equal to the same as the input outputData[sample] = inputData[sample]; // add noise to each output sample outputData[sample] += (Math.random() * 2 - 1) * 0.2; } } }); ``` You could also set up the event handler using the `onaudioprocess` property: ```js scriptNode.onaudioprocess = (audioProcessingEvent) => { // ... }; ``` ## Specifications Since the August 29, 2014, [Web Audio API specification](https://www.w3.org/TR/webaudio/#ScriptProcessorNode) publication, this feature has been deprecated. It is no longer on track to become a standard. It was replaced by [AudioWorklets](/en-US/docs/Web/API/AudioWorklet) and the {{domxref("AudioWorkletNode")}} interface. ## Browser compatibility {{Compat}} ## See also - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/scriptprocessornode
data/mdn-content/files/en-us/web/api/scriptprocessornode/buffersize/index.md
--- title: "ScriptProcessorNode: bufferSize property" short-title: bufferSize slug: Web/API/ScriptProcessorNode/bufferSize page-type: web-api-instance-property status: - deprecated browser-compat: api.ScriptProcessorNode.bufferSize --- {{APIRef("Web Audio API")}}{{Deprecated_Header}} The `bufferSize` property of the {{domxref("ScriptProcessorNode")}} interface returns an integer representing both the input and output buffer size, in sample-frames. Its value can be a power of 2 value in the range `256` – `16384`. > **Note:** This feature was replaced by [AudioWorklets](/en-US/docs/Web/API/AudioWorklet) and the {{domxref("AudioWorkletNode")}} interface. ## Value An integer. ## Examples See [`BaseAudioContext.createScriptProcessor()`](/en-US/docs/Web/API/BaseAudioContext/createScriptProcessor#examples) for example code. ## Specifications Since the August 29, 2014 [Web Audio API specification](https://www.w3.org/TR/webaudio/#ScriptProcessorNode) publication, this feature has been deprecated. It is no longer on track to become a standard. It was replaced by [AudioWorklets](/en-US/docs/Web/API/AudioWorklet) and the {{domxref("AudioWorkletNode")}} interface. ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/workerglobalscope/index.md
--- title: WorkerGlobalScope slug: Web/API/WorkerGlobalScope page-type: web-api-interface browser-compat: api.WorkerGlobalScope --- {{APIRef("Web Workers API")}} The **`WorkerGlobalScope`** interface of the [Web Workers API](/en-US/docs/Web/API/Web_Workers_API) is an interface representing the scope of any worker. Workers have no browsing context; this scope contains the information usually conveyed by {{domxref("Window")}} objects — in this case event handlers, the console or the associated {{domxref("WorkerNavigator")}} object. Each `WorkerGlobalScope` has its own event loop. This interface is usually specialized by each worker type: {{domxref("DedicatedWorkerGlobalScope")}} for dedicated workers, {{domxref("SharedWorkerGlobalScope")}} for shared workers, and {{domxref("ServiceWorkerGlobalScope")}} for [ServiceWorker](/en-US/docs/Web/API/Service_Worker_API). The `self` property returns the specialized scope for each context. {{InheritanceDiagram}} ## Instance properties _This interface inherits properties from the {{domxref("EventTarget")}} interface._ ### Standard properties - {{domxref("caches", "WorkerGlobalScope.caches")}} {{ReadOnlyInline}} - : Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests. - {{domxref("crossOriginIsolated", "WorkerGlobalScope.crossOriginIsolated")}} {{ReadOnlyInline}} - : Returns a boolean value that indicates whether the website is in a cross-origin isolation state. - {{domxref("crypto_property", "WorkerGlobalScope.crypto")}} {{ReadOnlyInline}} - : Returns the {{domxref("Crypto")}} object associated to the global object. - {{domxref("WorkerGlobalScope.fonts")}} {{ReadOnlyInline}} - : Returns the {{domxref("FontFaceSet")}} associated with the worker. - {{domxref("indexedDB", "WorkerGlobalScope.indexedDB")}} {{ReadOnlyInline}} - : Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object. - {{domxref("isSecureContext", "WorkerGlobalScope.isSecureContext")}} {{ReadOnlyInline}} - : Returns a boolean indicating whether the current context is secure (`true`) or not (`false`). - {{domxref("WorkerGlobalScope.location")}} {{ReadOnlyInline}} - : Returns the {{domxref("WorkerLocation")}} associated with the worker. It is a specific location object, mostly a subset of the {{domxref("Location")}} for browsing scopes, but adapted to workers.r. - {{domxref("WorkerGlobalScope.navigator")}} {{ReadOnlyInline}} - : Returns the {{domxref("WorkerNavigator")}} associated with the worker. It is a specific navigator object, mostly a subset of the {{domxref("Navigator")}} for browsing scopes, but adapted to workers. - {{domxref("origin", "WorkerGlobalScope.origin")}} {{ReadOnlyInline}} - : Returns the global object's origin, serialized as a string. - {{domxref("performance_property", "WorkerGlobalScope.performance")}} {{ReadOnlyInline}} - : Returns the {{domxref("Performance")}} associated with the worker. It is a regular performance object, except that only a subset of its property and methods are available to workers. - {{domxref("scheduler_property", "WorkerGlobalScope.scheduler")}} {{ReadOnlyInline}} - : Returns the {{domxref("Scheduler")}} object associated with the current context. This is the entry point for using the [Prioritized Task Scheduling API](/en-US/docs/Web/API/Prioritized_Task_Scheduling_API). - {{domxref("WorkerGlobalScope.self")}} {{ReadOnlyInline}} - : Returns a reference to the `WorkerGlobalScope` itself. Most of the time it is a specific scope like {{domxref("DedicatedWorkerGlobalScope")}}, {{domxref("SharedWorkerGlobalScope")}} or {{domxref("ServiceWorkerGlobalScope")}}. ### Non-standard properties - {{domxref("console")}} {{ReadOnlyInline}} {{Non-standard_inline}} - : Returns the {{domxref("console")}} associated with the worker. ## Instance methods _This interface inherits methods from the {{domxref("EventTarget")}} interface._ ### Standard methods - {{domxref("atob()", "WorkerGlobalScope.atob()")}} - : Decodes a string of data which has been encoded using base-64 encoding. - {{domxref("btoa()", "WorkerGlobalScope.btoa()")}} - : Creates a base-64 encoded {{Glossary("ASCII")}} string from a string of binary data. - {{domxref("clearInterval()", "WorkerGlobalScope.clearInterval()")}} - : Cancels the repeated execution set using {{domxref("setInterval()")}}. - {{domxref("clearTimeout()", "WorkerGlobalScope.clearTimeout()")}} - : Cancels the delayed execution set using {{domxref("setTimeout()")}}. - {{domxref("createImageBitmap()", "WorkerGlobalScope.createImageBitmap()")}} - : Accepts a variety of different image sources, and returns a {{jsxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at _(sx, sy)_ with width sw, and height sh. - {{domxref("fetch()", "WorkerGlobalScope.fetch()")}} - : Starts the process of fetching a resource from the network. - {{domxref("WorkerGlobalScope.importScripts()")}} - : Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: `importScripts('foo.js', 'bar.js');`. - {{domxref("queueMicrotask()", "WorkerGlobalScope.queueMicrotask()")}} - : Queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. - {{domxref("setInterval()", "WorkerGlobalScope.setInterval()")}} - : Schedules a function to execute every time a given number of milliseconds elapses. - {{domxref("setTimeout()", "WorkerGlobalScope.setTimeout()")}} - : Schedules a function to execute in a given amount of time. - {{domxref("structuredClone()", "WorkerGlobalScope.structuredClone()")}} - : Creates a [deep clone](/en-US/docs/Glossary/Deep_copy) of a given value using the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - {{domxref("reportError()", "WorkerGlobalScope.reportError()")}} - : Reports an error in a script, emulating an unhandled exception. ### Non-standard methods - {{domxref("WorkerGlobalScope.dump()")}} {{deprecated_inline}} {{non-standard_inline}} - : Allows you to write a message to stdout — i.e. in your terminal. This is the same as Firefox's {{domxref("window.dump")}}, but for workers. ## Events - {{domxref("WorkerGlobalScope/error_event", "error")}} - : Fired when an error occurred. - {{domxref("WorkerGlobalScope/languagechange_event", "languagechange")}} - : Fired at the global/worker scope object when the user's preferred languages change. - {{domxref("WorkerGlobalScope/offline_event", "offline")}} - : Fired when the browser has lost access to the network and the value of `navigator.onLine` switched to `false`. - {{domxref("WorkerGlobalScope/online_event", "online")}} - : Fired when the browser has gained access to the network and the value of `navigator.onLine` switched to `true`. - {{domxref("WorkerGlobalScope/rejectionhandled_event", "rejectionhandled")}} - : Fired on handled {{jsxref("Promise")}} rejection events. - {{domxref("WorkerGlobalScope/securitypolicyviolation_event", "securitypolicyviolation")}} - : Fired when a [Content Security Policy](/en-US/docs/Web/HTTP/CSP) is violated. - {{domxref("WorkerGlobalScope/unhandledrejection_event", "unhandledrejection")}} - : Fired on unhandled {{jsxref("Promise")}} rejection events. ## Example You won't access `WorkerGlobalScope` directly in your code; however, its properties and methods are inherited by more specific global scopes such as {{domxref("DedicatedWorkerGlobalScope")}} and {{domxref("SharedWorkerGlobalScope")}}. For example, you could import another script into the worker and print out the contents of the worker scope's `navigator` object using the following two lines: ```js importScripts("foo.js"); console.log(navigator); ``` > **Note:** Since the global scope of the worker script is effectively the global scope of the worker you are running ({{domxref("DedicatedWorkerGlobalScope")}} or whatever) and all worker global scopes inherit methods, properties, etc. from `WorkerGlobalScope`, you can run lines such as those above without specifying a parent object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other global object interface: {{domxref("Window")}}, {{domxref("DedicatedWorkerGlobalScope")}}, {{domxref("SharedWorkerGlobalScope")}}, {{domxref("ServiceWorkerGlobalScope")}} - Other Worker-related interfaces: {{domxref("Worker")}}, {{domxref("WorkerLocation")}} and {{domxref("WorkerNavigator")}} - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/dump/index.md
--- title: "WorkerGlobalScope: dump() method" short-title: dump() slug: Web/API/WorkerGlobalScope/dump page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.WorkerGlobalScope.dump --- {{APIRef("Web Workers API")}}{{Non-standard_Header}}{{Deprecated_Header}} The **`WorkerGlobalScope.dump()`** method logs messages to the browser's standard output (`stdout`). If the browser was started from a terminal, output sent to `dump()` will appear in the terminal. This is the same as {{domxref("Window.dump()")}}, but for workers. Output from `dump()` is _not_ sent to the browser's developer tools console. To log to the developer tools console, use [`console.log()`](/en-US/docs/Web/API/console/log_static). ## Syntax ```js-nolint dump(message) ``` ### Parameters - `message` - : A string containing the message to log. ### Return value None ({{jsxref("undefined")}}). ## Specifications This feature is not part of any specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/online_event/index.md
--- title: "WorkerGlobalScope: online event" short-title: online slug: Web/API/WorkerGlobalScope/online_event page-type: web-api-event browser-compat: api.WorkerGlobalScope.online_event --- {{APIRef("Web Workers API")}} The **`online`** event of the {{domxref("WorkerGlobalScope")}} fires when the device reconnects to the internet. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("online", (event) => {}); ononline = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example The following code snippet shows an `onoffline` handler set inside a worker: ```js self.ononline = () => { console.log("Your worker is now online"); }; ``` The same snippet, but using `addEventListener()`: ```js self.addEventListener("online", () => { console.log("Your worker is now online"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also The {{domxref("WorkerGlobalScope")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/languagechange_event/index.md
--- title: "WorkerGlobalScope: languagechange event" short-title: languagechange slug: Web/API/WorkerGlobalScope/languagechange_event page-type: web-api-event browser-compat: api.WorkerGlobalScope.languagechange_event --- {{APIRef}} The **`languagechange`** event is fired at the global scope object when the user's preferred language changes. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("languagechange", (event) => {}); onlanguagechange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples You can use the `languagechange` event in an {{domxref("EventTarget/addEventListener", "addEventListener")}} method: ```js worker.addEventListener("languagechange", () => { console.log("languagechange event detected!"); }); ``` Or use the `onlanguagechange` event handler property: ```js worker.onlanguagechange = (event) => { console.log("languagechange event detected!"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WorkerNavigator.language", "navigator.language")}} - {{domxref("WorkerNavigator.languages", "navigator.languages")}} - {{domxref("Navigator")}}
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/fonts/index.md
--- title: "WorkerGlobalScope: fonts property" short-title: fonts slug: Web/API/WorkerGlobalScope/fonts page-type: web-api-instance-property browser-compat: api.WorkerGlobalScope.fonts --- {{APIRef("DOM")}} The **`fonts`** property of the {{domxref("WorkerGlobalScope")}} interface returns the {{domxref("FontFaceSet")}} interface of the worker. This property is part of the [CSS Font Loading API](/en-US/docs/Web/API/CSS_Font_Loading_API). ## Value The returned value is the {{domxref("FontFaceSet")}} interface of the worker. The `FontFaceSet` interface is useful for loading new fonts, checking the status of previously loaded fonts etc. ## Examples ### Doing operation after all fonts are loaded ```js fonts.ready.then(() => { // Any operation that needs to be done only after all the fonts // have finished loading can go here. }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("FontFaceSet")}} interface - {{domxref("FontFace")}}
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/unhandledrejection_event/index.md
--- title: "WorkerGlobalScope: unhandledrejection event" short-title: unhandledrejection slug: Web/API/WorkerGlobalScope/unhandledrejection_event page-type: web-api-event browser-compat: api.WorkerGlobalScope.unhandledrejection_event --- {{APIRef}} The **`unhandledrejection`** event is sent to the global scope (typically {{domxref("WorkerGlobalScope")}}) of a script when a {{jsxref("Promise")}} that has no rejection handler is rejected. This is useful for debugging and for providing fallback error handling for unexpected situations. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js self.addEventListener("unhandledrejection", (event) => {}); self.onunhandledrejection = (event) => {}; ``` ## Event type A {{domxref("PromiseRejectionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PromiseRejectionEvent")}} ## Event properties - {{domxref("PromiseRejectionEvent.promise")}} {{ReadOnlyInline}} - : The JavaScript {{jsxref("Promise")}} that was rejected. - {{domxref("PromiseRejectionEvent.reason")}} {{ReadOnlyInline}} - : A value or {{jsxref("Object")}} indicating why the promise was rejected, as passed to {{jsxref("Promise.reject()")}}. ## Examples ### Basic error logging This example logs information about the unhandled promise rejection to the console. ```js self.addEventListener("unhandledrejection", (event) => { console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`); }); ``` You can also use the `onunhandledrejection` event handler property to set up the event listener: ```js self.onunhandledrejection = (event) => { console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`); }; ``` ### Preventing default handling Many environments (such as {{Glossary("Node.js")}}) report unhandled promise rejections to the console by default. You can prevent that from happening by adding a handler for `unhandledrejection` events that—in addition to any other tasks you wish to perform—calls {{domxref("Event.preventDefault()", "preventDefault()")}} to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code. This works because `unhandledrejection` is cancelable. ```js self.addEventListener("unhandledrejection", (event) => { // code for handling the unhandled rejection // … // Prevent the default handling (such as outputting the // error to the console) event.preventDefault(); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Promise rejection events](/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events) - {{domxref("PromiseRejectionEvent")}} - {{jsxref("Promise")}} - {{domxref("WorkerGlobalScope/rejectionhandled_event", "rejectionhandled")}} event
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/offline_event/index.md
--- title: "WorkerGlobalScope: offline event" short-title: offline slug: Web/API/WorkerGlobalScope/offline_event page-type: web-api-event browser-compat: api.WorkerGlobalScope.offline_event --- {{APIRef("Web Workers API")}} The **`offline`** event of the {{domxref("WorkerGlobalScope")}} fires when the device loses connection to the internet. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("offline", (event) => {}); onoffline = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example The following code snippet shows an `onoffline` handler set inside a worker: ```js self.onoffline = () => { console.log("Your worker is now offline"); }; ``` The same snippet, but using `addEventListener()`: ```js self.addEventListener("offline", () => { console.log("Your worker is now offline"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also The {{domxref("WorkerGlobalScope")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/importscripts/index.md
--- title: "WorkerGlobalScope: importScripts() method" short-title: importScripts() slug: Web/API/WorkerGlobalScope/importScripts page-type: web-api-instance-method browser-compat: api.WorkerGlobalScope.importScripts --- {{APIRef("Web Workers API")}} The **`importScripts()`** method of the {{domxref("WorkerGlobalScope")}} interface synchronously imports one or more scripts into the worker's scope. ## Syntax ```js-nolint importScripts(path0) importScripts(path0, path1) importScripts(path0, path1, /* …, */ pathN) ``` ### Parameters - `pathN` - : A string value representing the URL of the script to be imported. The URL may be absolute or relative. If the URL is relative, it is relative to the HTML document's base URL. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `NetworkError` - : Imported scripts were served without a `text/javascript` MIME type or without one of the permitted [legacy JavaScript MIME types](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#legacy_javascript_mime_types). ## Examples If you had some functionality written in a separate script called `foo.js` that you wanted to use inside worker.js, you could import it using the following line: ```js importScripts("foo.js"); ``` `importScripts()` and `self.importScripts()` are effectively equivalent — both represent `importScripts()` being called from inside the worker's inner scope. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WorkerGlobalScope")}}
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/navigator/index.md
--- title: "WorkerGlobalScope: navigator property" short-title: navigator slug: Web/API/WorkerGlobalScope/navigator page-type: web-api-instance-property browser-compat: api.WorkerGlobalScope.navigator --- {{APIRef("Web Workers API")}} The **`navigator`** read-only property of the {{domxref("WorkerGlobalScope")}} interface returns the {{domxref("WorkerNavigator")}} associated with the worker. It is a specific navigator object, mostly a subset of the {{domxref("Navigator")}} for browsing scopes, but adapted to workers. ## Value A {{domxref("WorkerNavigator")}} object. ## Examples If you call the following ```js console.log(navigator); ``` inside a worker (which would basically be the equivalent of `self.console.log(self.navigator);`, as these are being called on the worker scope, which can be referenced with {{domxref("WorkerGlobalScope.self")}}), you will get a {{domxref("WorkerNavigator")}} object written to the console — something like the following: ```plain Object {onLine: true, userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) Ap…ML, like Gecko) Chrome/40.0.2214.93 Safari/537.36", product: "Gecko", platform: "MacIntel", appVersion: "5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKi…ML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"…} appCodeName: "Mozilla" appName: "Netscape" appVersion: "5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36" hardwareConcurrency: 4 onLine: true platform: "MacIntel" product: "Gecko" userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36" __proto__: Object ``` You could use this navigator object to return more information about the runtime environment, as you might do with a normal {{domxref("Navigator")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also {{domxref("WorkerNavigator")}}
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/self/index.md
--- title: "WorkerGlobalScope: self property" short-title: self slug: Web/API/WorkerGlobalScope/self page-type: web-api-instance-property browser-compat: api.WorkerGlobalScope.self --- {{APIRef("Web Workers API")}} The **`self`** read-only property of the {{domxref("WorkerGlobalScope")}} interface returns a reference to the `WorkerGlobalScope` itself. Most of the time it is a specific scope like {{domxref("DedicatedWorkerGlobalScope")}}, {{domxref("SharedWorkerGlobalScope")}}, or {{domxref("ServiceWorkerGlobalScope")}}. ## Value A global scope object (differs depending on the type of worker you are dealing with, as indicated above). ## Examples If you called ```js console.log(self); ``` inside a worker, you will get a worker global scope of the same type as that worker object written to the console — something like the following: ```plain DedicatedWorkerGlobalScope { undefined: undefined, Infinity: Infinity, Math: MathConstructor, NaN: NaN, Intl: Object…} Infinity: Infinity Array: function Array() { [native code] } arguments: null caller: null isArray: function isArray() { [native code] } length: 1 name: "Array" observe: function observe() { [native code] } prototype: Array[0] unobserve: function unobserve() { [native code] } __proto__: function Empty() {} <function scope> ArrayBuffer: function ArrayBuffer() { [native code] } Blob: function Blob() { [native code] } Boolean: function Boolean() { [native code] } DataView: function DataView() { [native code] } Date: function Date() { [native code] } DedicatedWorkerGlobalScope: function DedicatedWorkerGlobalScope() { [native code] } Error: function Error() { [native code] } // etc. etc. ``` This provides a full list of the objects available to that worker scope, so it is quite a useful test if you want to see whether something is available to your worker or not. We also maintain a list of [Functions and classes available to Web Workers](/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also {{domxref("WorkerGlobalScope")}}
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/securitypolicyviolation_event/index.md
--- title: "WorkerGlobalScope: securitypolicyviolation event" short-title: securitypolicyviolation slug: Web/API/WorkerGlobalScope/securitypolicyviolation_event page-type: web-api-event browser-compat: api.WorkerGlobalScope.securitypolicyviolation_event --- {{APIRef}} The **`securitypolicyviolation`** event is fired when a [Content Security Policy](/en-US/docs/Web/HTTP/CSP) is violated in a worker. The handler can be assigned using the `onsecuritypolicyviolation` event handler property or using {{domxref("EventTarget.addEventListener()")}}. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("securitypolicyviolation", (event) => {}); onsecuritypolicyviolation = (event) => {}; ``` ## Event type A {{domxref("SecurityPolicyViolationEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SecurityPolicyViolationEvent")}} ## Examples The code below shows how you might add an event handler function using the `onsecuritypolicyviolation` event handler property or call `addEventListener()` method. ```js self.onsecuritypolicyviolation = (e) => { // Handle SecurityPolicyViolationEvent e here }; self.addEventListener("securitypolicyviolation", (e) => { // Handle SecurityPolicyViolationEvent e here }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("Document/securitypolicyviolation_event", "securitypolicyviolation")}} event of the {{domxref("Document")}} interface - The {{domxref("Element/securitypolicyviolation_event", "securitypolicyviolation")}} event of the {{domxref("Element")}} interface - [HTTP > Content Security Policy](/en-US/docs/Web/HTTP/CSP)
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/rejectionhandled_event/index.md
--- title: "WorkerGlobalScope: rejectionhandled event" short-title: rejectionhandled slug: Web/API/WorkerGlobalScope/rejectionhandled_event page-type: web-api-event browser-compat: api.WorkerGlobalScope.rejectionhandled_event --- {{APIRef}} The **`rejectionhandled`** event is sent to the script's global scope (typically {{domxref("WorkerGlobalScope")}}) whenever a rejected {{jsxref("Promise")}} is handled late, i.e., when a handler is attached to the promise after its rejection had caused an {{domxref("WorkerGlobalScope.unhandledrejection_event", "unhandledrejection")}} event. This can be used in debugging and for general application resiliency, in tandem with the `unhandledrejection` event, which is sent when a promise is rejected but there is no handler for the rejection at the time. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js self.addEventListener("rejectionhandled", (event) => {}); self.onrejectionhandled = (event) => {}; ``` ## Event type A {{domxref("PromiseRejectionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PromiseRejectionEvent")}} ## Event properties - {{domxref("PromiseRejectionEvent.promise")}} {{ReadOnlyInline}} - : The {{jsxref("Promise")}} that was rejected. - {{domxref("PromiseRejectionEvent.reason")}} {{ReadOnlyInline}} - : A value or {{jsxref("Object")}} indicating why the promise was rejected, as passed to {{jsxref("Promise.reject()")}}. ## Example You can use the `rejectionhandled` event to log promises that get rejected to the console, along with the reasons why they were rejected: ```js self.addEventListener("rejectionhandled", (event) => { console.log(`Promise rejected; reason: ${event.reason}`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Promise rejection events](/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events) - {{domxref("PromiseRejectionEvent")}} - {{jsxref("Promise")}} - {{domxref("WorkerGlobalScope/unhandledrejection_event", "unhandledrejection")}}
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/location/index.md
--- title: "WorkerGlobalScope: location property" short-title: location slug: Web/API/WorkerGlobalScope/location page-type: web-api-instance-property browser-compat: api.WorkerGlobalScope.location --- {{APIRef("Web Workers API")}} The **`location`** read-only property of the {{domxref("WorkerGlobalScope")}} interface returns the {{domxref("WorkerLocation")}} associated with the worker. It is a specific location object, mostly a subset of the {{domxref("Location")}} for browsing scopes, but adapted to workers. ## Value A {{domxref("WorkerLocation")}} object. ## Examples If you called the following in a document served at `localhost:8000` ```js console.log(location); ``` inside a worker (which would basically be the equivalent of `self.console.log(self.location);`, as these are being called on the worker scope, which can be referenced with {{domxref("WorkerGlobalScope.self")}}), you will get a {{domxref("WorkerLocation")}} object written to the console — something like the following: ```plain WorkerLocation {hash: "", search: "", pathname: "/worker.js", port: "8000", hostname: "localhost"…} hash: "" host: "localhost:8000" hostname: "localhost" href: "http://localhost:8000/worker.js" origin: "http://localhost:8000" pathname: "/worker.js" port: "8000" protocol: "http:" search: "" __proto__: WorkerLocation ``` You could use this location object to return more information about the document's location, as you might do with a normal {{domxref("Location")}} object. > **Note:** Firefox has a bug with using `console.log` inside shared/service workers (see [Firefox bug 1058644](https://bugzil.la/1058644)), which may return strange results, but this should be fixed soon. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also {{domxref("WorkerGlobalScope")}}
0
data/mdn-content/files/en-us/web/api/workerglobalscope
data/mdn-content/files/en-us/web/api/workerglobalscope/error_event/index.md
--- title: "WorkerGlobalScope: error event" short-title: error slug: Web/API/WorkerGlobalScope/error_event page-type: web-api-event browser-compat: api.WorkerGlobalScope.error_event --- {{APIRef("Web Workers API")}} The **`error`** event of the {{domxref("WorkerGlobalScope")}} interface fires when an error occurs in the worker. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("error", (event) => {}); onerror = (message, filename, lineno, colno, error) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example The following code snippet shows an `onerror` handler set inside a worker: ```js self.onerror = () => { console.log("There is an error inside your worker!"); }; ``` The same snippet, but using `addEventListener()`: ```js self.addEventListener("error", () => { console.log("There is an error inside your worker!"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also The {{domxref("WorkerGlobalScope")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfegaussianblurelement/index.md
--- title: SVGFEGaussianBlurElement slug: Web/API/SVGFEGaussianBlurElement page-type: web-api-interface browser-compat: api.SVGFEGaussianBlurElement --- {{APIRef("SVG")}} The **`SVGFEGaussianBlurElement`** interface corresponds to the {{SVGElement("feGaussianBlur")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGFEGaussianBlurElement.edgeMode")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("edgeMode")}} attribute of the given element. Returns two identical values that are one of the following values: - `SVG_EDGEMODE_UNKNOWN` (0) - : The type is not one of predefined types. It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. - `SVG_EDGEMODE_DUPLICATE` (1) - : Corresponds to the `duplicate` value. - `SVG_EDGEMODE_WRAP` (2) - : Corresponds to the `wrap` value. - `SVG_EDGEMODE_NONE` (3) - : Corresponds to `none` value. - {{domxref("SVGFEGaussianBlurElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element. - {{domxref("SVGFEGaussianBlurElement.in1")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element. - {{domxref("SVGFEGaussianBlurElement.result")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element. - {{domxref("SVGFEGaussianBlurElement.stdDeviationX")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the (possibly automatically computed) X component of the {{SVGAttr("stdDeviation")}} attribute of the given element. - {{domxref("SVGFEGaussianBlurElement.stdDeviationY")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the (possibly automatically computed) Y component of the {{SVGAttr("stdDeviation")}} attribute of the given element. - {{domxref("SVGFEGaussianBlurElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element. - {{domxref("SVGFEGaussianBlurElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGFEGaussianBlurElement.y")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element. ## Instance methods _This interface also inherits methods of its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGFEGaussianBlurElement.setStdDeviation()")}} - : Sets the values for the `stdDeviation` attribute. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("feGaussianBlur")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/index.md
--- title: SpeechSynthesisUtterance slug: Web/API/SpeechSynthesisUtterance page-type: web-api-interface browser-compat: api.SpeechSynthesisUtterance --- {{APIRef("Web Speech API")}} The **`SpeechSynthesisUtterance`** interface of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) represents a speech request. It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.) {{InheritanceDiagram}} ## Constructor - {{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance", "SpeechSynthesisUtterance()")}} - : Returns a new `SpeechSynthesisUtterance` object instance. ## Instance properties _`SpeechSynthesisUtterance` also inherits properties from its parent interface, {{domxref("EventTarget")}}._ - {{domxref("SpeechSynthesisUtterance.lang")}} - : Gets and sets the language of the utterance. - {{domxref("SpeechSynthesisUtterance.pitch")}} - : Gets and sets the pitch at which the utterance will be spoken at. - {{domxref("SpeechSynthesisUtterance.rate")}} - : Gets and sets the speed at which the utterance will be spoken at. - {{domxref("SpeechSynthesisUtterance.text")}} - : Gets and sets the text that will be synthesized when the utterance is spoken. - {{domxref("SpeechSynthesisUtterance.voice")}} - : Gets and sets the voice that will be used to speak the utterance. - {{domxref("SpeechSynthesisUtterance.volume")}} - : Gets and sets the volume that the utterance will be spoken at. ## Events Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the `oneventname` property of this interface. - [`boundary`](/en-US/docs/Web/API/SpeechSynthesisUtterance/boundary_event) - : Fired when the spoken utterance reaches a word or sentence boundary. Also available via the `onboundary` property. - [`end`](/en-US/docs/Web/API/SpeechSynthesisUtterance/end_event) - : Fired when the utterance has finished being spoken. Also available via the `onend` property. - [`error`](/en-US/docs/Web/API/SpeechSynthesisUtterance/error_event) - : Fired when an error occurs that prevents the utterance from being successfully spoken. Also available via the `onerror` property - [`mark`](/en-US/docs/Web/API/SpeechSynthesisUtterance/mark_event) - : Fired when the spoken utterance reaches a named SSML "mark" tag. Also available via the `onmark` property. - [`pause`](/en-US/docs/Web/API/SpeechSynthesisUtterance/pause_event) - : Fired when the utterance is paused part way through. Also available via the `onpause` property. - [`resume`](/en-US/docs/Web/API/SpeechSynthesisUtterance/resume_event) - : Fired when a paused utterance is resumed. Also available via the `onresume` property. - [`start`](/en-US/docs/Web/API/SpeechSynthesisUtterance/start_event) - : Fired when the utterance has begun to be spoken. Also available via the `onstart` property. ## Examples In our basic [Speech synthesizer demo](https://mdn.github.io/dom-examples/web-speech-api/speak-easy-synthesis/), we first grab a reference to the SpeechSynthesis controller using `window.speechSynthesis`. After defining some necessary variables, we retrieve a list of the voices available using {{domxref("SpeechSynthesis.getVoices()")}} and populate a select menu with them so the user can choose what voice they want. Inside the `inputForm.onsubmit` handler, we stop the form submitting with {{domxref("Event.preventDefault","preventDefault()")}}, use the {{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()", "constructor")}} to create a new utterance instance containing the text from the text {{htmlelement("input")}}, set the utterance's {{domxref("SpeechSynthesisUtterance.voice","voice")}} to the voice selected in the {{htmlelement("select")}} element, and start the utterance speaking via the {{domxref("SpeechSynthesis.speak()")}} method. ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); let voices; function loadVoices() { voices = synth.getVoices(); for (let i = 0; i < voices.length; i++) { const option = document.createElement("option"); option.textContent = `${voices[i].name} (${voices[i].lang})`; option.value = i; voiceSelect.appendChild(option); } } // in Google Chrome the voices are not ready on page load if ("onvoiceschanged" in synth) { synth.onvoiceschanged = loadVoices; } else { loadVoices(); } inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); utterThis.voice = voices[voiceSelect.value]; synth.speak(utterThis); inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/pause_event/index.md
--- title: "SpeechSynthesisUtterance: pause event" short-title: pause slug: Web/API/SpeechSynthesisUtterance/pause_event page-type: web-api-event browser-compat: api.SpeechSynthesisUtterance.pause_event --- {{APIRef("Web Speech API")}} The **`pause`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechSynthesisUtterance")}} object is fired when the utterance is paused part way through. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("pause", (event) => {}); onpause = (event) => {}; ``` ## Event type A {{domxref("SpeechSynthesisEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechSynthesisEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechSynthesisEvent.charIndex", "charIndex")}} {{ReadOnlyInline}} - : Returns the index position of the character in the {{domxref("SpeechSynthesisUtterance.text")}} that was being spoken when the event was triggered. - {{domxref("SpeechSynthesisEvent.elapsedTime", "elapsedTime")}} {{ReadOnlyInline}} - : Returns the elapsed time in seconds after the {{domxref("SpeechSynthesisUtterance.text")}} started being spoken that the event was triggered at. - {{domxref("SpeechSynthesisEvent.name", "name")}} {{ReadOnlyInline}} - : Returns the name associated with certain types of events occurring as the {{domxref("SpeechSynthesisUtterance.text")}} is being spoken: the name of the [SSML](https://www.w3.org/TR/speech-synthesis/#S3.3.2) marker reached in the case of a {{domxref("SpeechSynthesisUtterance.mark_event", "mark")}} event, or the type of boundary reached in the case of a {{domxref("SpeechSynthesisUtterance.boundary_event", "boundary")}} event. - {{domxref("SpeechSynthesisEvent.utterance", "utterance")}} {{ReadOnlyInline}} - : Returns the {{domxref("SpeechSynthesisUtterance")}} instance that the event was triggered on. ## Examples You can use the `pause` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js utterThis.addEventListener("pause", (event) => { console.log(`Speech paused after ${event.elapsedTime} seconds.`); }); ``` Or use the `onpause` event handler property: ```js utterThis.onpause = (event) => { console.log(`Speech paused after ${event.elapsedTime} seconds.`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/voice/index.md
--- title: "SpeechSynthesisUtterance: voice property" short-title: voice slug: Web/API/SpeechSynthesisUtterance/voice page-type: web-api-instance-property browser-compat: api.SpeechSynthesisUtterance.voice --- {{APIRef("Web Speech API")}} The **`voice`** property of the {{domxref("SpeechSynthesisUtterance")}} interface gets and sets the voice that will be used to speak the utterance. This should be set to one of the {{domxref("SpeechSynthesisVoice")}} objects returned by {{domxref("SpeechSynthesis.getVoices()")}}. If not set by the time the utterance is spoken, the voice used will be the most suitable default voice available for the utterance's {{domxref("SpeechSynthesisUtterance.lang","lang")}} setting. ## Value A {{domxref("SpeechSynthesisVoice")}} object. ## Examples ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); const voices = synth.getVoices(); // ... inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); for (let i = 0; i < voices.length; i++) { if (voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } synth.speak(utterThis); inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/volume/index.md
--- title: "SpeechSynthesisUtterance: volume property" short-title: volume slug: Web/API/SpeechSynthesisUtterance/volume page-type: web-api-instance-property browser-compat: api.SpeechSynthesisUtterance.volume --- {{APIRef("Web Speech API")}} The **`volume`** property of the {{domxref("SpeechSynthesisUtterance")}} interface gets and sets the volume that the utterance will be spoken at. If not set, the default value 1 will be used. ## Value A float that represents the volume value, between 0 (lowest) and 1 (highest.) If [SSML](https://www.w3.org/TR/speech-synthesis/) is used, this value will be overridden by [prosody tags](https://www.w3.org/TR/speech-synthesis/#S3.2.4) in the markup. ## Examples ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); const voices = synth.getVoices(); // ... inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); for (let i = 0; i < voices.length; i++) { if (voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } utterThis.volume = 0.5; synth.speak(utterThis); inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/speechsynthesisutterance/index.md
--- title: "SpeechSynthesisUtterance: SpeechSynthesisUtterance() constructor" short-title: SpeechSynthesisUtterance() slug: Web/API/SpeechSynthesisUtterance/SpeechSynthesisUtterance page-type: web-api-constructor browser-compat: api.SpeechSynthesisUtterance.SpeechSynthesisUtterance --- {{APIRef("Web Speech API")}} The `SpeechSynthesisUtterance()` constructor of the {{domxref("SpeechSynthesisUtterance")}} interface returns a new `SpeechSynthesisUtterance` object instance. ## Syntax ```js-nolint new SpeechSynthesisUtterance(text) ``` ### Parameters - `text` - : A string containing the text that will be synthesized when the utterance is spoken. ## Examples The following snippet is excerpted from our [Speech synthesizer demo](https://github.com/mdn/dom-examples/tree/main/web-speech-api/speak-easy-synthesis). ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); const voices = synth.getVoices(); // ... inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); for (let i = 0; i < voices.length; i++) { if (voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } synth.speak(utterThis); inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/text/index.md
--- title: "SpeechSynthesisUtterance: text property" short-title: text slug: Web/API/SpeechSynthesisUtterance/text page-type: web-api-instance-property browser-compat: api.SpeechSynthesisUtterance.text --- {{APIRef("Web Speech API")}} The **`text`** property of the {{domxref("SpeechSynthesisUtterance")}} interface gets and sets the text that will be synthesized when the utterance is spoken. The text may be provided as plain text, or a well-formed [SSML](https://www.w3.org/TR/speech-synthesis/) document. The SSML tags will be stripped away by devices that don't support SSML. ## Value A string representing the text to the synthesized. The maximum length of the text that can be spoken in each utterance is 32,767 characters. ## Examples ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); const voices = synth.getVoices(); // ... inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); for (let i = 0; i < voices.length; i++) { if (voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } console.log(utterThis.text); synth.speak(utterThis); inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/resume_event/index.md
--- title: "SpeechSynthesisUtterance: resume event" short-title: resume slug: Web/API/SpeechSynthesisUtterance/resume_event page-type: web-api-event browser-compat: api.SpeechSynthesisUtterance.resume_event --- {{APIRef("Web Speech API")}} The **`resume`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechSynthesisUtterance")}} object is fired when a paused utterance is resumed. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("resume", (event) => {}); onresume = (event) => {}; ``` ## Event type A {{domxref("SpeechSynthesisEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechSynthesisEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechSynthesisEvent.charIndex", "charIndex")}} {{ReadOnlyInline}} - : Returns the index position of the character in the {{domxref("SpeechSynthesisUtterance.text")}} that was being spoken when the event was triggered. - {{domxref("SpeechSynthesisEvent.elapsedTime", "elapsedTime")}} {{ReadOnlyInline}} - : Returns the elapsed time in seconds after the {{domxref("SpeechSynthesisUtterance.text")}} started being spoken that the event was triggered at. - {{domxref("SpeechSynthesisEvent.name", "name")}} {{ReadOnlyInline}} - : Returns the name associated with certain types of events occurring as the {{domxref("SpeechSynthesisUtterance.text")}} is being spoken: the name of the [SSML](https://www.w3.org/TR/speech-synthesis/#S3.3.2) marker reached in the case of a {{domxref("SpeechSynthesisUtterance.mark_event", "mark")}} event, or the type of boundary reached in the case of a {{domxref("SpeechSynthesisUtterance.boundary_event", "boundary")}} event. - {{domxref("SpeechSynthesisEvent.utterance", "utterance")}} {{ReadOnlyInline}} - : Returns the {{domxref("SpeechSynthesisUtterance")}} instance that the event was triggered on. ## Examples You can use the `resume` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js utterThis.addEventListener("resume", (event) => { console.log(`Speech resumed after ${event.elapsedTime} seconds.`); }); ``` Or use the `onresume` event handler property: ```js utterThis.onresume = (event) => { console.log(`Speech resumed after ${event.elapsedTime} seconds.`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/lang/index.md
--- title: "SpeechSynthesisUtterance: lang property" short-title: lang slug: Web/API/SpeechSynthesisUtterance/lang page-type: web-api-instance-property browser-compat: api.SpeechSynthesisUtterance.lang --- {{APIRef("Web Speech API")}} The **`lang`** property of the {{domxref("SpeechSynthesisUtterance")}} interface gets and sets the language of the utterance. If unset, the app's (i.e. the {{htmlelement("html")}} [`lang`](/en-US/docs/Web/HTML/Element/html#lang) value) lang will be used, or the user-agent default if that is unset too. ## Value A string representing a BCP 47 language tag. ## Examples ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); const voices = synth.getVoices(); // ... inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); for (let i = 0; i < voices.length; i++) { if (voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } utterThis.lang = "en-US"; synth.speak(utterThis); inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/start_event/index.md
--- title: "SpeechSynthesisUtterance: start event" short-title: start slug: Web/API/SpeechSynthesisUtterance/start_event page-type: web-api-event browser-compat: api.SpeechSynthesisUtterance.start_event --- {{APIRef("Web Speech API")}} The **`start`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechSynthesisUtterance")}} object is fired when the utterance has begun to be spoken. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("start", (event) => {}); onstart = (event) => {}; ``` ## Event type A {{domxref("SpeechSynthesisEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechSynthesisEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechSynthesisEvent.charIndex", "charIndex")}} {{ReadOnlyInline}} - : Returns the index position of the character in the {{domxref("SpeechSynthesisUtterance.text")}} that was being spoken when the event was triggered. - {{domxref("SpeechSynthesisEvent.elapsedTime", "elapsedTime")}} {{ReadOnlyInline}} - : Returns the elapsed time in seconds after the {{domxref("SpeechSynthesisUtterance.text")}} started being spoken that the event was triggered at. - {{domxref("SpeechSynthesisEvent.name", "name")}} {{ReadOnlyInline}} - : Returns the name associated with certain types of events occurring as the {{domxref("SpeechSynthesisUtterance.text")}} is being spoken: the name of the [SSML](https://www.w3.org/TR/speech-synthesis/#S3.3.2) marker reached in the case of a {{domxref("SpeechSynthesisUtterance.mark_event", "mark")}} event, or the type of boundary reached in the case of a {{domxref("SpeechSynthesisUtterance.boundary_event", "boundary")}} event. - {{domxref("SpeechSynthesisEvent.utterance", "utterance")}} {{ReadOnlyInline}} - : Returns the {{domxref("SpeechSynthesisUtterance")}} instance that the event was triggered on. ## Examples You can use the `start` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js utterThis.addEventListener("start", (event) => { console.log(`We have started uttering this speech: ${event.utterance.text}`); }); ``` Or use the `onstart` event handler property: ```js utterThis.onstart = (event) => { console.log(`We have started uttering this speech: ${event.utterance.text}`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/mark_event/index.md
--- title: "SpeechSynthesisUtterance: mark event" short-title: mark slug: Web/API/SpeechSynthesisUtterance/mark_event page-type: web-api-event browser-compat: api.SpeechSynthesisUtterance.mark_event --- {{APIRef("Web Speech API")}} The **`mark`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechSynthesisUtterance")}} object is fired when the spoken utterance reaches a named SSML "mark" tag. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("mark", (event) => {}); onmark = (event) => {}; ``` ## Event type A {{domxref("SpeechSynthesisEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechSynthesisEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechSynthesisEvent.charIndex", "charIndex")}} {{ReadOnlyInline}} - : Returns the index position of the character in the {{domxref("SpeechSynthesisUtterance.text")}} that was being spoken when the event was triggered. - {{domxref("SpeechSynthesisEvent.elapsedTime", "elapsedTime")}} {{ReadOnlyInline}} - : Returns the elapsed time in seconds after the {{domxref("SpeechSynthesisUtterance.text")}} started being spoken that the event was triggered at. - {{domxref("SpeechSynthesisEvent.name", "name")}} {{ReadOnlyInline}} - : Returns the name associated with certain types of events occurring as the {{domxref("SpeechSynthesisUtterance.text")}} is being spoken: the name of the [SSML](https://www.w3.org/TR/speech-synthesis/#S3.3.2) marker reached in the case of a {{domxref("SpeechSynthesisUtterance.mark_event", "mark")}} event, or the type of boundary reached in the case of a {{domxref("SpeechSynthesisUtterance.boundary_event", "boundary")}} event. - {{domxref("SpeechSynthesisEvent.utterance", "utterance")}} {{ReadOnlyInline}} - : Returns the {{domxref("SpeechSynthesisUtterance")}} instance that the event was triggered on. ## Examples You can use the `mark` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js utterThis.addEventListener("mark", (event) => { console.log(`A mark was reached: ${event.name}`); }); ``` Or use the `onmark` event handler property: ```js utterThis.onmark = (event) => { console.log(`A mark was reached: ${event.name}`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/rate/index.md
--- title: "SpeechSynthesisUtterance: rate property" short-title: rate slug: Web/API/SpeechSynthesisUtterance/rate page-type: web-api-instance-property browser-compat: api.SpeechSynthesisUtterance.rate --- {{APIRef("Web Speech API")}} The **`rate`** property of the {{domxref("SpeechSynthesisUtterance")}} interface gets and sets the speed at which the utterance will be spoken at. If unset, a default value of 1 will be used. ## Value A float representing the rate value. It can range between 0.1 (lowest) and 10 (highest), with 1 being the default rate for the current platform or voice, which should correspond to a normal speaking rate. Other values act as a percentage relative to this, so for example 2 is twice as fast, 0.5 is half as fast, etc. Some speech synthesis engines or voices may constrain the minimum and maximum rates further. If [SSML](https://www.w3.org/TR/speech-synthesis/) is used, this value will be overridden by [prosody tags](https://www.w3.org/TR/speech-synthesis/#S3.2.4) in the markup. ## Examples ### Adjusting playback rate In this example we can adjust the playback rate using the slider, then play the utterance with the "Play" button. #### HTML ```html <p id="text">It was a dark and stormy night.</p> <div id="rate-control"> <label for="rate">Rate:</label> <input type="range" min="0.5" max="2" value="1" step="0.1" id="rate" /> </div> <button id="play">Play</button> ``` #### CSS ```css body { font-family: sans-serif; } #rate-control { display: flex; align-items: center; gap: 1rem; margin: 1rem 0; } ``` #### JavaScript ```js const synth = window.speechSynthesis; const text = document.querySelector("#text"); const play = document.querySelector("#play"); const rate = document.querySelector("#rate"); function speak() { if (synth.speaking) { synth.cancel(); } const utterThis = new SpeechSynthesisUtterance(text.textContent); utterThis.addEventListener("error", () => { console.error("SpeechSynthesisUtterance error"); }); utterThis.rate = rate.value; synth.speak(utterThis); } play.addEventListener("click", speak); ``` #### Output {{EmbedLiveSample("Adjusting playback rate")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/boundary_event/index.md
--- title: "SpeechSynthesisUtterance: boundary event" short-title: boundary slug: Web/API/SpeechSynthesisUtterance/boundary_event page-type: web-api-event browser-compat: api.SpeechSynthesisUtterance.boundary_event --- {{APIRef("Web Speech API")}} The **`boundary`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) is fired when the spoken utterance reaches a word or sentence boundary. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("boundary", (event) => {}); onboundary = (event) => {}; ``` ## Event type A {{domxref("SpeechSynthesisEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechSynthesisEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechSynthesisEvent.charIndex", "charIndex")}} {{ReadOnlyInline}} - : Returns the index position of the character in the {{domxref("SpeechSynthesisUtterance.text")}} that was being spoken when the event was triggered. - {{domxref("SpeechSynthesisEvent.elapsedTime", "elapsedTime")}} {{ReadOnlyInline}} - : Returns the elapsed time in seconds after the {{domxref("SpeechSynthesisUtterance.text")}} started being spoken that the event was triggered at. - {{domxref("SpeechSynthesisEvent.name", "name")}} {{ReadOnlyInline}} - : Returns the name associated with certain types of events occurring as the {{domxref("SpeechSynthesisUtterance.text")}} is being spoken: the name of the [SSML](https://www.w3.org/TR/speech-synthesis/#S3.3.2) marker reached in the case of a {{domxref("SpeechSynthesisUtterance.mark_event", "mark")}} event, or the type of boundary reached in the case of a {{domxref("SpeechSynthesisUtterance.boundary_event", "boundary")}} event. - {{domxref("SpeechSynthesisEvent.utterance", "utterance")}} {{ReadOnlyInline}} - : Returns the {{domxref("SpeechSynthesisUtterance")}} instance that the event was triggered on. ## Examples You can use the `boundary` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js utterThis.addEventListener("boundary", (event) => { console.log( `${event.name} boundary reached after ${event.elapsedTime} seconds.`, ); }); ``` Or use the `onboundary` event handler property: ```js utterThis.onboundary = (event) => { console.log( `${event.name} boundary reached after ${event.elapsedTime} seconds.`, ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/pitch/index.md
--- title: "SpeechSynthesisUtterance: pitch property" short-title: pitch slug: Web/API/SpeechSynthesisUtterance/pitch page-type: web-api-instance-property browser-compat: api.SpeechSynthesisUtterance.pitch --- {{APIRef("Web Speech API")}} The **`pitch`** property of the {{domxref("SpeechSynthesisUtterance")}} interface gets and sets the pitch at which the utterance will be spoken at. If unset, a default value of 1 will be used. ## Value A float representing the pitch value. It can range between 0 (lowest) and 2 (highest), with 1 being the default pitch for the current platform or voice. Some speech synthesis engines or voices may constrain the minimum and maximum rates further. If [SSML](https://www.w3.org/TR/speech-synthesis/) is used, this value will be overridden by [prosody tags](https://www.w3.org/TR/speech-synthesis/#S3.2.4) in the markup. ## Examples ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); const voices = synth.getVoices(); // ... inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); for (let i = 0; i < voices.length; i++) { if (voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } utterThis.pitch = 1.5; synth.speak(utterThis); inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/end_event/index.md
--- title: "SpeechSynthesisUtterance: end event" short-title: end slug: Web/API/SpeechSynthesisUtterance/end_event page-type: web-api-event browser-compat: api.SpeechSynthesisUtterance.end_event --- {{APIRef("Web Speech API")}} The **`end`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechSynthesisUtterance")}} object is fired when the utterance has finished being spoken. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("end", (event) => {}); onend = (event) => {}; ``` ## Event type A {{domxref("SpeechSynthesisEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("SpeechSynthesisEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechSynthesisEvent.charIndex", "charIndex")}} {{ReadOnlyInline}} - : Returns the index position of the character in the {{domxref("SpeechSynthesisUtterance.text")}} that was being spoken when the event was triggered. - {{domxref("SpeechSynthesisEvent.elapsedTime", "elapsedTime")}} {{ReadOnlyInline}} - : Returns the elapsed time in seconds after the {{domxref("SpeechSynthesisUtterance.text")}} started being spoken that the event was triggered at. - {{domxref("SpeechSynthesisEvent.name", "name")}} {{ReadOnlyInline}} - : Returns the name associated with certain types of events occurring as the {{domxref("SpeechSynthesisUtterance.text")}} is being spoken: the name of the [SSML](https://www.w3.org/TR/speech-synthesis/#S3.3.2) marker reached in the case of a {{domxref("SpeechSynthesisUtterance.mark_event", "mark")}} event, or the type of boundary reached in the case of a {{domxref("SpeechSynthesisUtterance.boundary_event", "boundary")}} event. - {{domxref("SpeechSynthesisEvent.utterance", "utterance")}} {{ReadOnlyInline}} - : Returns the {{domxref("SpeechSynthesisUtterance")}} instance that the event was triggered on. ## Examples You can use the `end` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js utterThis.addEventListener("end", (event) => { console.log( `Utterance has finished being spoken after ${event.elapsedTime} seconds.`, ); }); ``` Or use the `onend` event handler property: ```js utterThis.onend = (event) => { console.log( `Utterance has finished being spoken after ${event.elapsedTime} seconds.`, ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesisutterance
data/mdn-content/files/en-us/web/api/speechsynthesisutterance/error_event/index.md
--- title: "SpeechSynthesisUtterance: error event" short-title: error slug: Web/API/SpeechSynthesisUtterance/error_event page-type: web-api-event browser-compat: api.SpeechSynthesisUtterance.error_event --- {{APIRef("Web Speech API")}} The **`error`** event of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) {{domxref("SpeechSynthesisUtterance")}} object is fired when an error occurs that prevents the utterance from being successfully spoken. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("error", (event) => {}); onerror = (event) => {}; ``` ## Event type A {{domxref("SpeechSynthesisErrorEvent")}}. Inherits from {{domxref("SpeechSynthesisEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("SpeechSynthesisErrorEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("SpeechSynthesisEvent.charIndex", "charIndex")}} {{ReadOnlyInline}} - : Returns the index position of the character in the {{domxref("SpeechSynthesisUtterance.text")}} that was being spoken when the event was triggered. - {{domxref("SpeechSynthesisEvent.elapsedTime", "elapsedTime")}} {{ReadOnlyInline}} - : Returns the elapsed time in seconds after the {{domxref("SpeechSynthesisUtterance.text")}} started being spoken that the event was triggered at. - {{domxref("SpeechSynthesisErrorEvent.error", "error")}} {{ReadOnlyInline}} - : Returns an error code indicating what has gone wrong with a speech synthesis attempt. - {{domxref("SpeechSynthesisEvent.name", "name")}} {{ReadOnlyInline}} - : Returns the name associated with certain types of events occurring as the {{domxref("SpeechSynthesisUtterance.text")}} is being spoken: the name of the [SSML](https://www.w3.org/TR/speech-synthesis/#S3.3.2) marker reached in the case of a {{domxref("SpeechSynthesisUtterance.mark_event", "mark")}} event, or the type of boundary reached in the case of a {{domxref("SpeechSynthesisUtterance.boundary_event", "boundary")}} event. - {{domxref("SpeechSynthesisEvent.utterance", "utterance")}} {{ReadOnlyInline}} - : Returns the {{domxref("SpeechSynthesisUtterance")}} instance that the event was triggered on. ## Examples You can use the `error` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js utterThis.addEventListener("error", (event) => { console.log( `An error has occurred with the speech synthesis: ${event.error}`, ); }); ``` Or use the `onerror` event handler property: ```js utterThis.onerror = (event) => { console.log( `An error has occurred with the speech synthesis: ${event.error}`, ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svggradientelement/index.md
--- title: SVGGradientElement slug: Web/API/SVGGradientElement page-type: web-api-interface browser-compat: api.SVGGradientElement --- {{APIRef("SVG")}} The **`SVGGradient`** interface is a base interface used by {{domxref("SVGLinearGradientElement")}} and {{domxref("SVGRadialGradientElement")}}. {{InheritanceDiagram}} ## Constants <table class="no-markdown"> <tbody> <tr> <th>Name</th> <th>Value</th> <th>Description</th> </tr> <tr> <td><code>SVG_SPREADMETHOD_UNKNOWN</code></td> <td>0</td> <td> The type is not one of predefined types. It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. </td> </tr> <tr> <td><code>SVG_SPREADMETHOD_PAD</code></td> <td>1</td> <td>Corresponds to value <em>pad</em>.</td> </tr> <tr> <td><code>SVG_SPREADMETHOD_REFLECT</code></td> <td>2</td> <td>Corresponds to value <em>reflect</em>.</td> </tr> <tr> <td><code>SVG_SPREADMETHOD_REPEAT</code></td> <td>3</td> <td>Corresponds to value <em>repeat</em>.</td> </tr> </tbody> </table> ## Instance properties _This interface also inherits properties from its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGGradientElement.href")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("href")}} or {{SVGAttr("xlink:href")}} {{deprecated_inline}} attribute of the given element. - {{domxref("SVGGradientElement.gradientUnits")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("gradientUnits")}} attribute on the given element. This property takes one of the constants defined in {{domxref("SVGUnitTypes")}}. - {{domxref("SVGGradientElement.gradientTransform")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedTransformList")}} corresponding to the {{SVGAttr("gradientTransform")}} attribute on the given element. - {{domxref("SVGGradientElement.spreadMethod")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("spreadMethod")}} attribute on the given element. One of the spread method types defined on this interface. ## Instance methods _This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/launchparams/index.md
--- title: LaunchParams slug: Web/API/LaunchParams page-type: web-api-interface status: - experimental browser-compat: api.LaunchParams --- {{APIRef("Launch Handler API")}}{{SeeCompatTable}} The **`LaunchParams`** interface of the {{domxref("Launch Handler API", "Launch Handler API", "", "nocode")}} is used when implementing custom launch navigation handling in a PWA. When {{domxref("LaunchQueue.setConsumer", "window.launchQueue.setConsumer()")}} is invoked to set up the launch navigation handling functionality, the callback function inside `setConsumer()` is passed a `LaunchParams` object instance. Such custom navigation handling is initiated via {{domxref("Window.launchQueue")}} when a PWA has been launched with a [`launch_handler`](/en-US/docs/Web/Manifest/launch_handler) `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`. {{InheritanceDiagram}} ## Instance properties - {{domxref("LaunchParams.files")}} {{ReadOnlyInline}}{{Experimental_Inline}} - : Returns a read-only array of {{domxref("FileSystemHandle")}} objects representing any files passed along with the launch navigation via the [`POST`](/en-US/docs/Web/HTTP/Methods/POST) method. - {{domxref("LaunchParams.targetURL")}} {{ReadOnlyInline}}{{Experimental_Inline}} - : Returns the target URL of the launch. ## Examples ```js if ("launchQueue" in window) { window.launchQueue.setConsumer((launchParams) => { if (launchParams.targetURL) { const params = new URL(launchParams.targetURL).searchParams; // Assuming a music player app that gets a track passed to it to be played const track = params.get("track"); if (track) { audio.src = track; title.textContent = new URL(track).pathname.substr(1); audio.play(); } } }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/) - {{domxref("Window.launchQueue")}} - [Musicr 2.0](https://launch-handler.glitch.me/) demo app
0
data/mdn-content/files/en-us/web/api/launchparams
data/mdn-content/files/en-us/web/api/launchparams/files/index.md
--- title: "LaunchParams: files property" short-title: files slug: Web/API/LaunchParams/files page-type: web-api-instance-property status: - experimental browser-compat: api.LaunchParams.files --- {{APIRef("Launch Handler API")}}{{SeeCompatTable}} The **`files`** read-only property of the {{domxref("LaunchParams")}} interface returns an array of {{domxref("FileSystemHandle")}} objects representing any files passed along with the launch navigation via the [`POST`](/en-US/docs/Web/HTTP/Methods/POST) method. ## Value A read-only array of {{domxref("FileSystemHandle")}} objects. ## Examples ```js if ("launchQueue" in window) { window.launchQueue.setConsumer((launchParams) => { if (launchParams.files) { const files = launchParams.files; for (file in files) { // Do stuff with file handles } } }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/) - {{domxref("Window.launchQueue")}} - [Musicr 2.0](https://launch-handler.glitch.me/) demo app
0
data/mdn-content/files/en-us/web/api/launchparams
data/mdn-content/files/en-us/web/api/launchparams/targeturl/index.md
--- title: "LaunchParams: targetURL property" short-title: targetURL slug: Web/API/LaunchParams/targetURL page-type: web-api-instance-property status: - experimental browser-compat: api.LaunchParams.targetURL --- {{APIRef("Launch Handler API")}}{{SeeCompatTable}} The **`targetURL`** read-only property of the {{domxref("LaunchParams")}} interface returns the target URL of the associated web app launch. ## Value A string. ## Examples ```js if ("launchQueue" in window) { window.launchQueue.setConsumer((launchParams) => { if (launchParams.targetURL) { const params = new URL(launchParams.targetURL).searchParams; // Assuming a music player app that gets a track passed to it to be played const track = params.get("track"); if (track) { audio.src = track; title.textContent = new URL(track).pathname.substr(1); audio.play(); } } }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/) - {{domxref("Window.launchQueue")}} - [Musicr 2.0](https://launch-handler.glitch.me/) demo app
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/textformatupdateevent/index.md
--- title: TextFormatUpdateEvent slug: Web/API/TextFormatUpdateEvent page-type: web-api-interface status: - experimental browser-compat: api.TextFormatUpdateEvent --- {{APIRef("EditContext API")}}{{SeeCompatTable}} The **`TextFormatUpdateEvent`** interface is a {{domxref("Event","DOM event")}} that represents a list of text formats that an {{glossary("Input Method Editor")}} (IME) window wants to apply to the text being composed in an editable region that's attached to an {{domxref("EditContext")}} instance. This interface inherits properties from {{domxref("Event")}}. {{InheritanceDiagram}} ## Constructor - {{domxref("TextFormatUpdateEvent.TextFormatUpdateEvent", "TextFormatUpdateEvent()")}} {{experimental_inline}} - : Creates a new `TextFormatUpdateEvent` object. ## Instance methods - {{domxref('TextFormatUpdateEvent.getTextFormats')}} {{experimental_inline}} - : Returns an {{jsxref("Array")}} of {{domxref("TextFormat")}} objects that represent the formats that the IME window wants to apply to the text. ## Examples ### Styling IME-composed text In the following example, the `textformatupdate` event is used to update the formatting of the text in the editable region. ```html <canvas id="editor-canvas"></canvas> ``` ```js const TEXT_X = 10; const TEXT_Y = 10; const canvas = document.getElementById("editor-canvas"); const ctx = canvas.getContext("2d"); const editContext = new EditContext(); canvas.editContext = editContext; editContext.addEventListener("textformatupdate", (e) => { // Clear the canvas. ctx.clearRect(0, 0, canvas.width, canvas.height); // Render the text. ctx.fillText(editContext.text, TEXT_X, TEXT_Y); console.log(`Rendering text: ${editContext.text}`); // Get the text formats that the IME window wants to apply. const formats = e.getTextFormats(); // Iterate over the text formats for (const format of formats) { const { rangeStart, rangeEnd, underlineStyle, underlineThickness } = format; console.log( `Applying underline ${underlineThickness} ${underlineStyle} between ${rangeStart} and ${rangeEnd}.`, ); const underlineXStart = ctx.measureText( editContext.text.substring(0, rangeStart), ).width; const underlineXEnd = ctx.measureText( editContext.text.substring(0, rangeEnd), ).width; const underlineY = TEXT_Y + 3; // For brevity, this example only draws a simple underline. // Use underlineStyle and underlineThickness to draw the correct underline. ctx.beginPath(); ctx.moveTo(TEXT_X + underlineXStart, underlineY); ctx.lineTo(TEXT_X + underlineXEnd, underlineY); ctx.stroke(); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/textformatupdateevent
data/mdn-content/files/en-us/web/api/textformatupdateevent/textformatupdateevent/index.md
--- title: "TextFormatUpdateEvent: TextFormatUpdateEvent() constructor" short-title: TextFormatUpdateEvent() slug: Web/API/TextFormatUpdateEvent/TextFormatUpdateEvent page-type: web-api-constructor status: - experimental browser-compat: api.TextFormatUpdateEvent.TextFormatUpdateEvent --- {{APIRef("TextFormatUpdateEvent API")}}{{SeeCompatTable}} The **`TextFormatUpdateEvent()`** constructor returns a new {{DOMxRef("TextFormatUpdateEvent")}} object. ## Syntax ```js-nolint new TextFormatUpdateEvent(type) new TextFormatUpdateEvent(type, options) ``` ### Parameters - `type` - : A string representing the type of the event. Possible values: `"textformatupdate"`. - `options` {{optional_inline}} - : An optional object with the following properties: - `textFormats` - : An {{jsxref("Array")}} of {{domxref("TextFormat")}} objects representing the text formats that need to be applied with this event. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{DOMxRef("TextFormatUpdateEvent")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api/textformatupdateevent
data/mdn-content/files/en-us/web/api/textformatupdateevent/gettextformats/index.md
--- title: "TextFormatUpdateEvent: getTextFormats() method" short-title: getTextFormats() slug: Web/API/TextFormatUpdateEvent/getTextFormats page-type: web-api-instance-method status: - experimental browser-compat: api.TextFormatUpdateEvent.getTextFormats --- {{APIRef("EditContext API")}}{{SeeCompatTable}} The **`getTextFormats()`** method of the {{domxref("TextFormatUpdateEvent")}} interface returns an {{jsxref("Array")}} of {{domxref("TextFormat")}} objects that represent the formats that an {{glossary("Input Method Editor")}} (IME) window wants to apply to the text being composed. ## Syntax ```js-nolint getTextFormats() ``` ### Return value An {{jsxref("Array")}} containing {{domxref("TextFormat")}} objects. ## Examples ### Styling IME-composed text In the following example, the `textformatupdate` event is used to update the formatting of the text in the editable region. ```html <canvas id="editor-canvas"></canvas> ``` ```js const TEXT_X = 10; const TEXT_Y = 10; const canvas = document.getElementById("editor-canvas"); const ctx = canvas.getContext("2d"); const editContext = new EditContext(); canvas.editContext = editContext; editContext.addEventListener("textformatupdate", (e) => { // Clear the canvas. ctx.clearRect(0, 0, canvas.width, canvas.height); // Render the text. ctx.fillText(editContext.text, TEXT_X, TEXT_Y); console.log(`Rendering text: ${editContext.text}`); // Get the text formats that the IME window wants to apply. const formats = e.getTextFormats(); // Iterate over the text formats for (const format of formats) { const { rangeStart, rangeEnd, underlineStyle, underlineThickness } = format; console.log( `Applying underline ${underlineThickness} ${underlineStyle} between ${rangeStart} and ${rangeEnd}.`, ); const underlineXStart = ctx.measureText( editContext.text.substring(0, rangeStart), ).width; const underlineXEnd = ctx.measureText( editContext.text.substring(0, rangeEnd), ).width; const underlineY = TEXT_Y + 3; // For brevity, this example only draws a simple underline. // Use underlineStyle and underlineThickness to draw the correct underline. ctx.beginPath(); ctx.moveTo(TEXT_X + underlineXStart, underlineY); ctx.lineTo(TEXT_X + underlineXEnd, underlineY); ctx.stroke(); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlulistelement/index.md
--- title: HTMLUListElement slug: Web/API/HTMLUListElement page-type: web-api-interface browser-compat: api.HTMLUListElement --- {{ APIRef("HTML DOM") }} The **`HTMLUListElement`** interface provides special properties (beyond those defined on the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating unordered list ({{HTMLElement("ul")}}) elements. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLUListElement.type")}} {{deprecated_inline}} - : A string value reflecting the [`type`](/en-US/docs/Web/HTML/Element/ul#type) and defining the kind of marker to be used to display. The values are browser dependent and have never been standardized. - {{domxref("HTMLUListElement.compact")}} {{deprecated_inline}} - : A boolean value indicating that spacing between list items should be reduced. This property reflects the [`compact`](/en-US/docs/Web/HTML/Element/ul#compact) attribute only, it doesn't consider the {{cssxref("line-height")}} CSS property used for that behavior in modern pages. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("ul") }}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgellipseelement/index.md
--- title: SVGEllipseElement slug: Web/API/SVGEllipseElement page-type: web-api-interface browser-compat: api.SVGEllipseElement --- {{APIRef("SVG")}} The **`SVGEllipseElement`** interface provides access to the properties of {{SVGElement("ellipse")}} elements. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGGeometryElement")}}._ - {{domxref("SVGEllipseElement.cx")}} {{ReadOnlyInline}} - : This property returns a {{domxref("SVGAnimatedLength")}} reflecting the {{SVGAttr("cx")}} attribute of the given {{SVGElement("ellipse")}} element. - {{domxref("SVGEllipseElement.cy")}} {{ReadOnlyInline}} - : This property returns a {{domxref("SVGAnimatedLength")}} reflecting the {{SVGAttr("cy")}} attribute of the given {{SVGElement("ellipse")}} element. - {{domxref("SVGEllipseElement.rx")}} {{ReadOnlyInline}} - : This property returns a {{domxref("SVGAnimatedLength")}} reflecting the {{SVGAttr("rx")}} attribute of the given {{SVGElement("ellipse")}} element. - {{domxref("SVGEllipseElement.ry")}} {{ReadOnlyInline}} - : This property returns a {{domxref("SVGAnimatedLength")}} reflecting the {{SVGAttr("ry")}} attribute of the given {{SVGElement("ellipse")}} element. ## Instance methods _This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGGeometryElement")}}._ ## Example ### SVG ```html <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <ellipse cx="100" cy="100" rx="100" ry="60" id="ellipse" onclick="outputSize();" /> </svg> ``` ### JavaScript ```js function outputSize() { const ellipse = document.getElementById("ellipse"); // Outputs "horizontal radius: 100 vertical radius: 60" console.log( `horizontal radius: ${ellipse.rx.baseVal.valueAsString}`, `vertical radius: ${ellipse.ry.baseVal.valueAsString}`, ); } ``` ### Result {{EmbedLiveSample("Example", 220, 220)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("ellipse")}} SVG Element
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/webotp_api/index.md
--- title: WebOTP API slug: Web/API/WebOTP_API page-type: web-api-overview spec-urls: https://wicg.github.io/web-otp/ --- {{securecontext_header}}{{DefaultAPISidebar("WebOTP API")}} The **WebOTP API** provides a streamlined user experience for web apps to verify that a phone number belongs to a user when using it as a sign-in factor. WebOTP is an extension of the [Credential Management API](/en-US/docs/Web/API/Credential_Management_API). The verification is done via a two-step process: 1. The app client requests a one-time password (OTP), which is obtained from a specially-formatted SMS message sent by the app server. 2. JavaScript is used to enter the OTP into a validation form on the app client and it is submitted back to the server to verify that it matches what was originally sent in the SMS. ## WebOTP concepts and usage Phone numbers are often used as a way to identify the user of an app. An SMS is frequently deployed to verify that the number belongs to the user. The SMS typically contains an OTP that the user is required to copy and paste into a form in the app to verify that they own the number. This is a somewhat clunky user experience. OTP use cases include: - Improving sign-in security by using a phone number as an extra factor (i.e. for two-factor authentication (2FA) or multifactor authentication (MFA)). - Verifying sensitive actions such as payments. The WebOTP API allows web apps to expedite this validation process by copying the OTP from the SMS and passing it to the app automatically after the user has provided consent (most native platforms have an equivalent API). Note that an OTP is bound to the sending domain. This is a useful security constraint for verifying that the OTP is coming from the right source, which can mitigate the risk of phishing attacks during day-to-day reauthentication. ### Security concerns with SMS OTPs SMS OTPs are useful for verifying phone numbers, and using SMS for a second factor is certainly better than having no second factor. In some regions, other identifiers such as email addresses and authenticators are not widely-used, so SMS OTPs are very common. However, SMSes aren't that secure. Attackers can spoof an SMS and hijack a person's phone number. Carriers can recycle phone numbers to new users after an account is closed. You are, therefore, recommended to use a stronger form of authentication if possible, such as a [Web Authentication API](/en-US/docs/Web/API/Web_Authentication_API)-based solution involving a password and security key or a passkey. ## How does the WebOTP API work? The process works like so: 1. At the point where phone number verification is required, an app client will ask a user to enter their phone number into a form, which is then submitted to the app server. 2. The app client then invokes {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} with an `otp` option specifying a `transport` type of `"sms"`. This triggers a request for an OTP from the underlying system, the source of which will be a [specially-formatted SMS message](#the_sms_message_format) (containing the OTP and the app's domain) received from the app server. The `get()` call is {{jsxref("Promise")}}-based and waits for the SMS message to be received. 3. The app server sends the SMS message to the specified phone number. This must be done just after Step 2 has occurred. 4. When the SMS is received on the device, provided it contains the app's domain, the browser will ask the user if they consent to the OTP being retrieved/used. Chrome, for example, displays a dialog asking them for their permission to retrieve the OTP from the SMS; other browsers may handle it differently. If they do consent, the `get()` call will fulfill with an {{domxref("OTPCredential")}} object containing the OTP. 5. You can then use the OTP in any way you wish. Typical usage would be to set it as the value of the validation form on the app client and then submit the form, making the process as seamless as possible. 6. The app server will then verify that the OTP sent back to it matches what it originally sent in the SMS and, if so, complete the process (for example, sign the user in). ### SMS message format A typical SMS message looks like so: ```plain Your verification code is 123456. @www.example.com #123456 ``` - The first line and second blank line are optional and are for human readability. - The last line is mandatory. It must be the last line if there are others present, and must consist of: - The domain part of the URL of the website that invoked the API, preceded by a `@`. - Followed by a space. - Followed by the OTP, preceded by a pound sign (`#`). > **Note:** The provided domain value must not include a URL schema, port, or other URL features not shown above. If the `get()` method is invoked by a third-party site embedded in an {{htmlelement("iframe")}}, the SMS structure should be: ```plain Your verification code is 123456. @top-level.example.com #123456 @embedded.com ``` In this case, the last line must consist of: - The domain part of the top-level domain, preceded by a `@`. - Followed by a space. - Followed by the OTP, preceded by a pound sign (`#`). - Followed by a space. - Followed by the domain part of the embedded domain, preceded by a `@`. ## Controlling access to the API The availability of WebOTP can be controlled using a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) specifying a {{httpheader("Permissions-Policy/otp-credentials", "otp-credentials")}} directive. This directive has a default allowlist value of `"self"`, meaning that by default, these methods can be used in top-level document contexts. You could specify a directive allowing the use of WebOTP in a specific cross-origin domain (i.e., inside an {{htmlelement("iframe")}}) like this: ```http Permissions-Policy: otp-credentials=(self "https://embedded.com") ``` Or you could specify it directly on the `<iframe>` like this: ```html <iframe src="https://embedded.com/..." allow="otp-credentials"> ... </iframe> ``` > **Note:** Where a policy forbids use of WebOTP `get()`, {{jsxref("Promise", "promises")}} returned by it will reject with a `SecurityError` {{domxref("DOMException")}}. ## Interfaces - {{domxref("OTPCredential")}} - : Returned when a WebOTP `get()` call fulfills; includes a `code` property that contains the retrieved OTP. ## Extensions to other interfaces - {{domxref("CredentialsContainer.get()")}}, the `otp` option - : Calling `get()` with an `otp` option instructs the user agent to attempt to retrieve an OTP from the underlying system's SMS app. ## Examples In this example, when an SMS message arrives and the user grants permission, an {{domxref("OTPCredential")}} object is returned with an OTP. This password is then prefilled into the verification form field, and the form is submitted. [Try this demo using a phone](https://web-otp.glitch.me/). The form field includes an [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete) attribute with the value of `one-time-code`. This is not needed for the WebOTP API to work, but it is worth including. As a result, Safari will prompt the user to autofill this field with the OTP when a correctly-formatted SMS is received, even though the WebOTP API isn't fully supported in Safari. ```html <input type="text" autocomplete="one-time-code" inputmode="numeric" /> ``` The JavaScript is as follows: ```js // Detect feature support via OTPCredential availability if ("OTPCredential" in window) { window.addEventListener("DOMContentLoaded", (e) => { const input = document.querySelector('input[autocomplete="one-time-code"]'); if (!input) return; // Set up an AbortController to use with the OTP request const ac = new AbortController(); const form = input.closest("form"); if (form) { // Abort the OTP request if the user attempts to submit the form manually form.addEventListener("submit", (e) => { ac.abort(); }); } // Request the OTP via get() navigator.credentials .get({ otp: { transport: ["sms"] }, signal: ac.signal, }) .then((otp) => { // When the OTP is received by the app client, enter it into the form // input and submit the form automatically input.value = otp.code; if (form) form.submit(); }) .catch((err) => { console.error(err); }); }); } ``` Another good use for the {{domxref("AbortController")}} is to cancel the `get()` request after a certain amount of time: ```js setTimeout(() => { // abort after 30 seconds ac.abort(); }, 30 * 1000); ``` If the user becomes distracted or navigates somewhere else, it is good to cancel the request so that they don't get presented with a permission prompt that is no longer relevant to them. ## Specifications {{Specifications}} ## See also - [Verify phone numbers on the web with WebOTP](https://developer.chrome.com/docs/identity/web-apis/web-otp) on developer.chrome.com (2023) - [Fill OTP forms within cross-origin iframes with WebOTP API](https://web.dev/articles/web-otp-iframe)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/screen/index.md
--- title: Screen slug: Web/API/Screen page-type: web-api-interface browser-compat: api.Screen --- {{APIRef("CSSOM")}} The `Screen` interface represents a screen, usually the one on which the current window is being rendered, and is obtained using {{DOMxRef("window.screen")}}. Note that browsers determine which screen to report as current by detecting which screen has the center of the browser window. {{InheritanceDiagram}} ## Instance properties _Also inherits properties from its parent {{domxref("EventTarget")}}_. - {{DOMxRef("Screen.availHeight")}} - : Specifies the height of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows. - {{DOMxRef("Screen.availWidth")}} - : Returns the amount of horizontal space in pixels available to the window. - {{DOMxRef("Screen.colorDepth")}} - : Returns the color depth of the screen. - {{DOMxRef("Screen.height")}} - : Returns the height of the screen in pixels. - {{domxref("Screen.isExtended")}} {{experimental_inline}} {{securecontext_inline}} - : Returns `true` if the user's device has multiple screens, and `false` if not. - {{DOMxRef("Screen.orientation")}} - : Returns the {{DOMxRef("ScreenOrientation")}} instance associated with this screen. - {{DOMxRef("Screen.pixelDepth")}} - : Gets the bit depth of the screen. - {{DOMxRef("Screen.width")}} - : Returns the width of the screen. - {{DOMxRef("Screen.mozEnabled")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Boolean. Setting to false will turn off the device's screen. - {{DOMxRef("Screen.mozBrightness")}} {{Non-standard_Inline}} {{Deprecated_Inline}} - : Controls the brightness of a device's screen. A double between 0 and 1.0 is expected. ## Non-standard properties The following properties are specified as part of the [Window Management API](/en-US/docs/Web/API/Window_Management_API), which makes them available on the {{domxref("ScreenDetailed")}} interface; this is where we have chosen to document them. However, non-standard versions of these properties are available on the `Screen` interface in browsers that don't support that API. See this page's [Browser compatibility](#browser_compatibility) table for details of the non-standard support. - {{domxref("ScreenDetailed.availLeft", "Screen.availLeft")}} {{ReadOnlyInline}} {{Non-standard_Inline}} - : A number representing the x-coordinate (left-hand edge) of the available screen area. - {{domxref("ScreenDetailed.availTop", "Screen.availTop")}} {{ReadOnlyInline}} {{Non-standard_Inline}} - : A number representing the y-coordinate (top edge) of the available screen area. - {{domxref("ScreenDetailed.left", "Screen.left")}} {{ReadOnlyInline}} {{Non-standard_Inline}} - : A number representing the x-coordinate (left-hand edge) of the total screen area. - {{domxref("ScreenDetailed.top", "Screen.top")}} {{ReadOnlyInline}} {{Non-standard_Inline}} {{deprecated_inline}} - : A number representing the y-coordinate (top edge) of the total screen area. ## Instance methods _Also inherits methods from its parent {{domxref("EventTarget")}}_. - {{DOMxRef("Screen.lockOrientation")}} {{Deprecated_Inline}} - : Lock the screen orientation (only works in fullscreen or for installed apps) - {{DOMxRef("Screen.unlockOrientation")}} {{Deprecated_Inline}} - : Unlock the screen orientation (only works in fullscreen or for installed apps) ## Events - {{domxref("Screen.change_event", "change")}} {{experimental_inline}} {{securecontext_inline}} - : Fired on a specific screen when it changes in some way — width or height, available width or height, color depth, or orientation. - {{DOMxRef("Screen.orientationchange_event", "orientationchange")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Fires when the screen orientation changes. ## Examples ```js if (screen.colorDepth < 8) { // use low-color version of page } else { // use regular, colorful page } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/colordepth/index.md
--- title: "Screen: colorDepth property" short-title: colorDepth slug: Web/API/Screen/colorDepth page-type: web-api-instance-property browser-compat: api.Screen.colorDepth --- {{APIRef("CSSOM")}} The **`Screen.colorDepth`** read-only property returns the color depth of the screen. Per the CSSOM, some implementations return `24` for compatibility reasons. See the browser compatibility section for those that don't. ## Value A number. ## Examples ```js // Check the color depth of the screen if (window.screen.colorDepth < 8) { // Use low-color version of page } else { // Use regular, colorful page } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("Screen.pixelDepth")}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/mozenabled/index.md
--- title: "Screen: mozEnabled property" short-title: mozEnabled slug: Web/API/Screen/mozEnabled page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.Screen.mozEnabled --- {{APIRef("CSSOM")}}{{Deprecated_Header}}{{Non-standard_Header}} This Boolean attribute controls the device's screen. Setting it to `false` will turn off the screen. ## Value A boolean. ## Specifications Not part of specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/orientationchange_event/index.md
--- title: "Screen: orientationchange event" short-title: orientationchange slug: Web/API/Screen/orientationchange_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.Screen.orientationchange_event --- {{APIRef("Screen Orientation API")}}{{Deprecated_Header}}{{Non-standard_Header}} The `orientationchange` event fires when the device's orientation has changed. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("orientationchange", (event) => {}); onorientationchange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Specifications This feature is not part of any specification. It is no longer on track to becoming a standard. Use the {{domxref("ScreenOrientation.change_event", "ScreenOrientation change event")}} instead. ## Browser compatibility {{Compat}} ## See also - [Managing screen orientation](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation)
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/orientation/index.md
--- title: "Screen: orientation property" short-title: orientation slug: Web/API/Screen/orientation page-type: web-api-instance-property browser-compat: api.Screen.orientation --- {{APIRef("Screen Orientation API")}} The **`orientation`** read-only property of the {{DOMxRef("Screen")}} interface returns the current orientation of the screen. ## Value An instance of {{DOMxRef("ScreenOrientation")}} representing the orientation of the screen. Note that older, prefixed versions returned a string equivalent to {{DOMxRef("ScreenOrientation.type")}}. ## Examples ```js switch (screen.orientation.type) { case "landscape-primary": console.log("That looks good."); break; case "landscape-secondary": console.log("Mmmh… the screen is upside down!"); break; case "portrait-secondary": case "portrait-primary": console.log("Mmmh… you should rotate your device to landscape"); break; default: console.log("The orientation API isn't supported in this browser :("); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("ScreenOrientation")}} - {{DOMxRef("Screen.orientationchange_event", "orientationchange")}} event - [Managing screen orientation](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation)
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/availwidth/index.md
--- title: "Screen: availWidth property" short-title: availWidth slug: Web/API/Screen/availWidth page-type: web-api-instance-property browser-compat: api.Screen.availWidth --- {{APIRef("CSSOM View")}} The **`Screen.availWidth`** property returns the amount of horizontal space (in pixels) available to the window. ## Value A number. ## Examples ```js const screenAvailWidth = window.screen.availWidth; console.log(screenAvailWidth); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/unlockorientation/index.md
--- title: "Screen: unlockOrientation() method" short-title: unlockOrientation() slug: Web/API/Screen/unlockOrientation page-type: web-api-instance-method status: - deprecated browser-compat: api.Screen.unlockOrientation --- {{APIRef("Screen Orientation API")}}{{Deprecated_Header}} The **`Screen.unlockOrientation()`** method removes all the previous screen locks set by the page/app. The {{DOMxRef("ScreenOrientation.unlock()")}} method should be used instead. > **Warning:** This feature is deprecated and should be avoided. Use the {{DOMxRef("ScreenOrientation.unlock()")}} method instead. > **Note:** This method only works for installed Web apps or for Web pages > in [fullscreen mode](/en-US/docs/Web/API/Fullscreen_API). ## Syntax ```js-nolint unlockOrientation() ``` ### Parameters None. ### Return value Returns `true` if the orientation was successfully unlocked or `false` if the orientation couldn't be unlocked. ## Examples ```js const unlockOrientation = screen.unlockOrientation || screen.mozUnlockOrientation || screen.msUnlockOrientation || (screen.orientation && screen.orientation.unlock); if (unlockOrientation()) { // orientation was unlocked } else { // orientation unlock failed } ``` ## Specifications This feature is not part of any specification. It is no longer on track to becoming a standard. Use {{domxref("ScreenOrientation.unlock()")}} instead. ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("Screen.orientation")}} - {{DOMxRef("Screen.lockOrientation()")}} - {{DOMxRef("Screen.orientationchange_event", "orientationchange")}} event - [Managing screen orientation](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation)
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/availheight/index.md
--- title: "Screen: availHeight property" short-title: availHeight slug: Web/API/Screen/availHeight page-type: web-api-instance-property browser-compat: api.Screen.availHeight --- {{APIRef("CSSOM")}} The read-only {{DOMxRef("Screen")}} interface's **`availHeight`** property returns the height, in CSS pixels, of the space available for Web content on the screen. Since {{DOMxRef("Screen")}} is exposed on the {{DOMxRef("Window")}} interface's {{DOMxRef("Window.screen", "window.screen")}} property, you access `availHeight` using `window.screen.availHeight`. You can similarly use {{DOMxRef("Screen.availWidth")}} to get the number of pixels which are horizontally available to the browser for its use. ## Value A numeric value indicating the number of CSS pixels tall the screen's available space is. This can be no larger than the value of {{DOMxRef("Screen.height", "window.screen.height")}}, and will be less if the device or user agent reserves any vertical space for itself. For instance, on a Mac whose Dock is located at the bottom of screen (which is the default), the value of `availHeight` is approximately the value of `height` (the total height of the screen in CSS pixels) minus the heights of the Dock and menu bar, as seen in the diagram below. [![Diagram showing how Screen.availHeight relates to Screen.height and the screen's contents](availheight-diagram.svg)](availheight-diagram.svg) ## Examples If your web application needs to open a new window, such as a tool palette which can contain multiple panels, and wants to position it so that it occupies the entire vertical space available, you can do so using code similar to what's seen here. In the main window, when it's time to open the panels, code like the following is used. ```js const paletteWindow = window.open( "panels.html", "Panels", "left=0, top=0, width=200", ); ``` The Panels window's HTML, in `panels.html`, has JavaScript code of its own, which is executed as soon as the window is created. It doesn't even need to wait for any particular event (or any event at all). That code handles resizing the window based on the available space: ```js window.outerHeight = window.screen.availHeight; ``` The result is something similar to the below. Note the Panels window filling all available vertical space at the left of the screen. [![Screenshot of the example for Screen.availHeight](screen-availheight.png)](screen-availheight.png) On a Windows system, this would function similarly, by opening the window and sizing it vertically so it uses all available vertical space, leaving room for the taskbar and any other interface elements that reserve space. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("Window")}} - {{DOMxRef("Screen")}} - {{DOMxRef("Screen.availWidth")}} - {{DOMxRef("Window.innerHeight")}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/availheight/availheight-diagram.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="69.5 -163.3 640 400" width="640pt" height="400pt"><defs><marker orient="auto" overflow="visible" markerUnits="strokeWidth" id="a" viewBox="-1 -4 10 8" markerWidth="10" markerHeight="8" color="#000"><path d="M8 0 0-3v6z" fill="currentColor" stroke="currentColor"/></marker><marker orient="auto" overflow="visible" markerUnits="strokeWidth" id="b" viewBox="-9 -4 10 8" markerWidth="10" markerHeight="8" color="#000"><path d="m-8 0 8 3v-6z" fill="currentColor" stroke="currentColor"/></marker></defs><g fill="none"><path fill="#fff" d="M0 0h640v400H0z"/><path fill="#dfdfff" d="M69.5-163.3h640v400h-640z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M69.5-163.3h640v400h-640z"/><path fill="#fff" d="M69.5-163.3h640v19.875h-640z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M69.5-163.3h640v19.875h-640z"/><text transform="translate(74.5 -161.559)" fill="#000"> <tspan font-family="Helvetica Neue" font-size="14" font-weight="500" x="0" y="13" textLength="38.542">  Firefox File Edit View History Bookmarks Tools Window Help</tspan> </text><path fill="#d6d5d7" fill-opacity=".75" d="M289.5 176.7h190v60h-190z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M289.5 176.7h190v60h-190z"/><path marker-end="url(#a)" marker-start="url(#b)" stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M519.5-153.4v380.2m-140-360.2v300.2"/><text transform="translate(534.5 21.7)" fill="#000"> <tspan font-family="Courier" font-size="16" font-weight="500" x="0" y="15" textLength="57.609">height</tspan> </text><text transform="translate(264.5 21.7)" fill="#000"> <tspan font-family="Courier" font-size="16" font-weight="500" x=".383" y="15" textLength="105.617">availHeight</tspan> </text><circle cx="329.5" cy="206.7" r="20" fill="#00f"/><circle cx="329.5" cy="206.7" r="20" stroke="#000" stroke-linejoin="round"/><circle cx="379.5" cy="206.7" r="20" fill="#ff8080"/><circle cx="379.5" cy="206.7" r="20" stroke="#000" stroke-linejoin="round"/><circle cx="439.5" cy="206.7" r="20" fill="#666"/><circle cx="439.5" cy="206.7" r="20" stroke="#000" stroke-linejoin="round"/></g></svg>
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/isextended/index.md
--- title: "Screen: isExtended property" short-title: isExtended slug: Web/API/Screen/isExtended page-type: web-api-instance-property status: - experimental browser-compat: api.Screen.isExtended --- {{APIRef("Window Management API")}}{{SeeCompatTable}}{{securecontext_header}} The **`isExtended`** read-only property of the {{domxref("Screen")}} interface returns `true` if the user's device has multiple screens, and `false` if not. This property is typically accessed via `window.screen.isExtended`, and can be used to test whether multiple screens are available before attempting to create a multi-window, multi-screen layout using the [Window Management API](/en-US/docs/Web/API/Window_Management_API). ## Value A boolean value — `true` if the device has multiple screens, and `false` if not. > **Note:** If a {{httpheader("Permissions-Policy/window-management", "window-management")}} [Permissions-Policy](/en-US/docs/Web/HTTP/Permissions_Policy) is set that blocks use the Window Management API, `isExtended` will always return `false`. ## Examples ```js if (window.screen.isExtended) { // Create multi-screen window layout } else { // Create single-screen window layout } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Window Management API](/en-US/docs/Web/API/Window_Management_API)
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/mozbrightness/index.md
--- title: "Screen: mozBrightness property" short-title: mozBrightness slug: Web/API/Screen/mozBrightness page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.Screen.mozBrightness --- {{APIRef("CSSOM")}}{{Deprecated_Header}}{{Non-standard_Header}} Indicates how bright the screen's backlight is, on a scale from 0 (very dim) to 1 (full brightness); this value is a double-precision float. You can read and write this attribute even when the screen is disabled, but the backlight is off while the screen is disabled. If you write a value of X into this attribute, the attribute may not have the same value X when you later read it. Most screens don't support as many different brightness levels as there are doubles between 0 and 1. The value's precision might be reduced before storing it. ## Value A number. ## Specifications Not part of specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/width/index.md
--- title: "Screen: width property" short-title: width slug: Web/API/Screen/width page-type: web-api-instance-property browser-compat: api.Screen.width --- {{APIRef("CSSOM")}} The **`Screen.width`** read-only property returns the width of the screen in CSS pixels. ## Value A number. ## Examples ```js // Crude way to check that the screen is at least 1024x768 if (window.screen.width >= 1024 && window.screen.height >= 768) { // Resolution is 1024x768 or above } ``` ## Notes Note that not all of the width given by this property may be available to the window itself. When other widgets occupy space that cannot be used by the `window` object, there is a difference in `window.screen.width` and `window.screen.availWidth`. See also {{DOMxRef("screen.height")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/change_event/index.md
--- title: "Screen: change event" short-title: change slug: Web/API/Screen/change_event page-type: web-api-event status: - experimental browser-compat: api.Screen.change_event --- {{APIRef("Window Management API")}}{{SeeCompatTable}}{{securecontext_header}} The **`change`** event of the {{domxref("Screen")}} interface is fired on a specific screen when one or more of the following properties change on it: - {{domxref("Screen.width", "width")}} - {{domxref("Screen.height", "height")}} - {{domxref("Screen.availWidth", "availWidth")}} - {{domxref("Screen.availHeight", "availHeight")}} - {{domxref("Screen.colorDepth", "colorDepth")}} - {{domxref("Screen.orientation", "orientation")}} ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("change", (event) => {}); onchange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js const firstScreen = (await window.getScreenDetails()).screens[0]; firstScreen.addEventListener("change", (event) => { console.log("The first screen has changed.", event, firstScreen); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Window Management API](/en-US/docs/Web/API/Window_Management_API)
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/height/index.md
--- title: "Screen: height property" short-title: height slug: Web/API/Screen/height page-type: web-api-instance-property browser-compat: api.Screen.height --- {{APIRef("CSSOM")}} The **`Screen.height`** read-only property returns the height of the screen in pixels. ## Value A number. ## Examples ```js if (window.screen.availHeight !== window.screen.height) { // Something is occupying some screen real estate! } ``` ## Notes Note that not all of the height given by this property may be available to the window itself. Widgets such as taskbars or other special application windows that integrate with the OS (e.g., the Spinner player minimized to act like an additional toolbar on windows) may reduce the amount of space available to browser windows and other applications. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/pixeldepth/index.md
--- title: "Screen: pixelDepth property" short-title: pixelDepth slug: Web/API/Screen/pixelDepth page-type: web-api-instance-property browser-compat: api.Screen.pixelDepth --- {{APIRef("CSSOM")}} Returns the bit depth of the screen. Per the CSSOM, some implementations return `24` for compatibility reasons. See the [browser compatibility](#browser_compatibility) section for those that don't. ## Value A number. ## Examples ```js // if there is not adequate bit depth // choose a simpler color document.style.color = window.screen.pixelDepth > 8 ? "#FAEBD7" : "#FFFFFF"; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("Screen.colorDepth")}}
0
data/mdn-content/files/en-us/web/api/screen
data/mdn-content/files/en-us/web/api/screen/lockorientation/index.md
--- title: "Screen: lockOrientation() method" short-title: lockOrientation() slug: Web/API/Screen/lockOrientation page-type: web-api-instance-method status: - deprecated browser-compat: api.Screen.lockOrientation --- {{APIRef("Screen Orientation API")}}{{Deprecated_Header}} The **`lockOrientation()`** method of the {{DOMxRef("Screen")}} interface locks the screen into a specified orientation. > **Warning:** This feature is deprecated and should be avoided. Use the {{DOMxRef("ScreenOrientation.lock()")}} method instead. > **Note:** This method only works for installed Web apps or for Web pages > in [fullscreen mode](/en-US/docs/Web/API/Fullscreen_API). ## Syntax ```js-nolint lockOrientation(orientation) ``` ### Parameters - `orientation` - : The orientation into which to lock the screen. This is either a string or an array of strings. Passing several strings lets the screen rotate only in the selected orientations. The following strings represent the possible orientation requirements you may specify: - `portrait-primary` - : It represents the orientation of the screen when it is in its primary portrait mode. A screen is considered in its primary portrait mode if the device is held in its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held turned by 90° clockwise. The normal position is device dependent. - `portrait-secondary` - : It represents the orientation of the screen when it is in its secondary portrait mode. A screen is considered in its secondary portrait mode if the device is held 180° from its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held is turned by 90° counterclockwise. The normal position is device dependent. - `landscape-primary` - : It represents the orientation of the screen when it is in its primary landscape mode. A screen is considered in its primary landscape mode if the device is held in its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° clockwise. The normal position is device dependent. - `landscape-secondary` - : It represents the orientation of the screen when it is in its secondary landscape mode. A screen is considered in its secondary landscape mode if the device held is 180° from its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° counterclockwise. The normal position is device dependent. - `portrait` - : It represents both `portrait-primary` and `portrait-secondary`. - `landscape` - : It represents both `landscape-primary` and `landscape-secondary`. - `default` - : It represents either `portrait-primary` and `landscape-primary` depends on natural orientation of devices. For example, if the panel resolution is 1280\*800, `default` will make it landscape, if the resolution is 800\*1280, `default` will make it to portrait. > **Note:** It's possible to set several locks at the same time. So, if > the lock is set for only one orientation, the screen orientation will never change > until the screen orientation is unlocked. Otherwise, the screen orientation will > change from an orientation to another as long as the orientations are amongst the > orientations the device has been locked to. ### Return value Returns `true` if the orientation was authorized to be locked or `false` if the orientation locking was denied. Note that the return value doesn't indicate that the screen orientation is indeed locked: there may be a delay. ## Examples ### Usage with a string argument ```js screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation; if (screen.lockOrientationUniversal("landscape-primary")) { // Orientation was locked } else { // Orientation lock failed } ``` ### Usage with an `Array` argument ```js screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation; if ( screen.lockOrientationUniversal(["landscape-primary", "landscape-secondary"]) ) { // Orientation was locked } else { // Orientation lock failed } ``` ## Specifications This feature is not part of any specification. It is no longer on track to becoming a standard. Use {{domxref("ScreenOrientation.lock()")}} instead. ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("Screen.orientation")}} - {{DOMxRef("Screen.unlockOrientation()")}} - {{DOMxRef("Screen.orientationchange_event", "orientationchange")}} event - [Managing screen orientation](/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/webgl_compressed_texture_s3tc/index.md
--- title: WEBGL_compressed_texture_s3tc extension short-title: WEBGL_compressed_texture_s3tc slug: Web/API/WEBGL_compressed_texture_s3tc page-type: webgl-extension browser-compat: api.WEBGL_compressed_texture_s3tc --- {{APIRef("WebGL")}} The **`WEBGL_compressed_texture_s3tc`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and exposes four [S3TC compressed texture formats](https://en.wikipedia.org/wiki/S3_Texture_Compression). Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial). > **Note:** This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts. ## Constants The compressed texture formats are exposed by four constants and can be used in two functions: {{domxref("WebGLRenderingContext.compressedTexImage2D", "compressedTexImage2D()")}} and {{domxref("WebGLRenderingContext.compressedTexSubImage2D", "compressedTexSubImage2D()")}}. - `ext.COMPRESSED_RGB_S3TC_DXT1_EXT` - : A DXT1-compressed image in an RGB image format. - `ext.COMPRESSED_RGBA_S3TC_DXT1_EXT` - : A DXT1-compressed image in an RGB image format with a simple on/off alpha value. - `ext.COMPRESSED_RGBA_S3TC_DXT3_EXT` - : A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression. - `ext.COMPRESSED_RGBA_S3TC_DXT5_EXT` - : A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done. ## Examples ```js const ext = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D( gl.TEXTURE_2D, 0, ext.COMPRESSED_RGBA_S3TC_DXT5_EXT, 512, 512, 0, textureData, ); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [S3 Texture Compression – OpenGL wiki](https://www.khronos.org/opengl/wiki/S3_Texture_Compression) - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("WebGLRenderingContext.compressedTexImage2D()")}} - {{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}} - {{domxref("WebGLRenderingContext.getParameter()")}}
0