11

Im having something like the below code.

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://localhost:8080');
  socket.on('connect', function(){
      socket.on('some-event', function(data) {});
  });
  socket.on('disconnect', function(){});
</script>

Inside the connect callback I have some code that responds to messages. This works perfectly fine on chrome. On first page load it works fine on firefox. If you reload the page then the connect event does not get called.

Im using 1.4.8 version of server and js client

Prasanth
  • 577
  • 1
  • 9
  • 24
  • Does this help at all: http://stackoverflow.com/questions/17298950/socket-io-not-working-in-chrome-and-firefox-on-windows – Adam Gerard Sep 15 '16 at 22:51

3 Answers3

3

I solved it using the following code. Not very clean but for the time being this helped us to progress with the project. As you can see the problem is the connect event not firing after a page reload, so I decided to attach the events after a timeout if connect was never fired.

function attachEventListners() {
    socket.on('some-event', function(data) {});
}

var attached = false;
socket.on('connect', function(){
      attachEventListners();
      attached = true;
});

setTimeout(function() {
    if (!attached) {
        attachEventListners();
    }
}, 1000);
Prasanth
  • 577
  • 1
  • 9
  • 24
0

You don't have to declare event listeners inside a connect listener, so even though I don't know a direct solution to your problem, I think this'll work around it:

<script>
  var socket = io('http://localhost:8080');
  socket.on('some-event', function(data) {});
  socket.on('disconnect', function(){});
</script>

Because being able to receive messages implies that the socket is connected.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • Thats the first thing that I tried, unfortunately it didn't work. – Prasanth Sep 16 '16 at 12:51
  • It should (see also [the official example code](http://socket.io/docs/#using-with-node-http-server)). If it doesn't, it may be caused by the same problem that is also causing your FF problem of missing the `connect` event. – robertklep Sep 16 '16 at 12:54
0

Instead of a timeout, you should use the load event listener on window

window.addEventListener("load",attachEventListners);
Stefan Vilbrandt
  • 282
  • 3
  • 11