首页 > 解决方案 > BroadcastChannel 与 localStorage - 兼容性

问题描述

当有新消息到达时,我在我的项目中使用 BroadcastChannel 来更改所有选项卡标题。问题是它只适用于 chrome 和 firefox。所以我决定使用 localStorage 创建一个 BroadcastChannel:

setInterval(function() {

    // check new messages:

    var title = localStorage.getItem('title');
    if(title != null && title != 0){

        document.title = document.title.replace(/\(\d+\)\s+/, "");
        document.title='('+title+')' + " " + document.title;

    }
    localStorage.setItem("title", "0");

    }, 100);

并且 ajax 将检查消息,如果它有一些新的:

localStorage.setItem("title", i);

问题是,它正在使用一些添加(1)的选项卡,但有些不是......我认为因为它在所有选项卡都可以读取它之前重置 localStorage setItem title = 0。有什么想法可以让它在所有标签都可以读取之前可用?

标签: javascriptjquery

解决方案


您应该使用在调用 setItem 时触发的“存储”事件,而不是按时间间隔读取本地存储。

对于真正适用于所有浏览器的 BroadcastChannel,我推荐https://github.com/pubkey/broadcast-channel


推荐阅读