Defending Against Tabnabbing
What you'll learn: How to prevent malicious pages from hijacking your site's tabs using three simple but powerful defensive techniques.
The Defense Strategy
Now that you understand how tabnabbing works, let's lock it down. The good news: preventing tabnabbing is straightforward and involves three complementary layers of defense.
1. Use rel="noopener noreferrer"
When you add a link with target="_blank", always include the rel attribute:
<a href="https://external-site.com" target="_blank" rel="noopener noreferrer">
Visit External Site
</a>
noopener: Prevents the new tab from accessingwindow.opener, cutting the control channel entirelynoreferrer: Additionally prevents the destination from seeing where the user came from (via theRefererheader)
Analogy: It's like giving someone directions to another building but not handing them the key back to your office.
2. Set window.opener to Null in JavaScript
If you're opening windows programmatically:
const newWindow = window.open('https://external-site.com', '_blank');
if (newWindow) {
newWindow.opener = null;
}
This manually severs the connection even if rel="noopener" wasn't set.
3. Configure Content Security Policy (CSP)
While CSP doesn't directly prevent tabnabbing, it limits what an attacker can do if they successfully redirect your tab:
Content-Security-Policy: default-src 'self'; frame-ancestors 'none';
This prevents your login page from loading malicious scripts or being framed, reducing the damage from a successful tabnabbing attack.
Key Takeaway: Defend against tabnabbing by always using rel="noopener noreferrer" on external links, setting window.opener = null in JavaScript window opens, and strengthening your site's CSP to limit post-redirect damage.