Make all external links open in a new tab with Javascript
On this page
A common client request I get is to make all the external links on a page open in a new tab. However, if the client's site has many pages, manually editing all the links can be very time-consuming.
For those scenarios, I like to rely on Javascript, even if for the short term. You can use the following snippet: it automatically modifies all external links on a page to open in a new tab.
document.querySelectorAll('a').forEach(a => {
if (a.hostname && a.hostname !== location.hostname) {
a.setAttribute('target', '_blank');
}
})
Simple but effective!