I want my external links to open in a new tab

I was successfully using this non-jQuery code snippet injected in the Ghost site footer:

<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>

This doesn’t name the tab, but checks if the URL is external and only then opens in a new tab.

17 Likes