Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong url scheme for WebSocket

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?

like image 577
agilesteel Avatar asked Dec 20 '22 12:12

agilesteel


1 Answers

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'))
like image 108
ThiefMaster Avatar answered Dec 31 '22 22:12

ThiefMaster