Open external links in new tab or window in Ghost

An easy way is to add a code snippet into our site using Ghost's code injection feature.

Open external links in new tab or window in Ghost

At the time of writing, the Ghost content editor does not support customizing of links, such as adding attributes to allow external links to open in a new tab or window. However, we can still achieve this through code injection (or editing theme files), so here's how.

What the code snippet does

First, we find all the link <a> elements in the post content, and compare the url hostname value to that of the blog. Then, set the target attribute to _blank and rel attribute to noreferrer noopener(read this on why).

If you wish to include links in the menu navigation as well, check out the end of this article.

Option 1:

  • You have a theme(e.g. Casper) installed that comes with jQuery
<script>
typeof $ !== 'undefined' && $(function () {
  $('.gh-content a').filter(function () {
    return this.hostname && this.hostname !== location.hostname;
  }).attr({
    target: '_blank',
    rel: 'noreferrer noopener'
  });
});
</script>
💡
Ghost does not ship with jQuery, but the default theme Casper does. If you chose the Option 1 and switch to a theme that does not include jQuery, this will not work.

Option 2 (preferred):

  • Does not require jQuery
  • Backwards compatibility for browsers
<script>
(function () {
  var list = document.querySelectorAll('.gh-content a');
  for (var i = 0; i < list.length; i++) {
    var a = list[i];
    if ((a === null || a === void 0 ? void 0 : a.hostname) !== location.hostname) {
      a.rel = "noopener noreferrer";
      a.target = "_blank";
    }
  }
})();
</script>

This is a prudent approach so definitely my preferred choice.

💡
This snippet is supported on most browsers, including IE9. Check out the browser support for document.querySelectorAll here.

Place the code snippet

  1. Go to your "Settings" page (the gear icon in the side bar)
  2. Under "Advanced", go to "Code injection"
  3. Copy and paste the code into under "Site Footer" (so that the code is executed after the DOM has loaded)
  4. Click "Save"
Example of how it will look like
💡
You could also add code directly to default.hbs in the theme files if you have access to them. If you prefer to do so, add the code before {{ghost_foot}}.

Add the .nav a selector to the querySelectorAll function like so, separated by a comma:

<script>
(function () {
  var list = document.querySelectorAll('.gh-content a, .nav a');
  for (var i = 0; i < list.length; i++) {
    var a = list[i];
    if ((a === null || a === void 0 ? void 0 : a.hostname) !== location.hostname) {
      a.rel = "noopener noreferrer";
      a.target = "_blank";
    }
  }
})();
</script>

Bonus: ES6 version

Array.from(document.querySelectorAll('.gh-content a'))
    .filter(a => a?.hostname !== location.hostname).forEach(a => {
        a.rel = "noopener noreferrer";
        a.target = "_blank";
    })