4

I use a Page.scala to start the Client-side of a Scala.js application. Thus Page.scala replaces index.html. The Scalatags raw function allows actual JavaScript to be included. In the Scalatags documentation the example is alert('Hello!'). I actually have a little bit of JavaScript that works out what the browser is, but saying "Hello!" is good for a start. The JavaScript itself is the get_browser_info() function here.

So my question is, can I call this little bit of JavaScript from within Scala code? And is that a sensible way of going about discovering the browser the user is using? I will want to send this information back to the Server.

Of course I could translate the function into Scala, but the JavaScript that checks the browser isn't that easy for me to read - I've never been a JavaScript programmer.

A translation would be great, even if it it would only nearly be answering the core question.

EDIT @sjrd gave the answer from the startup Scala code. To give the complete picture this is what Page.scala looks like:

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)
      )
    )
}

1 Answer 1

5

Once the script is executed, the get_browser_info is just like any JavaScript library, from Scala.js' point of view. You can therefore 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 static type facade of you prefer.

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

Comments

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.