4

How do I create the code for a web worker using Scala.js? Looking at the documentation everything seems to produce JavaScript functions rather than top level JavaScript. The new Worker constructor seems to require top level Javascript, rather than a function within a file. So in my Scala.js code I have:

var myWorker = new Worker("worker.js");
myWorker.onmessage = (e: scala.scalajs.js.Any) =>
{
  val e1 = e.asInstanceOf[MessageEvent]
  println("Worker message recieved:" -- e1.data.toString)
}
myWorker.postMessage("")

And in the file worker.js I have

self.postMessage("from webworker");

The message is picked up and displayed in the web console as intended.

1 Answer 1

5

Scala.js will indeed only ever generate non-top-level code, by design. However, you can add a bit of arbitrary JavaScript code at the beginning and/or end of the generated .js file with the scalaJSOutputWrapper sbt setting:

scalaJSOutputWrapper := ("", "example.WorkerMainObject().main();")

This would cause the generated .js file to have the specified top-level statement.

See also https://stackoverflow.com/a/34764513/1829647

Sign up to request clarification or add additional context in comments.

3 Comments

The scalaJSOutputWrapper is gone since scala-js.org/news/2017/07/03/announcing-scalajs-1.0.0-M1. Can one do the same with scalaJSLinkerConfig?
You don't need that anymore. You can have an actual main method since v0.6.18 or something.
It may sound dumb, but I still fail to understand how exactly. You mean something like in stackoverflow.com/questions/35926650/… (which was asked and answered about the same time as this)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.