Why ElementRef is not secure to use if so, what we can use instead?
I'm been using this ElementRef to see or watch a specific html tag and then to send as specific width after is initialize, but if this open a security risk I will not use it, and to be honest I don't understand why angular 2 teams allow this kind security flaws in their framework.
What is the secure and best technique to use? My test component below:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-standard',
template: ` <button type="button" #buttonW></button>`,
})
export class standardComponent implements OnInit {
name: string = 'app-standard';
viewWidthButton: any;
@ViewChild( 'buttonW' ) elButtonW: ElementRef;
constructor() {
this.viewWidthButton = this.elButtonW.nativeElement.offsetWidth;
console.log ('button width: ' + this.viewWidthButton);
}
ngOnInit() {
}
}
Angular 2 page reference:
https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html
Using ElementRef
doesn't directly make your site less secure. The Angular team is just saying "Hey, you may use this, just be careful with it".
If you are only using an ElementRef
to get information, like in your example a certain width, there is no security risk involved at all. It's a different story when you use an ElementRef
to modify the DOM. There, potential threats can arise. Such an example could be:
@ViewChild('myIdentifier')
myIdentifier: ElementRef
ngAfterViewInit() {
this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;
}
The problem with this is that it gets inserted directly into the DOM, skipping the Angular sanitisation mechanisms. What are sanitisation mechanisms? Usually, if something in the DOM is changed via Angular, Angular makes sure it's nothing dangerous. However, when using ElementRef to insert something into the DOM, Angular can't guarantee this. So it becomes your responsibility that nothing bad enters the DOM when using ElementRef
. An important keyword here is XSS (Cross-Site Scripting).
To summarise: If you poll the DOM for information, you are safe. If you modify the DOM using ElementRef
, make sure the modifications don't possibly contain malicious code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With