tags:

views:

100

answers:

2

Hello! In my javascript i want to open URL in new window with this method:

var win = window.open(url...);

How can i check this, not to open the same window and lose all inputted data. For example, if i opened "www.musite.com/addproduct" URL in new window, input data, leave my work place. then i click open window again, new window open and i lost all my data.

A: 

The window.open function returns a referens to the window if successfull or null if unsuccessfull.
You should check that win isn't null:

if (win != null) {
  // It is now safe to open the window.
}

You'll also want to set win to null upon closing the window so that you'll know that you can open it again.

Sani Huttunen
thanks, and how i can check event when window closed?and...var win = window.open(url) - in this moment window already opened
Dmitriy
+1  A: 

The following will allow you to open the window only once:

if (typeof win !== 'object') {
   win = window.open('http://www.google.com');
}
else {
   // Do nothing
}

As Sani suggested in another answer, it would be wise to keep track of when the window is closed, in order to be able to reopen it. You can listen for the window.onunload event in the popup window, as follows:

window.onunload = function() {
   window.opener.win = undefined;
}

The onunload event handler will set the win global variable of the window that opened the popup to undefined, so you would be able to reopen the window.

Be aware that due to the same origin policy, this will only work if the popup you open will be in the same domain as the parent window. In addition note that I've only tested the above in Firefox.

Daniel Vassallo
is there any event on window close? cause i check this solution.. and: i open window first time - OK. try open second copy of window - OK (message). Close window. Open one window - ERROR (Message that window is already opened)
Dmitriy
Yes, you can listen for `window.onunload` event in the popup: https://developer.mozilla.org/en/DOM/window.onunload
Daniel Vassallo
thanks a lot, works great
Dmitriy