Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting the existence of window after reload

so suppose I do this

var myWindow = false;
$('someelement').click(function(){
  var myWindow = window.open('url', 'name', 'width=100,height=200');
});

so the user clicks on the element on window A and a new window (call it window B) is opened...

but then suppose window A gets reloaded...due to this, var myWindow is now set to false...but then window B is still open....how can I detect the existence of Window B from window A after window A gets reloaded

I know that you can do this:

var hasWindow = window.open('', 'name');

and it will return a reference to window B if it's already open..

But then if window B is NOT opened yet, this will instead trigger a window opening, which is undesirable

How can I get a reference to window B if it's open without triggering a new window opening in the event in which window B is not open? (without resorting to cookie tricks)

like image 397
pillarOfLight Avatar asked Nov 12 '22 23:11

pillarOfLight


1 Answers

The best way to keep a LITTLE bit of state without storing in cookies is to save something to your window.name. It'll only work with a string, though, so you'll need to save it as a JSON string if you want more than just a single bit of data.

To read:

var keptState;
if (window.name !== "") {
    keptState = JSON.parse(window.name);
}

To write:

state = {
    "popupOpened" : true,
    "popupName" : "otherWindowName"
};
window.name = JSON.stringify(state);

On the other side of the refresh (or even navigating away from the site and back), it'll keep your variables you wanted. If you actually wanted a reference to the other window, however, you're on your own for that. I can't think of any way to determine that it's actually there. This would be a problem if, say, someone closed the popup window on their own.

At least this way, you can find out if you've opened it. Then you could do a popunder if you really needed that window without the popup. This always feels a little shady when I do it, but it's probably the best way to do what you're asking for.

var myWindow = window.open('', 'otherWindowName');
myWindow.blur();
window.focus();
like image 200
Dan Crews Avatar answered Nov 15 '22 11:11

Dan Crews