Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

Web Workers API posse un metodo llamado postMessage() el cual envia un mensaje al ambito del worker. Este metodo acepta un parametro, el cual es un dato enviado al worker. El dato puede ser un valor o objeto controlado por el algoritmo strctured clone (incluye referencias ciclicas).

El Worker puede enviar de vuelta información al hilo que lo genero usando el metodo DedicatedWorkerGlobalScope.postMessage.


myWorker.postMessage(aMessage, transferList);


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 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 it becomes available only to the worker it was sent to.
Only MessagePort and ArrayBuffer objects can be transferred.




The following code snippet shows 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 is of a Firefox addon that transfers an ArrayBuffer from the main thread to the ChromeWorker, and then the ChromeWorker trasnfers 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 ( {
        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);'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
);'arrBuf.byteLength post transfer:', arrBuf.byteLength);

Worker code

self.onmessage = function (msg) {
    switch ( {
        case 'do_sendWorkerArrBuff':
            throw 'no aTopic on incoming message to ChromeWorker';

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

    self.postMessage({aTopic:'do_sendMainArrBuff', aBuf:aBuf}, [aBuf]);'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

We see that byteLength goes to 0 as it is trasnferred. To see a fully working example of this Firefox demo addon see here: GitHub :: ChromeWorker - demo-transfer-arraybuffer


Specification Status Comment
WHATWG HTML Living Standard
The definition of 'Worker.postMessage()' in that specification.
Living Standard No change from Web Workers.
Web Workers
The definition of 'Worker.postMessage()' in that specification.
Candidate Recommendation Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support (Yes) (Yes) 10.0 [1] (Yes) (Yes)
Feature Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari 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.

Etiquetas y colaboradores del documento

 Colaboradores en esta página: mar777
 Última actualización por: mar777,