问题
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?
回答1:
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.
回答2:
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
回答3:
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.
回答4:
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>
来源:https://stackoverflow.com/questions/9496345/avoiding-duplicate-browser-tabs-or-windows-window-open