Tip: Protect your users from malicious websites when using target="_blank"

HTML, Link, Security · Jun 12, 2021

Oftentimes, when linking to an external resource from our websites, we use target="_blank" to open the linked page in a new tab or window. But there is a security risk we should be aware of. The new tab gains limited access to the linking page (i.e. our website) via Window.opener, which it can then use to alter the linking page's URL via Window.opener.location (this is known as tabnabbing).

This might be a problem if the external resource is not trustworthy, might have been hacked, the domain has changed owners over the years etc. There is no guarantee that a third-party resource, no matter how trustworthy, can be actually trusted with our users' security and we, as developers, should always be aware of this risk.

<!-- Bad: susceptible to tabnabbing -->
<a href="https://externalresource.com/some-page" target="_blank">
  External resource

<!-- Good: new tab cannot cause problems  -->
  rel="noopener noreferrer"
  External resource

In order to prevent a link that is opened in a new tab from causing any trouble, we should always add the rel="noopener noreferrer" attribute to all of our target="_blank" links.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • Tip: Customize the names of downloadable files

    Learn what HTML5 attribute you can use to customize the names of your downloadable files with this quick tip.

    HTML, Link · Jun 12, 2021

  • 8 tips for accessible websites

    Accessibility (a11y) can improve your website and attract new users. Learn how to get started with these 8 quick tips.

    HTML, Accessibility · Jun 12, 2021

  • Tip: Lazy load images in HTML

    Discover how to improve your website's performance by implementing lazy loading for images using a native HTML attribute.

    HTML, Image · Jun 12, 2021