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 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 />```
Thanks for sharing, I just do the same with an improved code on a similar topic, because origin.indexOf(domain) === -1
can be bypassed.
If your domain is
example.com
, a malicious link tobadexample.com
would match becauseindexOf
finds the substring and returns a position (not -1)
Perhaps the topics can be merged mixing the different techniques and detailing their pro/cons.