Worker.postMessage()

Deze vertaling is niet volledig. Help dit artikel te vertalen vanuit het Engels.

The postMessage() method of the Worker interface sends a message to the worker's inner scope. This accepts a single parameter, which is the data to send to the worker. The data may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.

The Worker can send back information to the thread that spawned it using the DedicatedWorkerGlobalScope.postMessage method.

Syntax

myWorker.postMessage(aMessage, transferList);

Parameters

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 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.

Returns

Void.

Example

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() {
  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');
}

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.

Specifications

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.

Documentlabels en -medewerkers

Labels: 
 Aan deze pagina hebben bijgedragen: vivi-anne
 Laatst bijgewerkt door: vivi-anne,