Caution!

This is an old post. Information here may be out-dated, or the post may re­flect opin­ions or be­liefs I no longer share.

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 find 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 ↩︎