Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute trusted script

Here is a minimalistic example of a component

export class AppComponent {

  htmlSnippet: string;

  constructor(private sanitizer: DomSanitizer) {
    this.htmlSnippet = this.sanitizer.sanitize(
      SecurityContext.HTML,
      `<p>snippet works!</p><script>alert("ddd");</script>`
    );
  }
}

and template

<p>app works!</p>

<div [innerHTML]="htmlSnippet"></div>

All the content is rendered. CSS works as well if any.

enter image description here

Is there a way to execute that alert?

like image 350
Taras Hupalo Avatar asked Jun 23 '26 01:06

Taras Hupalo


1 Answers

you can just create the script tag and append that to the body of the component

  constructor(private renderer2: Renderer2, private el: ElementRef) {}

  ngAfterViewInit() {
    let scriptEl = document.createElement("script");
    scriptEl.innerText = "alert('hello')";

    this.renderer2.appendChild(this.el.nativeElement, scriptEl);
  }

demo 🚀

according to this issue you can't put a script tag in the body of the template because it going to be removed the only way around this is to insert the script tag dynamically as above.

like image 170
Muhammed Albarmavi Avatar answered Jun 25 '26 19:06

Muhammed Albarmavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!