open url in new tab or reuse existing one whenever possible

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

How can I achieve this using 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.

Answers:

Answer

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.

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:

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.