Jotita
Jotita

Reputation: 33

load multiple script tag in angular component

I'm trying to load a series of scripts from a component of an angular application, I want to do it in a specific component and not in the index.html but I can't find a way to do it, any help or advice?

this is my code home.component.html

<div class="row">

 <div id="webchat" style="position: relative;z-index: 999999;"></div>

   <script>
      window.GB_SETUP={websocket_url: "wss://api-mychat.com", type:"config",
      channel: "6342", session_id: "34345", style:"343234"};
   </script>

   <script src="https://myscript.com/script.js"></script>
   <script src="https://myscript.com/script2.js"></script>


</div>

If I copy and paste as is in the index.html of the project it works great, but I want to do it inside a component

Upvotes: 1

Views: 803

Answers (1)

Angular ignores all script tags in templates for security reasons (to prevent cross-site-scripting / XSS).

To eliminate the risk of script injection attacks, Angular does not support the script element in templates. Angular ignores the script tag and outputs a warning to the browser console.

https://angular.io/guide/template-syntax#empower-your-html

As a workaround you could inject the script programmatically in your component's ts file, like so...

@Component({
...
})
export class HomeComponent implements OnInit {
    ...

    constructor(
         @Inject(DOCUMENT) private document: Document
    ) { }

    ngOnInit(): void {
        this.injectScript("https://myscript.com/script.js");
        this.injectScript("https://myscript.com/script2.js");
    }

    public injectScript(src: string) {
        if(this.document && src?.trim()) {
            const script = this.document.createElement("script");
            script.setAttribute("type","text/javascript");
            script.setAttribute("src",src.trim());
            this.document.head?.appendChild(script);
        }
    }
    ...
}

Upvotes: 1

Related Questions