简体   繁体   中英

Angular - How to execute a script stored in a string with InnerHtml

I'm trying to display an html and execute a script which are both stored in a string.

I have created a pipe which transform the string with the this.sanitizer.bypassSecurityTrustHtml() method.

Then, I inject the content of the string in the innerHtml attribute and combine it with my pipe.

You can execute it on stackblitz : https://stackblitz.com/edit/angular-uilj36

This is a part of my code :

safe.pipe.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>

The problem is that the script doesn't execute.

Anybody have an idea why the script is not executed ?

PS : I know that it's not recommended but someone asked me to do it :)

You could also use an iFrame instead of a div element. On the iFrame you can set the srcdoc property.

<iframe [srcdoc]="html | safe"></iframe>

it should display and run the html with its scripts.If you want to restrict the iframe you can use the sandbox property.

For your example it could look like this:

<iframe [srcdoc]="html | safe" sandbox="allow-scripts"></iframe>

iframes are made for such security things like executing scripts in an isolated environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM