Enabling offline capabilities in JavaScript

When we create Realtime Application with Firebase, we also need to monitor the connection when clients connect and disconnect with database.  Firebase provides a simple solution, which you can use to write to the database when a client disconnects from the Firebase Database servers. We can perform all operations such as writing, setting, updating, and removing can be performed upon a disconnection.

Refer to this example onDiscconnect() method of Firebase:

var presenceRef = firebase.database().ref("disconnectmessage");
// Write the string when client loses connection
presenceRef.onDisconnect().set("I disconnected!");

We can also attach the callback function to ensure that the onDisconnect() method is attached properly:

presenceRef.onDisconnect().remove(function(err) {
if (err) {
console.error('onDisconnect event not attached properly', err);
}
});

To cancel the onDisconnect() method, we can call .cancel() method onDisconnectRef.cancel();.

For detecting the connection state, Firebase Realtime Database provides special location  /.info/connected.

This is updated every time app connection state changes; it returns the boolean value to check whether the client connection state is connected:

var connectedRef = firebase.database().ref(".info/connected");
connectedRef.on("value", function(snap) {
if (snap.val() === true) {
alert("connected");
} else {
alert("not connected");
}
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset