【问题标题】:Angular : sanitizing HTML stripped some content on css styleAngular:清理 HTML 剥离了一些 CSS 样式的内容
【发布时间】:2018-05-20 18:40:54
【问题描述】:

我在我的 Angular 组件中使用所见即所得的编辑器,当我尝试预览编辑器的内容时​​,(在我将中心应用于文本之后), 我收到这个警告:

警告:清理 HTML 会删除一些内容(请参阅 http://g.co/ng/security#xss)。
平台浏览器.es5.js:1015

当我检查 html 时:

<p>Text Here...</p>

但是当我尝试使用 console.log() 来预览编辑器的内容时​​,我得到:

<p style="text-align: center;">Text Here...</p>

【问题讨论】:

    标签: javascript html css angular


    【解决方案1】:

    出于安全原因,这是 Angular 2+ 中的设计。您可以使用DomSanitizer 类解决它。

    例如,您可以制作一个防止清理值的管道:

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
    
    @Pipe({ name: 'noSanitize' })
    export class NoSanitizePipe implements PipeTransform {
       constructor(private domSanitizer: DomSanitizer) {
    
       }
       transform(html: string): SafeHtml {
          return this.domSanitizer.bypassSecurityTrustHtml(html);
       }
    }
    

    然后你可以像这样在绑定中使用它:

    <div [innerHTML]="htmlText | noSanitize">
    </div>
    

    【讨论】:

    • 有没有办法在保留样式属性的同时去除危险内容的内容?
    • 谁能把这个放到 npm 上?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多