[英]Angular - How to execute a script stored in a string with InnerHtml
我正在嘗試顯示一個 html 並執行一個腳本,它們都存儲在一個字符串中。
我創建了一個管道,它使用 this.sanitizer.bypassSecurityTrustHtml() 方法轉換字符串。
然后,我將字符串的內容注入到 innerHtml 屬性中,並將其與我的管道結合起來。
您可以在 stackblitz 上執行它: https ://stackblitz.com/edit/angular-uilj36
這是我的代碼的一部分:
安全管道.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
transform(value: any, args?: any): any {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public html = '<div>Html content</div> <script>console.log("run js ok");</script>';
}
app.component.html
<h1>Code injection :</h1>
<div [innerHtml]="html | safe"></div>
問題是腳本沒有執行。
有人知道為什么不執行腳本嗎?
PS:我知道不建議這樣做,但有人要求我這樣做:)
您也可以使用 iFrame 代替 div 元素。 在 iFrame 上,您可以設置 srcdoc 屬性。
<iframe [srcdoc]="html | safe"></iframe>
它應該顯示並運行帶有腳本的 html。如果要限制 iframe,可以使用沙箱屬性。
對於您的示例,它可能如下所示:
<iframe [srcdoc]="html | safe" sandbox="allow-scripts"></iframe>
iframe 是為諸如在隔離環境中執行腳本之類的安全事務而設計的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.