Code: Forcing Links In A New Tab

Web Developers Workstation

I’m often asked to make sure all external links open in a new browser window/tab. It’s our clients way of telling users you’re going to do what ever i want you to do.

Of course we explain to them why this practice is considered bad for usability as it allows the website to take control of the end users browser by forcing a new tab to open. However, we also understand the marketing implications of moving away from our clients site and loosing that all important brand touch point.

Sadly this conversation always seems to happen after we’ve just spent hours adding their content into the development site, but luckily we’ve come up with an elegant solution involving only a few lines of Javascript.

The Code

This snippet will add target=”_blank” to all external links on a page and force PDFs to open in a new window/tab as well. Replace mydomainname with yours so it knows which domain name to skip for internal links.