Search code examples
javascriptjqueryhtml

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

  1. http://www.legworkstudio.com/interactive/laika-the-boxtrolls
  2. http://www.legworkstudio.com/interactive/kentucky-fried-chicken
  3. http://www.legworkstudio.com/interactive/newton-run-better
  4. http://www.legworkstudio.com/interactive/coke-ahh-effect

Solution

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

    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.