0

I have a URL, which is working with JavaScript. When I am hitting that URL then it will open a new window popup(window.open()) and again when I am hitting the same URL from a new tab and on the same browser, It is opening a new window popup even previous popup window is already opened.

So, Is there any way to focus on an already opened popup window instead of opening a new popup window from the new tab on the same browser?

Rudra
  • 1
  • 3
  • Assuming you can modify both sites, you could detect when the popup is open, but I don't believe changing tab/window focus is possible with JS (At least I hope not, that seems very abusable) – DBS Apr 16 '21 at 09:14

1 Answers1

0

(Un)Fortunately, there seems to be no reliable way to bring a window or tab into focus (see here or here).

For your other issue (not opening a new popup if it is already open), you have some options based on cross window/tab communication (assuming same origin):

  • You can set a cookie in your popup and delete it once the popup is closed (or more specifically unloaded). When attempting to open a new popup, check whether the cookie is already set. This has some pitfalls like you not having control over how many times the popup is opened by the user (manually, without your guard).
  • You can implement a form of tab/window communication (summarized in this question).

Assuming you can modify the popup and they share the same origin, an implementation based on Broadcast Channels might look like this (just to give you an idea):

From the source:

const bc = new BroadcastChannel('channel_id');
let isPopupOpen = false;

bc.onmessage = (ev) => {
  if (ev.data === 'popup-id-exists') {
    isPopupOpen = true;
  }
};

function openPopup() {
  isPopupOpen = false;
  bc.postMessage('popup-id');
  setTimeout(() => { if (!isPopupOpen) window.open('popup.html') }, 100);
}

From the popup:

const bc = new BroadcastChannel('channel_id');
bc.onmessage = (ev) => {
  if (ev.data === 'popup-id') {
    bc.postMessage('popup-id-exists');
  }
};
thabs
  • 603
  • 2
  • 13