Is there a way to get all external links to open in a new tab?

I use Ghost for my blogging platform. I am trying to figure out why my external links all open in the same browser tab.

Is there a way to get all external links to open in a new tab?

I had the same question recently and added this into my site footer code injection. This works for eternal links which should always be opened in a new tab anyhow.

Hope it works for you!

<script>
    // Open external links. For site footer code injection
    const domain = window.location.hostname;
	const anchors = document.querySelectorAll('a[href]'); // Only select links with href attribute
 
    anchors.forEach(anchor => {
        const { origin } = new URL(anchor.href); // Get link origin
 
        if (origin.indexOf(domain) === -1) { // Check if external link
            anchor.setAttribute('target', '_blank');
            anchor.setAttribute('rel', 'noopener noreferrer'); // This is a good practice to avoid tabnabbing
        }
    })
</script><br />```
3 Likes