Reliably detect if the script is executing in a web worker

thomas picture thomas · Oct 28, 2011 · Viewed 12.1k times · Source

I am currently writing a little library in JavaScript to help me delegate to a web-worker some heavy computation .

For some reasons (mainly for the ability to debug in the UI thread and then run the same code in a worker) I'd like to detect if the script is currently running in a worker or in the UI thread.

I'm not a seasoned JavaScript developper and I would like to ensure that the following function will reliably detect if I'm in a worker or not :

function testenv() {
    try{
        if (importScripts) {
            postMessage("I think I'm in a worker actually.");
        }
    } catch (e) {
        if (e instanceof ReferenceError) {
            console.log("I'm the UI thread.");
        } else {
            throw e;
        }
    }
}

So, does it ?

Answer

borbulon picture borbulon · Aug 1, 2013

Quite late to the game on this one, but here's the best, most bulletproofy way I could come up with:

// run this in global scope of window or worker. since window.self = window, we're ok
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
    // huzzah! a worker!
} else {
    // I'm a window... sad trombone.
}