Greg Morris

How To Open External Links In A New Tab By Default In Ghost

Updated: Added in non-jQuery code snippet

This problem is a reasonably simple one if you know what you are doing with writing Javascript. Unfortunately, I am not, and this feels like an issue that shouldn’t need some script, but here we are.

After loads of Googling, looking at Github Gist, and trial and error, I finally found a solution to opening new links in a new tab thanks to InsidersByte.

As they point out you can do this with markdown or adding in target=_blank to the end of each Url, but who has time for that? So add this into the footer of your site.

With jQuery


var links = document.links;

for (var i = 0, linksLength = links.length; i < linksLength; i++) { if (links[i].hostname != window.location.hostname) { links[i].target = '_blank'; } }

non-jQuery


 var links = document.querySelectorAll(‘a’);
 links.forEach((link) => {
 var a = new RegExp(‘/’ + window.location.host + ‘/’);
 if(!a.test(link.href)) {
 link.addEventListener(‘click’, (event) => {
 event.preventDefault();
 event.stopPropagation();
 window.open(link.href, ‘_blank’);
 });
 }
 });

You could do this in your theme template if you like, but the easiest way is to head to your dashboard, and then Settings > Code Injection. Copy and paste in the code and remember to save!

Reload your site, and you should be sorted.

Did you get value from this?

Consider supporting me by chipping in for a coffee. Buy Me A Coffee
Reply via: