8

I want to disconnect a firebase socket without refreshing or closing the page, but how to do that?

Is there any method like socket.disconnect() or socket.close() I can use? I have just found the socket.onDisconnect() method.

bbbco
  • 1,508
  • 1
  • 10
  • 25
zhuhan1236
  • 83
  • 1
  • 4
  • 3
    What's the actual problem you're trying to solve? – Kato May 11 '13 at 15:01
  • @Kato an obvious use case that seems to fit the question would be, in a single-page app, closing a Firebase connection to avoid it needlessly using bandwidth after the user has navigated away from the part of the site that uses Firebase. – Mark Amery Mar 03 '15 at 11:46

2 Answers2

18

Firebase recently added support for two new static methods to each client, Firebase.goOffline() and Firebase.goOnline(), which allow you to manually disconnect and reconnect in your application.

From https://www.firebase.com/docs/javascript/firebase/gooffline.html:

Manually disconnect the Firebase client from the server and disable automatic reconnection.

The Firebase client automatically maintains a persistent connection to the Firebase server, which will remain active indefinitely and reconnect when disconnected. However, the goOffline( ) and goOnline( ) methods may be used to manually control the client connection in cases where a persistent connection is undesirable.

While offline, the Firebase client will no longer receive data updates from the server. However, all Firebase operations performed locally will continue to immediately fire events, allowing your application to continue behaving normally. Additionally, each operation performed locally will automatically be queued and retried upon reconnection to the Firebase server.

To reconnect to the Firebase server and begin receiving remote events, see goOnline( ). Once the connection is reestablished, the Firebase client will transmit the appropriate data and fire the appropriate events so that your client "catches up" automatically.

Note: Invoking this method will impact all Firebase connections.

See Firebase.goOffline( ) and Firebase.goOnline( ) for more details.

Rob DiMarco
  • 13,226
  • 1
  • 43
  • 55
  • 1
    while it will stop using the socket it does not close it. To demonstrate this, just try using it with node. After doing any transactions, the node process will continue after running goOffline. Too bad when you're using something like Lambda which requires a normal process exit in order to trigger the return call back. – Dale Corns May 08 '17 at 19:20
  • This also doesn't trigger any "onDisconnect" flows – Matt Westlake Apr 25 '19 at 01:29
-19

var dataRef = new Firebase("https://SampleChat.firebaseio-demo.com/");

You can disconnect using dataRef.unauth().

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ashok
  • 661
  • 6
  • 17
  • 1
    Thank you for your answer! But I didn't use dataRef.auth().So, it seems that dataRef.unauth() doesn't work. – zhuhan1236 May 11 '13 at 10:53