While workĀ­ing on imĀ­proveĀ­ments to this site, I wanted to make sure any exĀ­terĀ­nal links would open not just in a new tab, but also seĀ­curely.

I chanced upon this snipĀ­pet shared by Bradley Gauthier on Sitecast.

The origĀ­iĀ­nal snipĀ­pet as at the time of this post:

(function() {
var links = document.links;
for (var i = 0, linksLength = links.length; i < linksLength; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = "_blank";
links[i].setAttribute("rel", "noopener noreferrer");
links[i].className += " externalLink";
} else {
links[i].className += " localLink";
}
}
})();

Since I ļ¬nd ES2015/ES6 conĀ­cise while siĀ­mulĀ­taĀ­neĀ­ously aidĀ­ing code readĀ­abilĀ­ity, I imĀ­proved the snipĀ­pet and inĀ­cluded it on my site.

Here is the ES2015 verĀ­sion:

(function() {
let links = document.links;
if (links.length) {
// links is an HTMLCollection, an array-like object.
// We cannot directly call the forEach method on it.
// We can use the same function through the Array prototype object.
Array.prototype.forEach.call(links, link => {
if (link.hostname != window.location.hostname) {
link.target = "_blank";
link.setAttribute("rel", "noopener noreferrer");
link.classList.add("externalLink");
} else {
link.classList.add("localLink");
}
});
}
})();

I did gain two bits of JavaScript knowlĀ­edge thanks to the origĀ­iĀ­nal snipĀ­pet and the re-write:

  • document.links[1] - creĀ­ate and reĀ­turn an HTMLCollection live obĀ­ject of all the links in the docĀ­uĀ­ment. This also reĀ­turns area elĀ­eĀ­ments!
  • One canĀ­not diĀ­rectly loop over an HTMLCollection[2] by callĀ­ing the forEach method on the colĀ­lecĀ­tion. One can, inĀ­terĀ­estĀ­ingly, use the same itĀ­erĀ­aĀ­tion funcĀ­tion through the Array proĀ­toĀ­type obĀ­ject to get around this limĀ­iĀ­taĀ­tion.

Footnotes

  1. https://ā€‹deĀ­velĀ­oper.mozilla.org/ā€‹en-US/ā€‹docs/ā€‹Web/ā€‹API/ā€‹DocĀ­uĀ­ment/ā€‹links ā†©ļøŽ

  2. https://ā€‹deĀ­velĀ­oper.mozilla.org/ā€‹en-US/ā€‹docs/ā€‹Web/ā€‹API/ā€‹HTMLĀ­ColĀ­lecĀ­tion ā†©ļøŽ