2017-03-16 105 views
2

爲什麼ElementRef不安全使用,如果有的話,我們可以用什麼來代替?ElementRef安全風險角度2

我一直在使用這個ElementRef來查看或觀察一個特定的html標籤,然後在初始化後以特定寬度發送,但是如果這打開了安全風險,我不會使用它,並且說實話,不明白爲什麼角色2團隊在他們的框架中允許這種安全缺陷。

什麼是安全和最好的技術使用?我的測試組件的下方:

 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() { 
      } 

     } 

角2頁參考:

https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html

+0

看看[此博客文章](http://angularjs.blogspot.com.tr/2016/04/5-rookie-mistakes-to-avoid-with-angular.html) – ulubeyn

+0

推薦解決方案你的鏈接仍然使用ElementRef,不知道它是否安全 – jcdsr

+1

風險不是一個缺陷。 Angular沒有引入風險。它與'ElementRef'本身無關。你的代碼不會做任何冒險的事情。 – zeroflagL

回答

1

使用ElementRef不會直接使您的網站的安全性較低。 Angular團隊只是說「嘿,你可以用這個,只是要小心」

如果您只使用ElementRef得到信息,就像您的示例中的寬度一樣,根本不存在安全風險。當您使用ElementRef修改DOM時,情況會有所不同。那裏可能會出現潛在的威脅。這樣的例子可以是:

@ViewChild('myIdentifier') 
myIdentifier: ElementRef 

ngAfterViewInit() { 
    this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser; 
} 

這裏的問題是,它被直接插入DOM,跳過角禁制機制。什麼是衛生機制?通常,如果通過Angular更改DOM中的某些內容,Angular確保它沒有危險。但是,在使用ElementRef向DOM中插入內容時,Angular不能保證這一點。所以它變成你的責任,沒有什麼不好的東西進入DOM時使用ElementRef。這裏一個重要的關鍵字是XSS(跨站腳本)。

總結:如果您爲DOM查詢信息,您是安全的。如果您使用ElementRef修改DOM,請確保修改不會包含惡意代碼。