Javascript 在新选项卡中打开 url 或尽可能重用现有的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13779508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:52:53  来源:igfitidea点击:

open url in new tab or reuse existing one whenever possible

javascripthtmltabs

提问by Xiao Jia

Now I have a link

现在我有一个链接

<a href="blabla" target="_blank">link</a>

However, this always open up a new tab. I want the following effect

但是,这总是会打开一个新选项卡。我想要以下效果

  1. If the user already has a tab with the same URL, reuse that tab, and refresh if possible
  2. Otherwise, open a new tab
  1. 如果用户已有具有相同 URL 的选项卡,请重用该选项卡,并尽可能刷新
  2. 否则,打开一个新标签

How can I achieve this using JavaScript?

如何使用 JavaScript 实现这一目标?

It's OK if there're only some browser-specific methods, so users of browsers without corresponding support will "fallback" to the always-new-tab way.

如果只有一些特定于浏览器的方法也可以,因此没有相应支持的浏览器用户将“回退”到 always-new-tab 方式。

回答by ZER0

You can set specific window's name, in order to open reuse the tab. The problem is, as far as the href will be the same, it won't be reloaded. So you can't obtain the refreshpart easily.

您可以设置特定窗口的名称,以便打开重复使用该选项卡。问题是,只要 href 相同,就不会重新加载。所以你不能轻易获得refresh零件。

So, for instance, you can have:

因此,例如,您可以拥有:

<a href="blabla" target="blabla">link</a>
<a href="foo" target="bar">link</a>

In JS, you can actually obtain the same, using window.open. You could also use the url as target, so that you don't need to specify manually:

在 JS 中,您实际上可以使用window.open. 您也可以使用 url as target,这样您就不需要手动指定:

<a href="blabla" onclick="window.open(this.href, this.href); return false">link</a>
<a href="foo" onclick="window.open(this.href, this.href); return false">link</a>

You could also generalize, and add a click listener to the document, in order to open some links in this way. Something like:

您也可以概括,并在文档中添加一个单击侦听器,以便以这种方式打开一些链接。就像是:

<div id="container">
    <a href="blabla">link</a>
    <a href="foo">link</a>
</div>

<script>
    document.getElementById("container").onclick = function(evt){
        if (evt.target.tagName === "A")
            window.open(evt.target.href, evt.target.href);

        return false;
    }
</script>

If the page are on the same domain, at this point you could probably trying to do an empiric refresh of the page as well.

如果页面在同一个域中,此时您可能也可以尝试对页面进行经验刷新。