大网数据广告活动
Web 标准与前端开发

DedicatedWorkerGlobalScope: message event

· 52CE 我爱测

The `message` event is fired on a DedicatedWorkerGlobalScope object when the worker receives a message from its parent (i.e., when the parent sends a message using `Worker.postMessage()`).

Web Workers APIdedicated

The message event is fired on a DedicatedWorkerGlobalScope object when the worker receives a message from its parent (i.e., when the parent sends a message using Worker.postMessage()).

This event is not cancellable and does not bubble.

Syntax

Use the event name in EventTarget/addEventListener:

addEventListener("message", (event) => { })

Alternatively, assign to the event handler property of the interface:

onmessage = (event) => { }

Event type

A MessageEvent. Inherits from Event.

MessageEvent

Example

The following code snippet shows creation of a Worker object using the Worker.Worker constructor. Messages are passed to the worker when the value inside the form input first changes. An Worker.message_event handler is also present, to deal with messages are passed back from the worker.

// main.js

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

first.onchange = () => {
  myWorker.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

myWorker.onmessage = (e) => {
  result.textContent = e.data;
  console.log("Message received from worker");
};

The worker assigns an onmessage handler to its global scope (but note that this replaces other event listeners added using onmessage, if any):

// worker.js

self.onmessage = (e) => {
  console.log("Message received from main script");
  const workerResult = `Result: ${e.data[0] * e.data[1]}`;
  console.log("Posting message back to main script");
  postMessage(workerResult);
};

Alternatively, the worker script can listen for the message using addEventListener():

// worker.js

self.addEventListener("message", (e) => {
  console.log("Message received from main script");
  const workerResult = `Result: ${e.data[0] * e.data[1]}`;
  console.log("Posting message back to main script");
  postMessage(workerResult);
});

Notice how in the main script, onmessage has to be defined on myWorker, whereas inside the worker script you just need onmessage because the worker is effectively the global scope (DedicatedWorkerGlobalScope).

For a full example, see our Basic dedicated worker example (run dedicated worker).

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。