Window.open only if the window is not open

℡╲_俬逩灬. 提交于 2019-12-01 16:39:41

You should first to call winRef = window.open("", "winPopup") without URL - this will return a window, if it exists, without reloading. And only if winRef is null or empty window, then create new window.

Here is my test code:

var winRef;

function OpenWindow()
{
  if(typeof(winRef) == 'undefined' || winRef.closed)
  {
    //create new
    var url = 'http://someurl';
    winRef = window.open('', 'winPop', 'sampleListOfOptions');
    if(winRef == null || winRef.document.location.href != url)
    {
      winRef = window.open(url, 'winPop');
    }
  }
  else
  {
    //give it focus (in case it got burried)
    winRef.focus();
  } 
}

It works.

WTK

Like you said, after navigating away from original page you're losing track of what windows you may have opened.

As far as I can tell, there's no way to "regain" reference to that particular window. You may (using cookies, server side session or whatever) know that window was opened already, but you won't ever have a direct access to it from different page (even on the same domain). This kind of communication between already opened windows may be simulated with help of ajax and server side code, that would serve as agent when sharing some information between two windows. It's not an easy nor clean solution however.

Thanks to Stan and http://ektaraval.blogspot.ca/2011/05/how-to-set-focus-to-child-window.html

My solution creates a breakout pop-up mp3 player that remains active site wide and only refreshes if the window is not open prior to clicking the link button

function OpenWindow(){
    var targetWin = window.open('','winPop', 'sample-options');
    if(targetWin.location == 'about:blank'){
        //create new
        targetWin.location.href = 'http://site/megaplayer';
        targetWin.focus();
    } else {
        //give it focus (in case it got burried)
        targetWin.focus();
    } 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!