Javascript: how to make sure window.open returns the same window if it is already open

I am working on a web application in which I have to open a popup. I use a method window.open()to open a popup, for example:

window.open(url, "popupWin");

where url contains the url where I need to open the popup. Now the problem is that if I execute window.open()from multiple tabs (with the same or different URLs), at least in Chrome, this may / may not give you the same window that was opened earlier. This behavior is inconsistent, I mean, every time he should get me a new window, or he should open an open window to me every time.

I need to keep the same popup for the whole domain .

Can someone please help me with this problem?

+4
source share
2 answers

It looks good that there is a direction to go or at least try.

It stays completely on localStorage, giving you the ability to share knowledge through your tabs within the same domain.

The code below does not work yet (this is only the direction), so do not expect too much from its launch, as it is.

What it does: it saves pop-ups at the URL in localStorage, and when you try to open a new one with the same URL, it will not. If you do not want to distinguish them by URL, it is even simpler: save boolean in localStorage instead of an object.

What he does not do, but must:

  • onunload () reset localStorage . localStorage boolean false
  • onunload (, ) , reset - . , , ( localStorage, , , , ) localStorage boolean false.

, , , . , , :

// get the localstorage url map
function getOpenPopups() {
  var obj = localStorage.getItem('mypopups');

  return obj ? JSON.parse(obj) : {};
}

// set the localstorage url map
function setOpenPopups(object) {
  localStorage.setItem('mypopups', JSON.stringify(object))
}

// open the popup
function popup(url, title) {
  var popups = getOpenPopups();

  // check whether popup with this url is already open
  // if not then set it and open the popup
  if (!popups[url]) {
    popups[url] = true;

        setOpenPopups(popups);

    return window.open('abc', 'cde');
  }
  else {
    return false;
  }
}

jsFiddle

+2

w3c , window.open() null, . , closed .

var newWindow = window.open('/some/path', 'TestWindow');
// ...
if (!newWindow.closed) {

}

, , . name, _blank, _self, _top, _parent, .

0

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


All Articles