DEV Community

Azriz Jasni
Azriz Jasni

Posted on • Edited on

Secure your apps with Angular Directive when using target='_blank'

Hi, today I want to share with you guys on how to secure your apps if you are using target='_blank'.

Usually to link an external url, we will do something like this:
<a href='https://dev.to'>Dev.to</a>.Please noted that this will still work. But unfortunately there is an security issues here.You can read more about it here and it also included with example:
https://mathiasbynens.github.io/rel-noopener/#hax

To solve this issue we can simply add an extra attribute to anchor tag.
<a href='https://dev.to' rel='noopener noreferrer'>Dev.to</a>.

However, let say in our app we have a lot of external link to put.
And personally, I dont really like to write rel='noopener noreferrer' to every anchor tag I have.

With that, we can automatically add rel='noopener noreferrer' to every anchor tag with Angular Directive.

// target-blank.directive.ts import { Directive, HostBinding } from '@angular/core'; @Directive({ // target every <a target="_blank">...<a> selector: 'a[target=_blank]', }) export class TargetBlankDirective { // will add <a ... rel='noopener noreferrer'>...</a> @HostBinding('attr.rel') rel = 'noopener noreferrer'; } 
Enter fullscreen mode Exit fullscreen mode
// and just use it like this <a href='someurl' target='_blank'>someurl</a> // will render like this <a href='someurl' target='_blank' rel='noopener noreferrer'>someurl</a> 
Enter fullscreen mode Exit fullscreen mode

One last thing, let say you have dynamic action on click. How would we want to prevent this.

function openInNewTab(url: string): void { // open link in new tab const newTab = window.open(url, '_blank') // set opener to null so that no one can references it newTab.opener = null } openInNewTab('https://dev.to') 
Enter fullscreen mode Exit fullscreen mode

You can play around here

In conclusion:

Pro Cons
Automatically add rel='noopener noreferrer' New Developer unaware of this directive behaviour
Able to prevent this issue automatically Client disable JS

You can read more here
https://www.pixelstech.net/article/1537002042-The-danger-of-target%3D_blank-and-opener

Top comments (4)

Collapse
 
jedi_zaidi profile image
Ahmad Zaidi • Edited

simple yet crucial! thanks for sharing!

if you're using vue, you can do this by simply creating component with rel="noopener norefferer" specified on the anchor tag.

Collapse
 
maslow profile image
Maslow

I think you made a typo. You typed ref='noopener noreferrer' 3 times instead of "rel".

Collapse
 
azrizhaziq profile image
Azriz Jasni

Thank man, appreciate your sharp πŸ‘€

Collapse
 
bmitchinson profile image
Ben Mitchinson

Thanks for this!