I have a trusted Javascript/Angular script in a string format that I would like execute in an angular component. I understant this is what the Domsanitizer bypassSecurityTrustScript() does. Angular Domsanitizer
However when try to run in my component nothing happens. How do i use this to run a js code from a string? This is what I have done so far is below and also in stackblitz Custom Script StackBlitz Thanks in advance.
mycomponent.ts
constructor(private domSanitizer: DomSanitizer)
test(){
let code: string = "console.log('Hello World')";
this.domSanitzer.bypassSecurityTrustScript(code);
}
bypassSecurityTrustScript
is not supposed to run anything. The only thing it does is wrapping the provided value into SafeScript so that when it is used in a template binding it bypasses sanitization.
It does not perform any transformations on the value.
Official documentation shows how similar values for styles, URLs, and HTML can be used. And that is where things get a bit weird.
It seems that it is possible to use the SafeScript value in the template like this:
<script [innerHtml]="safeScript"></script>
but indeed it does not work because Angular wipes out all <script>
tags from templates.
Please keep in mind that running JS from strings is a security risk, so you should think twice before doing it.
If there is no other way to perform that it is possible to go with a more "traditional" JS approachs to perform this, including eval
and Function constructor.
It is also possible to add a <script>
directly to the DOM (by using global document
object or Rendered)
import { Component, Renderer2, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";
//...
export class ButtonOverviewExample {
constructor(
private renderer: Renderer2,
@Inject(DOCUMENT) private document: HTMLDocument
) {}
test() {
const script = this.renderer.createElement("script");
this.renderer.setProperty(
script,
"text",
"console.log('Hello World')"
);
// It will add a new `<script>` on each call
this.renderer.appendChild(this.document.body, script);
}
}