/ javascript

Convert all external links to open in a new tab or window with JavaScript

A simple one-line javascript to automatically open all external links in a new tab or window

I recently migrated the blog to Ghost.org. The markdown renders the hyperlinks but does not automatically open the external link in a new tab or window. This affects your site's navigation and bounce rate.

As simple method to fix this is to add the following line to the page footer

Array.prototype.forEach.call(document.getElementsByTagName("a"), function(a) { if(a.hostname!=location.hostname) { a.target = "_blank"} })

i.e. On a Ghost blog, you can add the following script tag to: Code injection > Blog footer


<script type="text/javascript">
    Array.prototype.forEach.call(document.getElementsByTagName("a"), function(a) { if(a.hostname!=location.hostname) { a.target = "_blank"} })
</script>


How does it work?

The below is the same line as above, in a readable format

Array.prototype.forEach.call(
    document.getElementsByTagName("a"), 
    function(a) { 
        if(a.hostname!=location.hostname) { 
            a.target = "_blank"
        } 
    }
)

First we get all the hyperlinks on the page with: document.getElementsByTagName("a")

As specified in DOM4 it returns an HTMLCollection.

Then we use the Array iterator to itererate over the collection Array.prototype.forEach.call(...)

This takes two arguments. One is the collection and the other one is the callback function that accepts an element from that collection.

There are other parameters that the callback function can accept. Check the reference for Array.prototype.forEach

In the callback function we check whether the hostname for the link and the page is the same. If not, we set the _target to blank

function(a) {  // a  = <a href...> HTML element

    if(a.hostname!=location.hostname) { 
        a.target = "_blank"
    } 
}

Anup Shinde

Anup Shinde is Programmer, Algo Trader, Web Developer, Data Analyst and Machine-Learning researcher.

Read More
Convert all external links to open in a new tab or window with JavaScript
Share this

Subscribe to Anup Shinde