During QA on almost every web project I’ve worked on, a time comes when somebody files a bug report like this:
These links should open in a new window.
I usually try to have a conversation with them about how opening links in a new window is unexpected behavior, it can be jarring, we should let users decide how to use their browser, et cetera, but I have never won that battle and always end up implementing target="_blank"
.
On one project I inherited though, a bunch of links were already opening in a new window. I was doing an accessibility audit and remediation. In order to keep the links opening in a new window and meet WCAG guidelines, links that opened in a new window needed:
rel="noopener noreferrer"
for securityInstead of combing through the markup to add this, I created a small JavaScript module that would accomplish all three. Here’s how I did it.
In our initialization, we need two things:
You can get the current host with JavaScript easily with window.location.host
. We’ll use this to compare each link to.
To grab all the links, we can use an attribute selector that targets the href
attribute. We already know we only want external URLs so we’ll grab elements with an href that starts with http
.
// This will grab every single <a> on the page
document.querySelectorAll('a');
// This will grab only <a> elements that have
// a full url in the href, either http or https
document.querySelectorAll('a[href^="http"]');
#web-development #javascript #technology #accessibility