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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With