Window.open only if the window is not open

前端 未结 3 1405
予麋鹿
予麋鹿 2021-01-18 02:14

I have a link on my site that opens a new window to a page that plays a very long audio file. My current script works fine to open the page and not refresh if the link is cl

相关标签:
3条回答
  • 2021-01-18 02:32

    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();
        } 
    }
    
    0 讨论(0)
  • 2021-01-18 02:38

    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.

    0 讨论(0)
  • 2021-01-18 02:50

    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.

    0 讨论(0)
提交回复
热议问题