Prasanth
Prasanth

Reputation: 577

socket.io connection event not firing in firefox

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

Upvotes: 11

Views: 1342

Answers (3)

Stefan Vilbrandt
Stefan Vilbrandt

Reputation: 292

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

window.addEventListener("load",attachEventListners);

Upvotes: 0

robertklep
robertklep

Reputation: 203231

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.

Upvotes: 0

Prasanth
Prasanth

Reputation: 577

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

Upvotes: 3

Related Questions