简体   繁体   English

如何使用 JavaScript 从新选项卡中关注打开的弹出窗口 window

[英]How to focus on opened popup window from a new tab using JavaScript

I have a URL, which is working with JavaScript.我有一个 URL,它正在与 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. 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 已经打开。

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?那么,有没有办法专注于已经打开的弹出窗口 window 而不是从同一浏览器的新选项卡中打开新的弹出窗口 window ?

(Un)Fortunately, there seems to be no reliable way to bring a window or tab into focus (see here or here ). (Un)幸运的是,似乎没有可靠的方法可以使 window 或标签成为焦点(请参阅此处此处)。

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 ).您可以在弹出窗口中设置一个 cookie,并在弹出窗口关闭(或更具体地说是unloaded )后将其删除。 When attempting to open a new popup, check whether the cookie is already set.尝试打开新弹出窗口时,请检查 cookie 是否已设置。 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');
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM