浏览器window.open行为变更致弹窗聚焦失效,求解决方案
问题:多实例Web应用中实现同一Target仅对应一个弹窗并聚焦
我开发的Web应用需要打开多个外部弹窗,例如使用window.open('https://stackoverflow.com/', 'stackoverflow')。用户可能打开多个应用实例,我希望同一target仅对应一个弹窗。
此前采用BroadcastChannel在多实例间共享已打开的target信息,通过window.open('', target)聚焦已有窗口,无需重载页面。但目前浏览器行为变更,该操作会打开新的about:blank窗口。我尝试改为发送广播消息调用focus(),但对最小化窗口无效果。
以下是两个测试代码片段,寻求其他可行解决方案:
测试代码片段1
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <button onclick="openWindow('https://stackoverflow.com/', 'stackoverflow')"> Open stackoverflow </button> <script> const broadcastChannel = new BroadcastChannel('WindowService'); const openWindowsTarget = []; broadcastChannel.onmessage = (event) => { if (event.data.type === 'open') { openWindowsTarget.push(event.data.value); console.log({openWindowsTarget}) } }; function openWindow(url, target) { if (openWindowsTarget.includes(target)) { window.open('', target); } else { broadcastChannel.postMessage({ type: 'open', value: target }); openWindowsTarget.push(target); window.open(url, target); } } </script> </body> </html>
测试代码片段2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <button onclick="openWindow('https://stackoverflow.com/', 'stackoverflow')"> Open stackoverflow </button> <script> const broadcastChannel = new BroadcastChannel('WindowService'); const openWindowsTarget = []; const localWindows = {}; broadcastChannel.onmessage = (event) => { if (event.data.type === 'open') { openWindowsTarget.push(event.data.value); console.log({openWindowsTarget}) } if (event.data.type === 'focus') { if( localWindows[event.data.value] ){ localWindows[event.data.value].focus(); } } }; function openWindow(url, target) { if (openWindowsTarget.includes(target)) { broadcastChannel.postMessage({ type: 'focus', value: target }); } else { broadcastChannel.postMessage({ type: 'open', value: target }); openWindowsTarget.push(target); localWindows[target] = window.open(url, target); } } </script> </body> </html>
内容的提问来源于stack exchange,提问作者ar099968
相关产品推荐
相关产品推荐

