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.
My guess is that you will need to create an own
onmessage
property on each worker instance for this to work:However, don't expect this to work in every browser. Some might create the
.onmessage
property on construction of the Worker and initialise it withnull
- your setter would never be called.