如何在不使用 window 打开的情况下关闭选项卡

How to close tab without using window open

我使用以下方法打开带有一些页面内容的新选项卡(在新进程中),

var p = document.getElementById("myElement"); 
var a = document.createElement('a');
a.setAttribute('href',".../mypage.html");
a.setAttribute('rel',"noreferrer");
a.setAttribute('target',"_blank");
p.appendChild(a);
a.click();

http://news.softpedia.com/news/Force-Google-Chrome-to-Open-Links-in-New-Processes-128962.shtml

当您使用此代码时,它总是会打开新标签页, 我希望当您调用此代码时,它会查看它是否是在新选项卡中打开的先前调用,然后它将关闭它并且新调用将在新选项卡中打开。 或者可能 运行 到上一个选项卡中的新页面而不关闭它。

我不能使用常规 window.open API 的 ...

Service workers 如果您可以控制所有涉及的页面,则有可能。

How to Send Messages Between Service Workers and Clients 描述了如何实现进入每个页面并提供在这些页面之间广播消息的方法的服务工作者。

服务人员无权访问 DOM。相反,您可以安排将消息传递给特定的客户端(页面),然后该客户端根据该消息执行它自己的 DOM 操作。

无论采用何种解决方案,请记住,出于安全考虑,页面已被沙盒化,因此需要某种自愿协议才能进行交互。如果不是因为这个,它会特别容易,例如,当你输入另一个 page/tab.

时,让一个 page/tab 劫持你的密码

你需要的是 SharedWorker(不是 Service Worker,不同的东西)。您在之前链接的 MDN 页面中有一个完整的示例。

然而,根据 caniuse.com,localStorage 是一个更好的选择,考虑到兼容性来协调这样的小任务。对于您的具体情况,在 index.html:

<a href="example.html" rel="noreferrer" target="_blank">Open in another process</a>
<button>Close</button>
<script>
document.querySelector('button').onclick = () => {
  // Change the value if you want the storage event to be triggered.
  localStorage.setItem('close', Date.now());
};
</script>

现在里面 example.html:

<p>This page is in another process.</p>
<script>
window.addEventListener('storage', event => {
  if (event.key === 'close') { window.close(); }
});
</script>

希望对您有所帮助!

使用与我的回答相同的技术 。但是不要改变主 window 中的 dom 只需调用 window.close(); Example