Worker.postMessage() - Web API 接口参考 编辑

Worker 接口的 postMessage()方法向worker的内部作用域发送一个消息。这接受单个参数,这是要发送给worker的数据。数据可以是由结构化克隆算法处理的任何值或JavaScript对象,其包括循环引用。

工作者可以使用 DedicatedWorkerGlobalScope.postMessage  方法将信息发送回生成它的线程。

语法

myWorker.postMessage(aMessage, transferList);

参数

aMessage
The object to deliver to the worker; this will be in the data field in the event delivered to the DedicatedWorkerGlobalScope.onmessage handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
transferList 可选
一个可选的Transferable对象的数组,用于传递所有权。如果一个对象的所有权被转移,在发送它的上下文中将变为不可用(中止),并且只有在它被发送到的worker中可用。
可转移对象是如ArrayBufferMessagePortImageBitmap的实例对象。transferList数组中不可传入null。

Returns

Void.

Example

以下代码显示了如何使用 Worker() 构造函数创建一个Worker对象。当两个表单输入(firstsecond)中的其中一个的输入值改变时, change 事件将调用postMessage()把两个input的值发送给当前worker。

var myWorker = new Worker('worker.js');

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

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

有关完整的示例,请参阅我们的Basic dedicated worker example (run dedicated worker).

Note: postMessage() 一次只能发送一个对象。如上所示,如果你想传递多个值,可以使用数组。

Transfer Example

This example shows a Firefox add-on that transfers an ArrayBuffer from the main thread to the ChromeWorker, and then the ChromeWorker transfers it back to the main thread.

Main thread code:

var myWorker = new ChromeWorker(self.path + 'myWorker.js');

function handleMessageFromWorker(msg) {
    console.log('incoming message from worker, msg:', msg);
    switch (msg.data.aTopic) {
        case 'do_sendMainArrBuff':
            sendMainArrBuff(msg.data.aBuf)
            break;
        default:
            throw 'no aTopic on incoming message to ChromeWorker';
    }
}

myWorker.addEventListener('message', handleMessageFromWorker);

// Ok lets create the buffer and send it
var arrBuf = new ArrayBuffer(8);
console.info('arrBuf.byteLength pre transfer:', arrBuf.byteLength);

myWorker.postMessage(
    {
        aTopic: 'do_sendWorkerArrBuff',
        aBuf: arrBuf // The array buffer that we passed to the transferrable section 3 lines below
    },
    [
        arrBuf // The array buffer we created 9 lines above
    ]
);

console.info('arrBuf.byteLength post transfer:', arrBuf.byteLength);

Worker code

self.onmessage = function (msg) {
    switch (msg.data.aTopic) {
        case 'do_sendWorkerArrBuff':
                sendWorkerArrBuff(msg.data.aBuf)
            break;
        default:
            throw 'no aTopic on incoming message to ChromeWorker';
    }
}

function sendWorkerArrBuff(aBuf) {
    console.info('from worker, PRE send back aBuf.byteLength:', aBuf.byteLength);

    self.postMessage({aTopic:'do_sendMainArrBuff', aBuf:aBuf}, [aBuf]);

    console.info('from worker, POST send back aBuf.byteLength:', aBuf.byteLength);
}

Output logged

arrBuf.byteLength pre transfer: 8                              bootstrap.js:40
arrBuf.byteLength post transfer: 0                             bootstrap.js:42

from worker, PRE send back aBuf.byteLength: 8                  myWorker.js:5:2

incoming message from worker, msg: message { ... }             bootstrap.js:20
got back buf in main thread, aBuf.byteLength: 8                bootstrap.js:12

from worker, POST send back aBuf.byteLength: 0                 myWorker.js:7:2

byteLength goes to 0 as it is transferred. To see a full working example of this Firefox demo add-on see here: GitHub :: ChromeWorker - demo-transfer-arraybuffer

Specifications

SpecificationStatusComment
HTML Living Standard
Worker.postMessage()
Living StandardNo change from Unknown.
Unknown
Worker.postMessage()
UnknownInitial definition.

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support(Yes)(Yes)10.0 [1](Yes)(Yes)
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support(Yes)(Yes)(Yes)10.0 [1](Yes)(Yes)

[1] Internet Explorer does not support Transferable objects.

See also

  • The Worker interface it belongs to.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:42 次

字数:10562

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文