Javascript:在多个选项卡中播放一次音频
Javascript: Play audio once in multiple tabs
在我的应用程序中,我编写了系统播放音频,当用户收到通知时通知用户。
如果用户打开了很多浏览器选项卡,这个音频会被播放很多次(一个选项卡)。
是否有办法做到音频只播放一次?
谢谢!
您可以在localStorage
:
//create random key variable
var randomKey = Math.random() * 10000;
//set key if it does not exist
if (localStorage.getItem("tabKey") === null) {
localStorage.setItem("tabKey", randomKey);
}
这样,项目tabKey
将被设置为第一个选项卡的randomKey
。现在,当你播放音频时,你可以这样做:
if (localStorage.getItem("tabKey") === randomKey) {
playAudio();
}
这将只播放第一个选项卡中的音频。
唯一的问题是,您必须对用户关闭第一个选项卡的情况做出反应。您可以取消选项卡关闭上的tabKey
项,并使用storage
事件在其他选项卡中捕获此事件:
//when main tab closes, remove item from localStorage
window.addEventListener("unload", function () {
if (localStorage.getItem("tabKey") === randomKey) {
localStorage.removeItem("tabKey");
}
});
//when non-main tabs receive the "close" event,
//the first one will set the `tabKey` to its `randomKey`
window.addEventListener("storage", function(evt) {
if (evt.key === "tabKey" && evt.newValue === null) {
if (localStorage.getItem("tabKey") === null) {
localStorage.setItem("tabKey", randomKey);
}
}
});
相关文章:
- Javascript返回值只在循环中返回一次
- Jquery FadeIn FadeOut 只工作一次
- Javascript html每点击一次就会更改url
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- JQuery-一次停止所有音频
- 安卓播放音频一次
- 使用 Javascript/jQuery 一次播放一个 HTML 音频文件
- Internet Explorer 10:<音频>“播放”事件处理程序仅发生一次
- 为什么"结束”;音频html5的事件触发不止一次
- 音频播放器-一次只播放一首曲目,不起作用
- Javascript-每30秒播放一次音频剪辑
- 为什么可以't我使用HTML5音频标签播放声音不止一次
- 音频重复不止一次
- 音频自动播放一次
- 一次可以播放多少个HTML音频元素
- 音频播放一次只在谷歌浏览器的html
- Javascript:在多个选项卡中播放一次音频
- 2个音频,我想一次只播放一个HTML5音频元素
- 我只希望我的音频mp3文件播放一次,但它没有发生
- Ajax只播放一次音频文件