检测在 javascript 中打开的同一应用的多个镶边标签页

Detect multiple chrome tabs opened of the same app in javascript

本文关键字:标签 应用 javascript 检测      更新时间:2023-09-26

有没有办法检测是否打开了同一应用程序的多个浏览器选项卡。

假设我有 www.test.com,我打开了这个网站的 4 个选项卡。

有没有办法检测在 JavaScript 中打开了多个选项卡?

您可以使用我的sysend.js库,它使用localStorage在打开的选项卡/窗口之间发送消息。所有要做的是以下代码:

sysend.on('notification', function() {
   sysend.broadcast('multiple');
});
sysend.on('multiple', function() {
   // this will fire n-1 times if there are n tabs open if n > 1
   alert('multiple pages');
});
sysend.broadcast('notification');

吉斯菲德尔

有,但不能保证总是正确的:

window.onload = function() {
  var applicationCount = localStorage.getItem("applicationCount");
  if (!applicationCount) {
    applicationCount = 0;
  }
  localStorage.setItem("applicationCount", ++applicationCount);
}
window.onbeforeunload = function(e) {
  var applicationCount = localStorage.getItem("applicationCount");
  if (!applicationCount) {
    applicationCount = 1;
  }
  localStorage.setItem("applicationCount", --applicationCount);
};

它使用在选项卡之间共享的本地存储。但请注意,如果浏览器崩溃,该值仍会保存。