Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create webworker code in Scala.js

Tags:

scala.js

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.

like image 285
Rich Oliver Avatar asked Sep 20 '25 14:09

Rich Oliver


1 Answers

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

like image 139
sjrd Avatar answered Sep 22 '25 14:09

sjrd