1

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

3
  • Why do you want to do this in a component? Commented Aug 17, 2022 at 19:17
  • Because I need the client to have passed the login first Commented Aug 17, 2022 at 19:51
  • Can't these scripts be imported using import? Commented Aug 17, 2022 at 19:53

1 Answer 1

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);
        }
    }
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.