I have a websockets program in play 2.1, which works just fine and the template looks like this:
// Contents of the view.scala.html file
@(userName: String)(implicit request: RequestHeader)
@main("text") {
  <script type="text/javascript" charset="utf-8">
  $(function() {
    var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
    alert("before")
    var socket = new WS("@routes.Application.view(userName).webSocketURL()");
    alert("after")
    socket.onmessage = function(event) {
      alert(event.data);
    };
  });
  </script>
}
The issue is that as soon as I move my javascript into the assets.javascripts folder and change the view.scala.html file into the following it stops working.
// Contents of the view.scala.html file
@(userName: String)(implicit request: RequestHeader)
@main("text") {
  <script type="text/javascript" charset="utf-8"
          src="@routes.Assets.at("javascripts/viewer.min.js")"></script>
}
Play finds the file, executes the javascript, I can see the popup triggered by the alert("before") line of code, but after that... nothing.
This is the google chrome error I get in the console:
Wrong url scheme for WebSocket
http://localhost:9000/@routes.Application.view(userName).webSocketURL()
What am I missing?
A WebSocket needs ws:// or wss:// (for SSL) instead of http://.
However, the problem in your code is that the statement @routes.Application.view(userName).webSocketURL() apparently isn't replaced with some useful value but kept as-is. This is because your framework seems to consider assets completely static and thus ignores anything in there that would be a placeholder/variable in a normal template.
One possible solution for your problem would be keeping the URL in your template, e.g. by adding data-ws="@....." to your <body> tag and then use JavaScript to extract that attribute:
var socket = new WebSocket(document.body.getAttribute('data-ws'))
                        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