html - 如何在 Angular 5 中防止 html 注入(inject)

标签 html angular typescript sanitization

我想阻止用户在文本框中输入 html 注入(inject)。我研究了一些例子,但它们通常是关于允许 html 标签通过管道并说 Angular 自动清理 html 标签。但在我的示例中,当我输入 <script>alert('blabla')</script> 时到文本框,它被接受并注册到数据库,如下所示..

如何预防?

我的模板代码是:

<div fxLayout="row">
          <mat-form-field fxFlex="20">
            <input matInput name="label" [(ngModel)]="product.label" placeholder="Label"
                   required>
          </mat-form-field>
        </div>

我的 ts 文件是:

import { Product } from '../../../';

@Component({
  selector: '....',
  templateUrl: '....',
  styleUrls: ['....']
})
export class ProductEditComponent implements OnInit {

  product: Product = <Product>{};

  constructor(some services etc.) {

  }

  ngOnInit() {

   //some code
  }

再次注意:我想阻止进入html脚本注入(inject),不允许使用旁路或管道...

最佳答案

您可以使用 DomSanitizer 来实现此目的

import { DomSanitizer } from "@angular/platform-browser"
import { SecurityContext } from "@angular/core";

constructor(private sanit:DomSanitizer){
  var dom = this.sanitizer.sanitize(SecurityContext.HTML, "<script> alert('HELLO'); </script>");
  console.log(dom);
}

如果返回null,那么就是html的问题,否则返回传递的html

关于html - 如何在 Angular 5 中防止 html 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55848070/

相关文章:

html - 在填充父容器的 div 内创建一个可滚动区域?

css - 如何解决错误 'The name of the class AccordionGroup should end with the suffix Component'

json - 在类中使用 RxJs Subject 时 JSON.stringify 上的循环对象异常

html - 试图将文字放在图片下方,但文字太低了

php - 从 PHP 数组制作 HTML 列表?

node.js - 全新安装 npm 和 Node

html - 不要在一个特定的输入上包含 css 样式

javascript - TS 2 数组,如果第一个数组中的项目存在于第二个数组中,则附加到第二个数组的开头

typescript - Ionic 2 与 Stripe 集成

javascript - JQuery Double Scroll - 边距/对齐问题