Optimize your browsing experience by opening URLs in new tabs or reusing existing URLs where possible
P粉939473759
2023-08-24 19:03:55
<p>Now I have a link</p>
<pre class="brush:php;toolbar:false;"><a href="blabla" target="_blank">link</a></pre>
<p>However, this always opens a new tab. I want the following effect</p>
<ol>
<li>If the user already has a tab with the same URL, please reuse the tab and refresh if possible</li>
<li>Otherwise, open a new tab</li>
</ol>
<p>How can I achieve this using JavaScript? </p>
<p>It's okay if there are only some browser-specific methods, so users without correspondingly supported browsers will "fall back" to the always-new-tab approach. </p>
Setting
target="child"
Will refresh the current tab (if already open)You can set the name of a specific window to open reused tabs. The problem is, as long as the href is the same, it won't reload. So you can't easily get the
refresh
part.For example, you can:
In JS you can actually get the same result using
window.open
. You can also use a url as thetarget
so you don't need to specify it manually:You can also generalize and add a click listener to the document so that certain links are opened this way. Something like this:
If the page is in the same domain, you may also try to refresh the page at this time.