如何避免在网页返回时通过JS触发重复的PubNub通知

时间:2019-04-22 17:52:02

标签: javascript twitter-bootstrap pubnub

我在使用 pubnub 使用 JS引导程序通知事件时遇到问题。

当BS通知事件被触发时,我切换到另一个页面,然后返回到事件被触发的页面-事件再次被触发。喜欢它的缓存。假设JS事件是通过此页面上的PubNub(例如,在聊天中)触发了4次,然后我切换到另一页面。

然后,我在浏览器中返回触发该事件的页面-一瞬间我得到了4倍的通知!

我的问题:如何避免在页面返回时触发JS事件?

用于引导的JS代码通知:

$.notify({
    icon: "/profile/getprofileimage/{0}/100".format(userid),
    message: message
}, {
    icon_type: 'image',
    type: "success",
    delay: 400,
    allow_dismiss: false,
    animate: {
    enter: 'animated bounceInDown',
    exit: 'animated bounceOutUp'
}
});

PubNub:

channels['request-received-<?php echo $_SESSION["user"]["id"]; ?>'] = function (data) {
    notify(data.Message, data.From);
    play('newpending');

    if (typeof(hoodlister) !== "undefined" && hoodlister instanceof list)
        hoodlister.getItem(data.From).then(updateProfile);
    if (typeof(visitorlister) !== "undefined" && visitorlister instanceof list)
        visitorlister.getItem(data.From).then(updateProfile);
    if (typeof(pendingmatcheslister) !== "undefined" && pendingmatcheslister instanceof list)
        pendingmatcheslister.refresh();
};

1 个答案:

答案 0 :(得分:1)

也许可以根据消息的时间令牌来保留警报的缓存,这可以解决您的问题。您可以在触发警报之前检查缓存。

当消息量很少时,PubNub时间令牌(17位数字)几乎是唯一的,因此虽然这不是很优雅,但可能是您需要的简单解决方法。

如果您触发大量警报,并且浏览器选项卡已存在数日,则缓存可能会变大,因此您可能需要处理该问题。

let cache = {};

pubnub.addListener({
    message: function(event) {
        if (!cache[event.timetoken]) {
            cache[event.timetoken] = true;
            // trigger the alert here
        }
    }
});