Setting the "target
" attribute to "_blank
"
The simplest way to open links (anchor tags) in a new tab is by using the target="_blank"
declaration (which you should use with rel="noopener"
):
<a href="https://example.com" target="_blank" rel="noopener">Example</a>
While the MDN docs state that:
Setting
target='_blank'
on<a>
elements now implicitly provides the samerel
behavior as settingrel='noopener'
which does not setwindow.opener
.
The rel="noopener"
declaration should be used explicitly because it prevents security flaws caused by the incorrect use of the target="_blank"
declaration, and because not all browsers enable this implicit behaviour. Read more about this here.
You should also keep in mind that using target="_blank"
will change the default behaviour of the browser and consider how using it will affect your project's UX.
Note: "_blank" is not a typo, "blank" and "_blank" are two different values.
When set to "_blank"
the target
attribute will always open links (anchor tags) in a new tab when clicked. While target="blank"
will open the first-clicked link in a new tab, but any future links that share target="blank"
will open in that same tab.
Opening links in new tabs using JavaScript
For those of you who aren't using standard HTML links, you could use elements that look and behave like anchor tags.
<button data-href="https://example.com">Example</button>
You'd then implement their behavior using the window.open
method:
for (const link of document.querySelectorAll("[data-href]")) {
link.addEventListener("click", () => {
window.open(link.getAttribute("data-href"), "_blank");
});
}
Keep in mind that you could also use the above code with actual anchor tags:
<a class="custom" href="https://example.com">Example</a>
Although you'd have to use event.preventDefault
to overwrite existing behaviour:
for (const link of document.querySelectorAll("a.custom")) {
link.addEventListener("click", event => {
event.preventDefault();
window.open(link.getAttribute("href"), "_blank");
});
}
Once again, you should consider how changing default behaviours will affect the user's experience.