Tuesday, January 19, 2016

Forcing all links to open in a new tab

At my current work, we have a feature called custom pages. This feature provides a bare bones CMS for administrators to make custom page posts. We then display these posts inside an iframe. The iframe contents are served over https. However, users might publish links that serve up content over http. Unfortunately what will happen if a user tries to click the link in an evergreen browser is that the browser will block the link from navigating away. This effectively causes the iframe to display no content.

We were thinking of the best way to force all links to open in a new tab. We thought we had a few options:

  1. Modify all anchor tags to have a target="_blank" attribute
  2. Use an event handler to handle all click events on anchor tags to open a new tab
It turns out there is an even easier and more elegant option, the base tag. This tag has 2 attributes: href and target. The href attribute forces all anchor tags to use the specified value as the base url for all relative links. The target attribute forces all anchor tags to use that value for navigating. It's important to note that individual anchor tags can still override the value in the base tag.

So there you have it, force all links to open in a new window with a very simple html tag.