If you are using the Ghost CMS for your site you will notice that there isn't a possibility in the Post or Page editor to change link settings. Therefore, the HTML target
attribute can't be set to _blank
to open external links in a new tab or window.
Solution 1: Add HTML block (local)
A first simple solution is by adding external links in a separate HTML code block in the editor with the target="_blank"
property:
This trick works with out-of-the-box tools and without adding or changing the code, but in my opinion it is more a workaround instead of a great solution because every external link has to be replaced with this code block.
Solution 2: Add small JavaScript (jQuery) script (global)
A more simple and backward compatible solution for old posts and pages is by adding a small JavaScript code block that will add the target="_blank"
property to the links. While Ghost uses jQuery by default, we can create a simple jQuery script and add this directly in the theme or in the Ghost backend in the Settings > Code injection > Site Footer part.
To add the target attribute to every link you can simply use:
<script type="text/javascript">
$(document).ready(function() {
$("a").attr("target", "_blank");
});
</script>
This works great but you will notice that this script adds the target attribute to all links. To only add it to external links we have to adjust the $("a")
part by filtering out every internal link. Further, the rel="noopener noreferrer"
attribute should be added to prevent window.opener
reference. This results in the following code:
<script type="text/javascript">
$(document).ready(function() {
$("a").each(function(){
if(this.href.indexOf(window.location.host) == -1) {
$(this).prop({
target: "_blank",
rel: "noopener noreferrer"
});
}
})
});
</script>
Due to the window.location.host
property you don't have to worry about moving your site to another host: It will work directly in your installation!
By the way: This code snippet is also used here in our blog. Just try it by clicking on some links.
References
- Logo in the header image: Ghost Logo