Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window.open only if the window is not open

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 clicked multiple times. However, when I have moved to a seperate page on my site and click this link again, it reloads. I am aware that when the parent element changes, I will lose my variable and thus I will need to open the window, overiding the existing content. I am trying to find a solution around that. I would prefer not to use a cookie to achieve this, but I will if required.

My script is as follows:

function OpenWindow(){
    if(typeof(winRef) == 'undefined' || winRef.closed){
    //create new
    winRef = window.open('http://samplesite/page','winPop','sampleListOfOptions');
    } else {
    //give it focus (in case it got burried)
     winRef.focus();
    } 
}
like image 741
Tyler Demerchant Avatar asked Nov 16 '12 07:11

Tyler Demerchant


2 Answers

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.

like image 138
Stan Avatar answered Sep 24 '22 20:09

Stan


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();
    } 
}
like image 45
Tyler Demerchant Avatar answered Sep 25 '22 20:09

Tyler Demerchant