Search code examples
scalaweb-workerscala.js

In Scala.js, how can code detect whether it is running in a browser window or a WebWorker?


From plain JavaScript, we can test for features directly; see: Reliably detect if the script is executing in a web worker.

How would you accomplish this from Scala.js?


Solution

  • As Justin du Coeur already commented, because ScalaJS compiles down to JavaScript, there is nothing you can do in JavaScript that you couldn't do in ScalaJS.

    So you will find that the code looks oddly similar to the one you have linked:

    import org.scalajs.dom
    
    if(js.typeOf(dom.document) == "undefined") {
      println("I'm fairly confident I'm a webworker")
    } else {
      println("I'm fairly confident I'm in the renderer thread")
    }
    

    Try it out!


    I hope this helps.