[Angular] 使用Pipe來解決innerHTML造成的 sanitizing HTML stripped some content 錯誤
使用Angular嵌入HTML
會造成錯誤
因為ANGULAR架構會避免XSS攻擊
會對內容做編譯
這樣我們要呈現的內容就會被削掉
所以要使用自定義的pipe來消毒
讓內容可以轉換並呈現
https://stackoverflow.com/questions/39681163/angular-2-sanitizing-html-stripped-some-content-with-div-id-this-is-bug-or-fe
https://stackoverflow.com/questions/47681813/angular-sanitizing-html-stripped-some-content-on-css-style
html
<mat-card [innerHTML]="activeMeterApiFormat | sanitizeHtml"></mat-card>
ts
//#region 串cr004GetHtml API
this.cr004Service.cr004GetHtml$Json$Response(params).subscribe({
next: (res: any) => {
this.activeMeterApiFormat = Object.values(res.body.body!).toString();
},
});
//#endregion
Pipe
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);
}
}
留言
張貼留言