-2

I want to open a URL in a new browser tab with JavaScript or jQuery. And if it's already been opened, the tab is selected.

I use this function to open.

function OpenInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

What should I do if the tab is already open?

Farhad
  • 104
  • 3
  • 17
  • Keep an array of windows that you've already opened. On OpenInNewTab check the array to see if there's a window for the url, if there is focus to it, otherwise open the window and push to the array. – artm Oct 04 '14 at 12:03
  • 1
    Is there a reason why this can't go on the anchor tag as a simple target="_blank"? – Captain Kenpachi Oct 04 '14 at 12:06
  • Check the conversation here http://stackoverflow.com/q/8135188/3637090 – Bojan Petkovski Oct 04 '14 at 12:07

2 Answers2

0

See Here:

How to change browser focus from one tab to another

and Here:

Detect If Browser Tab Has Focus

Both of which are previous stack overflow posts.

It's possible to know when your on a tab, and when the user moves away from it (Using the new Page Visibility API)

But it's not possible to switch to another tab using javascript.

You COULD however (Which I very much doubt applies in your case) write an external program for your operating system that could communicate with the browser application and switch it that way, but directly from a web page, it's a non starter and a huge security risk.

Community
  • 1
  • 1
shawty
  • 5,729
  • 2
  • 37
  • 71
0

In general case a script can't get from the browser the info about opened pages because of security purposes.

Maybe it can be handful to store all links to child pages loading from current page and check every time before using window.open

var openedPages = []

function openUrl(url)
{
  if (!isWindowActive(url))
  {
    var win = window.open(url, '_blank')

    // also it's good to prevent duplicate url's, but I omit that stuff for simplicity
    openedPages.push({ 'url': url, 'win' : win })
  }
}

function isWindowActive(url)
{
   for(var i = 0; i < openedPages.length; ++i)
   {
     var page = openedPages[i]

     if (page.url === url)
     {
       return !page.win.closed
     }

     return false
   }
}
diziaq
  • 6,881
  • 16
  • 54
  • 96
  • OK I'm wrong. I wrote this example to explain: http://jsfiddle.net/wc70ef29/ –  Oct 04 '14 at 13:49