Azriz Jasni
Posted on May 1, 2019
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';
}
// 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>
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')
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
Posted on May 1, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.