javascriptexternalbrowser-tabexternal-links

How to know if browser tab is already open using 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

Example URLs

yahoo.com and google.com

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

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

Solution

  • You may use something like following

    <!-- 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();
    };
    

    Working jsBin | More on window.open method

    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);
      }
    };
    

    Working jsBin

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

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

    and remove random reference from the next line

    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.