Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. SharedWorker

SharedWorker

Limited availability

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

TheSharedWorker interface represents a specific kind of worker that can beaccessed from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope,SharedWorkerGlobalScope.

Note:If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port).

EventTarget SharedWorker

Constructors

SharedWorker()

Creates a shared web worker that executes the script at the specified URL.

Instance properties

Inherits properties from its parent,EventTarget.

SharedWorker.portRead only

Returns aMessagePort object used to communicate with and control the shared worker.

Events

error

Fires when an error occurs in the shared worker.

Instance methods

Inherits methods from its parent,EventTarget.

Example

In ourBasic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.

The following code snippet shows creation of aSharedWorker object using theSharedWorker() constructor. Both scripts contain this:

js
const myWorker = new SharedWorker("worker.js");

Note:Once a shared worker is created, any script running in the same origin can obtain a reference to that worker and communicate with it. The shared worker will be alive as long as its global scope's owner set (a set ofDocument andWorkerGlobalScope objects) is not empty (for example, if there is any live page holding a reference to it, maybe throughnew SharedWorker()). To read more about shared worker lifetime, seeThe worker's lifetime section of the HTML specification.

Both scripts then access the worker through aMessagePort object created using theSharedWorker.port property. If the onmessage event is attached using addEventListener, the port is manually started using itsstart() method:

js
myWorker.port.start();

When the port is started, both scripts post messages to the worker and handle messages sent from it usingport.postMessage() andport.onmessage, respectively:

Note:You can use browser devtools to debug your SharedWorker, by entering a URL in your browser address bar to access the devtools workers inspector; for example, in Chrome, the URLchrome://inspect/#workers, and in Firefox, the URLabout:debugging#workers.

js
[first, second].forEach((input) => {  input.onchange = () => {    myWorker.port.postMessage([first.value, second.value]);    console.log("Message posted to worker");  };});myWorker.port.onmessage = (e) => {  result1.textContent = e.data;  console.log("Message received from worker");};

Inside the worker we use theonconnect handler to connect to the same port discussed above. The ports associated with that worker are accessible in theconnect event'sports property — we then useMessagePortstart() method to start the port, and theonmessage handler to deal with messages sent from the main threads.

js
onconnect = (e) => {  const port = e.ports[0];  port.addEventListener("message", (e) => {    const workerResult = `Result: ${e.data[0] * e.data[1]}`;    port.postMessage(workerResult);  });  port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.};

Specifications

Specification
HTML
# shared-workers-and-the-sharedworker-interface

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp