Open External Links in a New Window - Ghost

Kirtan Thakkar

Kirtan Thakkar

Life is all about learning

Ghost, by default opens every link in the same window, even external. Like links from your blog posts pointing to some other websites are also opened in the same window. This takes your users away as they navigate away to a different website and might never come back. So, I found a workaround for this and here is the solution.

Solution

A little code snippet of JQuery can tune this settings without editing your theme files. Below is the code snippet:

<script>
// By default, Ghost opens links in the existing tab.
// Insert this in your Ghost code injection footer
// to get all your links to open in a new tab instead!
$(document).ready(function() {
$('a[href^=http]').each(function() {
// Get the current host and replace '.' with '\.'
var regex = '/' + window.location.host + '/';
regex = regex.replace(/\./g,'\\\.');
// Create a regular expression to check with link's href
var regexp = new RegExp(regex);
// If link is not from the current host add a jQuery on click function
// to open the link in a new window/tab
if(!regexp.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank'); // Open in a new window
});
}
});
});
</script>

I forked the original code snippet and added some spices to make it better.

  • Add this code snippet in the Blog Footer section in the Code Injection section from your Ghost Admin Panel and Save it. You are good to go!

Ghost Code Injection Blog Footer

This is safe for use with any #label you might be using or by your theme.

That's all. All your external links will open in a new window.