Search code examples

Opening external links in the same new tab

How to open external links in the same new tab in the same browser window ?

( i.e. first click in an external link triggers a new tab, but subsequent clicks on the external links open up in that same tab without creating additional tabs in the browser window )

Example : See how LegWorkStudio doing it in their portfolio in between the following links



  • Opening external links in the same new tab can be a bit tricky due to browser security policies, but it's possible with JavaScript only when the external linked files are in the same server (Remote or localhost).

    <!DOCTYPE html>
    <html lang="en">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>External Links</title>
        <a href="./link1.html" class="external-link">External Link 1</a>
        <a href="./link2.html" class="external-link">External Link 2</a>
            document.addEventListener('DOMContentLoaded', (event) => {
                let externalTab;
                document.querySelectorAll('a.external-link').forEach(link => {
                    link.addEventListener('click', function(event) {
                        const url = this.href;
                        if (!externalTab || externalTab.closed) {
                            externalTab =, '_blank');
                        } else {
                            externalTab.location.href = url;

    The above example contains two external links with the class external-link. Below are the step-by-step solution used:

    1. The script waits for the DOM content to load before running
    2. It selects all links with the class external-link
    3. It adds an event listener to each link that:
      • a. Prevents the default behavior (opening in a new tab).
      • b. Checks if the external tab exists or if it is closed:
        • I. If it doesn't exist or is closed, it opens a new tab
        • II. If it exists and is open, it changes the location of the existing tab to the new URL
      • c. Focuses on the external tab

    This ensures that the first click opens a new tab, and subsequent clicks reuse that same tab for external links.