首页 > 解决方案 > Angular 的 bypassSecurityTrustHtml 管道如何在后台工作?

问题描述

我使用了各种SafeHtml管道,但我想知道它实际上是如何工作的。Angular 如何知道应用于 DOM 的文本已经通过管道传递并且是安全的?它只是在编译阶段完成还是运行时检查?

文档说:

调用任何 bypassSecurityTrust... API 都会禁用 Angular 对传入值的内置清理

安全 HTML 管道的常见实现:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({name: 'sanitizeHtml'})
export class SanitizeHtmlPipe implements PipeTransform {
  constructor(private _sanitizer:DomSanitizer) {
  }
  transform(v:string):SafeHtml {
    return this._sanitizer.bypassSecurityTrustHtml(v);
  }
}

更新:dom_sanitization_service.ts 源中找出来。该bypassSecurityTrustHtml函数返回一个new SafeHtmlImpl(value);实例。在此sanitize过程中,有一个检查:if (value instanceof SafeHtmlImpl),如果是,则跳过清理过程

标签: angular

解决方案


我认为你误解了函数的意义。它实际上并没有清理,它甚至不检查 HTML。它所做的只是创建一个设置了标志的对象,因此 Angular 安全性不会阻止它。如果字符串包含不安全的 HTML,则不会被阻止。

开发人员仍然应该自己编写一些函数或使用其他一些工具来确保 HTML 是安全的。


推荐阅读