1 min read

How to Open External Links in a New Tab in Ghost CMS

When I first started writing posts for CreaDev Labs in my chosen content management system, Ghost, I noticed all the links in my posts would open up in my current browser tab. This was fine for internal links to other posts I’d written on CreaDev Labs, but links to external sites were opening in the same tab as well. I prefer links to external sites to open in a new tab so you can easily come back to CreaDev Labs and not lose your place.

I searched in the settings to see if there was a switch I could turn on to allow external links to open in a new tab, but there didn’t appear to be anything like that. I went to Google next to see if anyone else had a solution, and I found some code snippets people had written and put into the code injection section in Ghost. I gave those a try, but they weren’t working for me, so I ended up writing my own small code snippet:

<script type='text/javascript'>
  $( document ).ready(function() {
  	$(".gh-content a").each(function() {
    	if ($(this).attr("href").indexOf("https://creadevlabs.com") === -1) {
            $(this).attr("target","_blank");
        }
    })
  });
</script>

I added this to my site by going to Settings > Code Injection and including it in the Site Footer section. If you wanted to use this snippet on your Ghost site, you could simply copy it into the same section on your site, and change the part where it says creadevlabs.com to whatever your site’s url is. I don’t know for sure if the .gh-content class exists in every theme, so you might have to find out the class name of the content section by looking at it in your browser’s developer tools. At the time of writing this, I’m using the Dawn theme, so if you’re using that theme, this snippet should work for you without any problems.

If you run into issues implementing this, you can shoot me an email at brennan@creadevlabs.com or send me a message on LinkedIn.