Angular 2, DomSanitizer, bypassSecurityTrustHtml, SVG

Я использовал DomSanitizer с SVG в строке HTML.

До текущей версии Angular это работало просто отлично:

this.domSanitizer.bypassSecurityTrustHtml(content);

Теперь я получаю объект обратно называется

SafeHtmlImpl {changingThisBreaksApplicationSecurity: "<svg> blah </svg>"}
changingThisBreaksApplicationSecurity

Есть ли теперь новый способ доступа к выводу DomSanitizer? Должен ли я получить его как тип SafeHTML или что-то? Какой смысл иметь bypassSecurityTrustHtml, если он все еще фильтрует html?

Есть ответы на открытку? Пожалуйста...

4 ответа

Решение

ДЕМО: https://plnkr.co/edit/Qke2jktna55h40ubUl8o?p=preview

import { DomSanitizer } from '@angular/platform-browser'

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    console.log(this.sanitized.bypassSecurityTrustHtml(value))
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div [innerHtml]="html | safeHtml">
    </div>
  `,
})
export class App {
  name:string;
  html: safeHtml;
  constructor() {
    this.name = 'Angular2'
    this.html = "<svg> blah </svg>";
  }
}

Использование DomSanitizer.bypassSecurityTrustHtml:

constructor(private sanitizer: DomSanitizer) {
}

let html = this.sanitizer.bypassSecurityTrustHtml("<svg> blah </svg>");

Дополнительная информация: https://angular.io/docs/ts/latest/guide/security.html.

По этому вопросу вы можете посетить здесь

Мы можем добавить специальную продезинфицированную трубу и использовать ее по всему миру. Если ваш HTML не очищен должным образом, тогда внутренний HTML игнорирует svg, сторонний URL и т. д., поэтому мы можем исправить это, как показано ниже:

hero.component.html :

      <div [innerHTML]="htmlString | sanitizedHtml"></div>

hero.component.ts

      import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-hero',
    templateUrl: './hero.component.html',
    styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
    htmlString: any;

    constructor() { }

    ngOnInit(): void {
        this.htmlString = `
        <div class="container">
            <header class="blog-header py-3">
            <div class="row flex-nowrap justify-content-between align-items-center">
                <div class="col-4 pt-1">
                <a class="text-muted" href="#">Subscribe</a>
                </div>
                <div class="col-4 text-center">
                <a class="blog-header-logo text-dark" href="#">Large</a>
                </div>
                <div class="col-4 d-flex justify-content-end align-items-center">
                <a class="text-muted" href="#">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mx-3"><circle cx="10.5" cy="10.5" r="7.5"></circle><line x1="21" y1="21" x2="15.8" y2="15.8"></line></svg>
                </a>
                <a class="btn btn-sm btn-outline-secondary" href="#">Sign up</a>
                </div>
            </div>
            </header>
        </div>`;
    }
}

продезинфицированный-html.pipe.ts

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

@Pipe({
    name: 'sanitizedHtml'
})
export class SanitizedHtmlPipe implements PipeTransform {
    constructor(private sanitized: DomSanitizer) {}

    transform(value: any): any {
        return this.sanitized.bypassSecurityTrustHtml(value);
    }
}

Выход:

Это также можно сделать с помощью обозначения объектных скобок:

let safeHtml = this.domSanitizer.bypassSecurityTrustHtml(content);
console.log(safeHtml["changingThisBreaksApplicationSecurity");

Пришлось сделать это, потому что safeHtml.changingThisBreaksApplicationSecurity у меня не сработало.

Другие вопросы по тегам