Calling Javascript from Scala.js
I am using Page.scala
Scala.js to run the client side of my application. Thus, it Page.scala
replaces index.html. The Scalatags feature raw
allows you to enable actual JavaScript. In the Scalatags documentation, the example is a warning ("Hello!"). I actually have a bit of JavaScript that defines what the browser is, but says "Hello!" good for a start. JavaScript itself is a get_browser_info()
function here .
So my question is, can I call this little JavaScript from Scala code? And is that a sane way to find the browser that the user is using? I want to send this information to the Server.
Of course, I could translate the function into Scala, but the JavaScript that the browser checks is not so easy for me to read - I've never been a JavaScript programmer.
The translation would be great even if it almost answered the main question.
EDIT @sjrd gave the answer from the Scala startup code. To give a complete picture, it looks like this: Page_scala:
object Page{
val boot =
"simple.MyScalaClient().main(document.getElementById('contents'))"
val browserVersionFn = "<script>function get_browser_info(){var ua=navigator.userAgent ... version: M[1]};}</script>"
val skeleton =
html(
head(
meta(charset:="utf-8"),
script(src:= "/myappname/myappname-fastopt.js"),
link(
rel:="stylesheet",
href:="http://yui.yahooapis.com/pure/0.5.0/pure-min.css"
)
),
body(
style := "margin:30",
onload := boot,
div(id:="contents"),
raw(browserVersionFn)
)
)
}
source to share
Once the script is executed, it get_browser_info
looks like any JavaScript library, from the point of view of Scala.js'. Therefore, you can call it in a dynamically typed way like this:
val browser = js.Dynamic.global.get_browser_info()
val name = browser.name.asInstanceOf[String]
val version = browser.version.asInstanceOf[String]
Or you can define a facade of the static type that you prefer.
source to share