javascript - 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。有什么想法可以让它在所有标签都可以读取之前可用?
解决方案
您应该使用在调用 setItem 时触发的“存储”事件,而不是按时间间隔读取本地存储。
对于真正适用于所有浏览器的 BroadcastChannel,我推荐https://github.com/pubkey/broadcast-channel
推荐阅读
- r - 我应该如何修复我的 x 轴?
- rest - 使用 Ember 使用 Dark Sky Weather API 时出现 404
- clipboard - API 在 monaco-editor 中获取 html 格式的内容?
- python - 使用 Tee-Object 将 python 脚本的结果输出到终端和文件
- javascript - 如何在 ejs 文件、nodeJS 应用程序中包含 JS 脚本?
- video - 视频文件在 Chrome 而不是 Safari 中找到/工作,无论 HTML 标签如何
- hibernate - 休眠删除父级
- java - 使用 Room 将二进制文件的链接与元数据一起存储是一种好习惯吗?
- r - 在函数中修改变量的内存有效方法
- javascript - 如何循环获取数组Javascript中对象的值?