如何知道浏览器选项卡是否已使用Javascript打开? [英] How to know if browser tab is already open using Javascript?

查看:180
本文介绍了如何知道浏览器选项卡是否已使用Javascript打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何知道或检查两个浏览器选项卡是否已打开,如果这些选项卡已打开,用户将收到一个警告框或消息框,说网址已经打开,类似于纯粹/原生JavaScript?此浏览器选项卡包含一个外部网站,我没有任何权限来操纵或更改它。谢谢

How to know or check if the two browser tab is already open and if those tab are open, the user will receive an alert box or msg box saying that 'the url is already open', something like that, in pure/native JavaScript? This browser tab is contain an external website which is I don't have any privileges to manipulate or change it. Thanks

示例网址

yahoo.com and google.com

我想提醒用户是否已经打开yahoo.com和google.com的标签

I want to alert the user if there's already open tab for yahoo.com and google.com

我想使用tabCreate打开这样的网址:

And I want to use tabCreate to open the url like this:

tabCreate("http://maps.google.com/", "tabMapsPermanentAddress");
mean to open a new tab, it is use in creating chrome extension


推荐答案

您可以使用以下内容

<!-- HTML -->
<a id="opener">Open window</a>

// JavaScript
var a = document.getElementById('opener'), w;        
a.onclick = function() {
  if (!w || w.closed) {
    w = window.open("https://www.google.com","_blank","menubar = 0, scrollbars = 0");
  } else {
    console.log('window is already opened');
  }
  w.focus();
};

工作jsBin | 有关window.open方法的更多信息

如果您想控制多个窗口,请使用下面的代码段

If you want to control more than one window, use the snippet below

<!-- HTML -->
<a href="https://www.google.com" class="opener">Open google.com</a> | 
<a href="http://www.yahoo.com" class="opener">Open yahoo.com</a> 

//JavaScript
window.onload = function(){
  var a = document.querySelectorAll('.opener'), w = [], url, random, i;
  for(i = 0; i < a.length; i++){
    (function(i){
      a[i].onclick = function(e) {
        if (!w[i] || w[i].closed) {
          url = this.href;
          random = Math.floor((Math.random() * 100) + 1); 
          w[i] = window.open(url, "_blank", random, "menubar = 0, scrollbars = 0");
        } else {
          console.log('window ' + url + ' is already opened');
        }
        e.preventDefault();
        w[i].focus();
      };
    })(i);
  }
};

工作jsBin

如果您不希望它们在单独的窗口中加载,只需排除此行

If you don't want them to load in separated window, just exclude this line

random = Math.floor((Math.random()*100)+1);

并从下一行删除 random 引用

w[i] = window.open(url, "_blank", random, "menubar=0,scrollbars=0");

附注:如上所示,我们创建了两个带有第三方内容的窗口;你应该知道没有办法从他们那里得到任何参考(到父/开启窗口)。

Side note: As you can see above, we created two windows with some third party content; you should know that there's no way to get any reference (to the parent/opener window) from them.

这篇关于如何知道浏览器选项卡是否已使用Javascript打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆