When adding links to external sites in markdown there is no way to define that they should open up in a new windows - this is a simplification made in Markdown. In this site I create links to various resources and it’s desirable to open up those in a new window.
Out of the box it seems that Hugo is stripping out html links from the markdown when producing the static pages, so a workaround need to be done!
Possible ways to solve this would be to;
- Create a custom shorthand for this purpose
- Utilize Javascript to parse links on page and set target on external links only.
I’ve used to second way before with good results and know it’s a quick fix. I picked up a script from stack overflow that looked like it should do the trick.
(() => {
(document.querySelectorAll('a')).forEach(link => {
link.hostname !== location.hostname && link.setAttribute('target', '_blank');
})
})();
It basically queries for all links on the page and check the hostname of those. If it’s not the same as the current hostname it will add the target attribute on the link. There are nice scripts using jQuery but as I don’t use it on this site plain vanilla js is fine!
Note that you should not start parsing the links before the DOM has loaded.
I added this to /layouts/partials/extend_footer.html to override the templates own content (nice touch to have this empty template that makes it easy to extend the template functionality).