HomeBloggingGhostHow to Open External Links in a New Tab in Ghost

Unlike WordPress, Ghost uses a Markdown-based content editor instead of HTML-based. The content editor — just like the core of Ghost itself — also has a minimalist nuance. It offers pleasurable writing experience thanks to a sidebarless concept to minimize distractions. The minimalist concept of Ghost is also applied to content formatting. When writing a new blog post or page, you can add a link to a certain text, but there is no option to add an attribute to the link. You can’t, for instance, add a target attribute to open the link in a new tab (target=__blank).

Since Ghost offers no built-in option to add a target attribute to a link, you need to add a new function to open links (external links more precisely) in a new tab. You can use the following JavaScript snippet to add the function.

<script type="text/javascript">
    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');
            });
        }
    });
</script>

You can either add the code snippet about to the site header or footer. To do so, login to your Ghost dashboard (yoursite.com/ghost) and click the gear icon on the left panel to open the Settings screen. Once the Settings screen opens, click Code injection on the ADVANCED section.

Paste the code snippet above to the site header or site footer and click the Save button on the top-right corner.

From now on, all external links on your Ghost site will be open in a new tab, including links on the header navigation if you have one.

The Bottom Line

Ghost is a headless CMS that adopts a minimalist concept. Ghost offers minimum setting options in all areas, including text formatting on the content editor. There is no option to open a link in a new tab. There are probably some Ghost themes that offer this option. If you use a theme that doesn’t offer such an option, you can use the tip above to open external links in a new tab.

This page may contain affiliate links, which help support bettertechtips.com. Learn more