I personally prefer to handle this via vanilla JavaScript. If for whatever reason the JS doesn’t work there’s no great issue because links will still function. Perfect example of progressive enhancement.
I don’t set that Blackfriday option, as I prefer just middle clicking on a link if I need to open it in a different tab.
But I am curious what you are trying to do in that shortcode. I didn’t understand your problem statement, and the solution you achieved with that shortcode.
function handleExternalLinks() {
// Variables.
var links = document.links;
var linksLength = links.length;
var link;
var linkHref;
var hostname = window.location.hostname;
// Loop through all links.
for (var i = 0; i < linksLength; i++) {
// Instantite the indivdual link.
link = links[i];
// Get the link's href attribute.
linkHref = link.href;
// If the link is to an external site or a javascript:void(0);.
if (
link.hostname != hostname &&
linkHref !== 'javascript:void(0)' &&
linkHref !== 'javascript:void(0);'
) {
// Set the target of the link to _blank.
link.target = '_blank';
}
}
} // handleExternalLinks()
As I said, I’m not overly fussed with the backward compatibility of my JS because as far as I’m concerned this is a value add not a core feature. A jQuery implementation of this would be more robust.
I would recommend running this in the footer of every page via handleExternalLinks().
A much simpler version of this code can be found here.
@kaushalmodi My problem is that I want links to pages outside of my site to open in a new tab, but links to pages inside my site to open in the current tab.
The blackfriday option opens all links in a new tab, so I was thinking to either leave the blackfriday as is and put JS in my relref shortcode to open local links in the same tab.
I just don’t know how to do it or f it is even a good idea.
Hmm, based on the hrefTargetBlank documentation, I assumed that it already did that (As I mentioned above, I leave that option at the default false as I anyways middle click on links to open them in separate tabs.) …
Does it not work that way?
If not, then maybe:
Open an issue on Blackfriday repo
Looks like Blackfriday’s definition of “external link” is “not relative link”, which is bad IMO. At least in hugo docs, we should correctly document what hrefTargetBlank actually does… I’ll open an issue for that in hugoDocs. Done.