How to check that javascript does not open the same window with window.open function

In my javascript, I want to open the URL in a new window using this method:

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

How can I check this, and not open the same window and lose all the data entered. For example, if I opened the URL "www.musite.com/addproduct" in a new window, enter the data, leave your workplace. then I click on the open window again, open a new window, and I lost all my data.

+4
source share
2 answers

Below you can 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 re-open it. You can listen to the window.onunload event in a popup window, as shown below:

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

The onunload event onunload sets the global variable win in the window, opening the popup to undefined so that you can open the window again.

Remember that due to the same origin policy, this will only work if the popup is in the same domain as the parent window. Also, note that I just tested above in Firefox.

+2
source

The window.open function returns a link to the window if successful or null if it is unsuccessful.
You should check that win not null:

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

You will also want to set win to null when you close the window so you know you can open it again.

0
source

Source: https://habr.com/ru/post/1307823/


All Articles