Search code examples
javascriptpostmessageworker

how to: ´postMessage´ can it send two messages?


is it possible to send two messages with 1 postMessage() from a worker.js? and us the two messages in two different places.

etc

w.onmessage = function (event) {
document.getElementById(event.message 1 here).innerHTML=event.message 2 here;
};

Solution

  • Actually postMessage can post not only String, but any Object, e.g.

     myWorker.postMessage({
         m1: 'msg1',
         m2: 'msg2'
     });
    

    And in your worker:

     onmessage = function (event) {
         //will be msg1
         console.log(event.data.m1);
    
         //will be msg2
         console.log(event.data.m2);
     };