首页 > 解决方案 > 如果浏览器选项卡空闲,Firebase child_changed 事件会随机丢失

问题描述

我正在构建实时应用程序,其中一个人正在进入应用程序,并且该会话的所有连接用户都被注意到或接收一个人正在输入的有效负载。

以下是我的 firebase child_changed 监听器,每个设备都在监听:

firebase.database().ref().child('collection')
    .orderByChild('sessionId')
    .equalTo('123') //unique id
    .on('child_changed', function (snapshot) {
    //some processing                 
});

每当有人进入应用程序时,我都会像这样在 firebase 文档/集合上方更新:

var newObject = {},
        fbId = 'Kh8nyd9C1FGeBx229ogyr';// unique id of document to be updated

newObject[fbId] = {
    'sessionId': '123',
    'payLoad': JSON.stringify(payLoad), //different payload to send to each device which is listening to collection and this session
    'lastUpdated': new Date().getTime() //adding unique time so child_changed should trigger
};

firebase.database().ref().child('collection').update(newObject);

//rules

"rules": {
    "$uid": {
        "collection": {
            ".read": "auth.uid == $uid",
                ".write": "auth.uid == $uid",
                    ".indexOn": ["sessionlId"]
        }  
    }
}

//data

{
  "Azublidegytttsbmnmnmnm": { //uid
    "collection": {
      "Kh8nyd9C1FGeBx229ogyr": {
        "sessionId": 123,
        "payLoad": {Id: '11', Name: 'John Doe'},
        "lastUpdated": 1543875382963 
      }
    }  
  }
}

上面的代码在大多数情况下都可以工作,但是如果浏览器选项卡保持空闲一段时间,然后它会停止接收此事件或无法触发 child_changed 事件,如果正在进入的人已经进入并且其他连接的人的选项卡空闲,则会错过事件。我刷新浏览器 firebase 连接代码得到刷新,现在一切正常。

对于每次触发此 child_changed 事件的任何帮助表示赞赏。或者请建议任何其他方法来解决这个问题。

我的 firebase 库是 3.5.3 版本。

谢谢!

标签: javascriptangularjsfirebaseionic-frameworkfirebase-realtime-database

解决方案


将我的 firebase 3.5.3 更新到最新版本。而且我已经开始直接在节点上绑定事件,而不是监听整个 json 集合(在 root 监听)。

旧代码:

firebase.database().ref().child('collection')
    .orderByChild('sessionId')
    .equalTo('123') //unique id
    .on('child_changed', function (snapshot) {
    //some processing                 
});

新代码:

firebase.database().ref().child('collection/Kh8nyd9C1FGeBx229ogyr') //Kh8nyd9C1FGeBx229ogyr here is firebase generated node and its unique id
    .on('child_changed', function (snapshot) {
    //some processing                 
});

PS 尝试听最低级别来获取 child_changed 事件。来自 Firebase 支持


推荐阅读