Somebody
Somebody

Reputation: 9645

Javascript: Check for duplicate opened window

Is it possible to check if same window is already opened?

For example i have opened a window via javascript.

Can i check if that's opened on another page via javascript?

Just want to focus on page if it's been opened already to avoid duplicate windows.

Thanks ;)

Upvotes: 2

Views: 8890

Answers (3)

SRTECH
SRTECH

Reputation: 15

This will help if you want to open a url from a link

 var Win=null;
function newTab(url){
//var Win; // this will hold our opened window

// first check to see if the window already exists
if (Win != null) {
// the window has already been created, but did the user close it?
// if so, then reopen it. Otherwise make it the active window.
if (!Win.closed) {
  Win.close();
//   return winObj;
}

 // otherwise fall through to the code below to re-open the window
 } 

 // if we get here, then the window hasn't been created yet, or it
 // was closed by the user.
 Win = window.open(url);

 return Win; 

 }
 newTab('index.html');

Upvotes: 0

Residuum
Residuum

Reputation: 12064

Look at window.open() method. You must specify the name of the window as the second parameter. If there already is a window with that name, then the new URL will be opened in the already existing window, see http://www.w3schools.com/jsref/met_win_open.asp

If you really want to check, if the window is opened by your own scripts, then you have to keep a reference to the opened window in a global variable or the likes and create it with

var myOpenedWindow = myOpenedWindow || window.open(URL, "MyNewWindow");

You can also encapsulate this behavior in a method:

var myOpenWindow = function(URL) {
    var myOpenedWindow = myOpenedWindow || window.open(URL, "MyNewWindow");
    myOpenedWindow.location.href= URL;
    myOpenedWindow.focus();
}

And call that function with myOpenWindow('http://www.example.com/');

Upvotes: 2

Harry Joy
Harry Joy

Reputation: 59670

If you have parent--child window then here is a solution that will allow you to check to see if a child window is open from the parent that launched it. This will bring a focus to the child window without reloading its data:

 <script type="text/javascript">
    var popWin;
    function popPage(url)
    {
       if (popWin &! popWin.closed && popWin.focus){
           popWin.focus();
       } else {
          popWin = window.open(url,'','width=800,height=600');
      }
    }
</script>

    <a href="http://www.xzy.com"
onclick="popPage(this.href);return false;">link</a>

one more thing ::--- If the user refreshes the parent window, it may loses all its references to any child windows it may have had open.

Hope this helps and let me know the output.

Upvotes: 1

Related Questions