open url in new tab or reuse existing one whenever possible(在新标签中打开 url 或尽可能重用现有的)

本文介绍了在新标签中打开 url 或尽可能重用现有的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个链接

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

但是,这总是会打开一个新标签.我想要下面的效果

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

  1. 如果用户已有具有相同 URL 的选项卡,请重复使用该选项卡,并尽可能刷新
  2. 否则,请打开一个新标签

如何使用 JavaScript 实现这一点?

How can I achieve this using JavaScript?

如果只有一些特定于浏览器的方法也没关系,因此没有相应支持的浏览器用户将回退"到always-new-tab方式.

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.

推荐答案

你可以设置特定窗口的名称,以便打开重用选项卡.问题是,只要 href 相同,它就不会被重新加载.所以你不能轻易获得 refresh 部分.

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 refresh part easily.

因此,例如,您可以:

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

在 JS 中,您实际上可以使用 window.open 获得相同的结果.你也可以使用url作为target,这样你就不需要手动指定了:

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:

<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.

这篇关于在新标签中打开 url 或尽可能重用现有的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!