[英]How to use pubnub timetoken to handle page refreshes
When pubnub is connected, users inside my app receive messages no problem. 连接pubnub时,我的应用程序内的用户不会收到任何消息。 However, let's say they refresh the page or go to another page within the app.
但是,假设他们刷新了页面或转到了应用程序中的另一个页面。 There's a 2 -> 5 seconds of downtime before the user can connect to pubnub again.
在用户可以再次连接到pubnub之前,有2-> 5秒钟的停机时间。 During this time some pubnub messages may be missed.
在此期间,可能会错过某些发布消息。
Thankfully, the pubnub subscribe API allows you to specify a timetoken
to point to a past time (eg 10 seconds ago). 幸运的是, pubnub订阅API允许您指定指向过去时间(例如10秒前)的时间
timetoken
。
pubnub.subscribe({
channels: ['my_channel'],
timetoken: '13534398158620385'
});
Description: 描述:
Specifies timetoken from which to start returning any available cached messages. 指定从其开始返回任何可用的缓存消息的时间令牌。
Question: What's the safest way to specify this timetoken
such that few messages are missed? 问题:指定此时间
timetoken
使很少的消息丢失的最安全方法是什么?
First, listen out for beforeunload
events on the window. 首先,在窗口上侦听
beforeunload
事件。 These will be fired before the page is moved away from. 这些信息会在页面移开之前触发。 Inside this create a cookie to save the current
timetoken
: 在其中创建一个cookie以保存当前的
timetoken
:
window.addEventListener('beforeunload', () => {
const now = new Date().getTime();
// pubnub timetokens are 17 digits long
const timetoken = `${now}0000`;
createCookie(PUBNUB_TIMETOKEN_COOKIE, timetoken, EXPIRATION);
});
Note: PUBNUB_TIMETOKEN_COOKIE
and EXPIRATION
are constants of your choosing. 注意:
PUBNUB_TIMETOKEN_COOKIE
和EXPIRATION
是您选择的常量。 I set my cookie to expire after 10 seconds to prevent clashes. 我将Cookie设置为在10秒后过期,以防止发生冲突。 Also you'll need to define a
createCookie
function similar to this one . 另外,您还需要定义一个与此类似的
createCookie
函数。
Next, when subscribing to pubnub on page load, use this cookie if it exists: 接下来,在页面加载时订阅pubnub时,请使用此cookie(如果存在):
pubnub.subscribe({
channels: ['my_channel'],
timetoken: getCookie(PUBNUB_TIMETOKEN_COOKIE)
});
This way, if the user refreshes or navigates to another page, missed messages should be caught. 这样,如果用户刷新或导航到另一个页面,则应该捕获错过的消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.