Search code examples
javascriptweb-workerpostmessageemscripten

Process message from Webworker created by unreachable code


I'm really new with JavaScript, I'm sorry if the answer is obvious.

I want to send a message to the main thread from a web-worker. I don't have any access to the part of the code who create the worker so I can't just add worker.onmessage = [...]. I have access to the JavaScript code that is executed at the begining of my process, but not the one who create the workers.

I was wondering if there's a way to do something like window.onEveryMessageFromAnyWorker = doSomeMagic()

Thanks a lot!


Solution

  • No, that's not possible. You need the handle to the web worker in order to listen for its messages. Make sure you really can't change the code that makes the worker, if you you can't read below:

    Hacky solution

    If you're writing userscript or other "hacky" code, I suggest you override the worker constructor:

    // Execute this before the worker is being created
    window.OldWorker = Worker;
    window.Worker = function(path) {
        console.log("Worker created: ", path);
        // The original worker is applied on this object
        return new OldWorker(path);
    }
    

    Note that this is nasty piece of code. It might break things.

    Once you have this code, you can access the worker that is created:

    window.Worker = function(path) {
        console.log("Worker created: ", path);
        var worker = new OldWorker(path);
        if(path == "something.js") {
            // do something
            worker.addEventListener("message", (e)=>{console.log("Message:", e.data});
        }
        // The original worker is applied on this object
        return worker;
    }
    

    Note that you must use worker.addEventListener. Setting .onmessage can cause your callback to be overridden, since there can be only one callback in the onmessage property.