We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

Worker interface의 메서드, postMessage()Worker 자신의 내부 영역으로 메시지를 전달합니다. 이 메서드는 Worker 자신에게 보낼 하나의 매개변수를 받습니다. 매개변수로 들어갈 데이터는 순환 참조를 포함하는 structured clone algorithm에 의해 다루어지는 JavaScript 객체를 포함에 어떤 값이든 들어갈 수 있습니다.

 Worker는 정보를 다시 DedicatedWorkerGlobalScope.postMessage 메서드를 사용해 받은 정보를 산란시키는 스레드로 전달해줄 수 있다.


myWorker.postMessage(aMessage, transferList);


worker로 전해 줄 객체;  이 매개변수는 DedicatedWorkerGlobalScope.onmessage 이벤트 핸들러로 전해질 이벤트의 데이터 필드에 들어갈 것이다. 순환 참조를 포함하는 structured clone 알고리즘에 의해 다루어지는 JavaScript 객체 혹은 어떤 값이라도 이 매개변수에 들어갈 수 있다.
transferList Optional
An optional array of Transferable objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to.
Transferable objects are instances of classes like ArrayBuffer, MessagePort or ImageBitmap objects can be transferred. null is not an acceptable value for the transferList.




The following code snippet shows the creation of a Worker object using the Worker() constructor. When either of two form inputs (first and second) have their values changed, change events invoke postMessage() to send the value of both inputs to the current worker.

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

first.onchange = function() {
  console.log('Message posted to worker');

second.onchange = function() {
  console.log('Message posted to worker');

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

Note: postMessage() can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.

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':
            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);

        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':
            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


Specification Status Comment
HTML Living Standard
The definition of 'Worker.postMessage()' in that specification.
Living Standard  

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!

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support (Yes) (Yes) (Yes) 10.0 [1] (Yes) (Yes)
Feature Android Edge Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) 10.0 [1] (Yes) (Yes)

[1] Internet Explorer does not support Transferable objects.

See also

  • The Worker interface it belongs to.

문서 태그 및 공헌자

이 페이지의 공헌자: TaeYoon2
최종 변경: TaeYoon2,