How to modify onmesage property in Web Worker in real-time?

218 Views Asked by At

I'm trying to modify onmessage property of Web Worker to create a wrapper around user defined onmessage function in real time.

I've tried by using defineProperty on Worker prototype.

page.js

<script>

Object.defineProperty(Worker.prototype, 'onmessage', {  
    set: function(f) {      
                        Worker.prototype.__onmessage__ = function(e) {
                            console.log('wrapper');                             
                            f(e);
                        }
                     },


    get: function() { return Worker.prototype.__onmessage__; }  
}); 


var w = new Worker("worker.js");

w.onmessage = function(e) {  // defineProperty.set is invoked on assignment
  console.log(e.data + ' from worker');
}

console.log(w.onmessage);  // displays function Worker.__onmessage__(e)

w.postMessage('hello');    // start worker; w.onmesage is never invoked

</script>

worker.js

onmessage = function(e) {        
  postMessage(e.data);  
}

Worker onmesage callback is never invoked. Tried in FF and Chrome.

1

There are 1 best solutions below

0
On

My guess is that you will need to create an own onmessage property on each worker instance for this to work:

Object.defineProperty(Worker.prototype, "onmessage", {
    set: function(f) {
        Object.defineProperty(this, "onmessage", {
            value: function(e) {
                console.log('wrapper:', e);
                return f.apply(this, arguments);
            },
            writable: true,
            configurable: true
        });
    },
    configurable: true
});

However, don't expect this to work in every browser. Some might create the .onmessage property on construction of the Worker and initialise it with null - your setter would never be called.