代码之家  ›  专栏  ›  技术社区  ›  Mike Me

忽略用户注入的HTML,但呈现开发人员的HTML-Angular

  •  0
  • Mike Me  · 技术社区  · 6 年前

    如果我有以下T&C:

    <p>The company USERCOMPANY will have the responsibility to accept the T&C</p>
    

    *用户公司将被用户公司替换的位置

    <strong>My Company</strong> 还是js脚本?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Agash Thamo.    6 年前

    如果两个都单独存储,则可以使用(quick和dirty)转义USERCOMPANY中的值:

    USERCOMPANYstring.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    

    safe 管道: <p [innerHTML]="yourVariable | safe: html"></p>

    安全管道:

    import { Pipe, PipeTransform } from "@angular/core";
    import {
      DomSanitizer,
      SafeHtml,
      SafeStyle,
      SafeScript,
      SafeUrl,
      SafeResourceUrl
    } from "@angular/platform-browser";
    
    @Pipe({
      name: "safe"
    })
    export class SafePipe implements PipeTransform {
      constructor(protected sanitizer: DomSanitizer) {}
    
      public transform(
        value: any,
        type: string
      ): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
        switch (type) {
          case "html":
            return this.sanitizer.bypassSecurityTrustHtml(value);
          case "style":
            return this.sanitizer.bypassSecurityTrustStyle(value);
          case "script":
            return this.sanitizer.bypassSecurityTrustScript(value);
          case "url":
            return this.sanitizer.bypassSecurityTrustUrl(value);
          case "resourceUrl":
            return this.sanitizer.bypassSecurityTrustResourceUrl(value);
          default:
            throw new Error(`Invalid safe type specified: ${type}`);
        }
      }
    }