Shashwat
Shashwat

Reputation: 2668

Avoiding duplicate browser tabs or windows (window.open())

In Javascript, we can use window.open() to open a new browser window or tab. But if a tab is already open, it should highlight that only. It should not open duplicate tabs. How to do that?

Upvotes: 3

Views: 11432

Answers (4)

JamesT
JamesT

Reputation: 83

Candide's code needs a slight correction. The null condition should be checked and not "!="

popwin.html is the page you want to open in a popup. I know this is already answered, just posting in case someone wanted to refer later on.

MAIN WINDOW CODE:

<script type='text/javascript'>
var newwin;
function popup(){

if (newwin == null) 
    { 
    window.open('popwin.html', 'newwin'); 
    } 
    else 
    { 
    newwin.focus(); 
    }
}

</script>

CALL THE POPUP in body area of same page:

<a href="#" onClick="popup();">Open Window</a>

Upvotes: 0

Yaniro
Yaniro

Reputation: 1587

Make sure you supply the same window name to window.open() every time! (second parameter, must not be empty)

You will need to manage the window object returned from window.open() and check if it was closed or not, check out https://developer.mozilla.org/en/DOM/window and the closed property. You will have to have a window to url list which will help you decide if to use window.open() to open a new window (a url which isn't open at the moment) or use the openedWindow.focus() (openedWindow is the object returned by the previous call to window.open()) to bring the window into view.

Upvotes: 2

Roland Mai
Roland Mai

Reputation: 31077

The second argument of window.open(strUrl, strWindowName[, strWindowFeatures]); is the window name. if you specify that parameter, to anything other than "_blank" it will refer to the already opened tab/window.

For instance:

window.open('/about', 'newwindow');

and

window.open('/contact', 'newwindow');

will open the page in an already opened window/tab.

Upvotes: 5

Tim
Tim

Reputation: 320

Give the window a target name: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

New urls wil open in it if exist already

Upvotes: 2

Related Questions