Rai Rz
Rai Rz

Reputation: 535

Javascript : get current window.open() when parent window was refreshed

I want open window but when user refreshed parent location or going to hyperlink, we got last child window and using this code win_pop.location.replace('http://example.com') .

for example :

var win_pop = window.open(url, 'lastWin', 'width=300px,height=200px,top=1200px,left=2000px');

why after refresh parent location child window doesn't working.! before any refresh or going to hyperlink in parent page that working well.

win_pop.location.replace('http://example.com') !!

Do you got any best suggest ?

Upvotes: 0

Views: 175

Answers (2)

Kaiido
Kaiido

Reputation: 136618

@Quentin is right about what happens to your js variable, but he seems to have forgotten a little thing:

You can make use of the postMessage API and the MessageEvent.source property which will point to your popup Window.

So you can start a loop on your popup which will post a message every n-th seconds to window.opener.

setInterval(function(){
  window.opener.postMessage('foo', '*');
}, delay);

Then in all your pages, you will listen for the message event, and set your popup variable to the MessageEvent.source you just retrieved:

onmessage = function(evt){
  popup = evt.source;
};

And voilà!

Here is a plnkr

Upvotes: 1

Quentin
Quentin

Reputation: 943128

  1. You load a page
  2. You assign a value to a variable called win_pop
  3. You load a new page

The lifespan of a JavaScript program running in an instance of a webpage is only as long as that webpage instance exists.

When you have a new page, you have a new JS environment, and the old data is lost.

win_pop no longer contains the value you assigned to it.

Much of the time you can store data between pages (e.g. via Local Storage), but that only applies to simple objects, arrays and primitives.

There is no way to preserve the reference to a new window.


The only way to achieve that effect would be to avoid reloading the original page. For example, by performing all navigation to "new pages" by using Ajax and manipulating the history with pushState and friends.

Upvotes: 2

Related Questions