'Add and remove chatbot script tags in Angular components to only show on certain pages

I would like to inject a chatbot <script></script>in certain of my Angular components, and when the user is about to navigate to a different component/URL, I would like to remove the <script></script> (if necessary?).

I had a look at using Renderer2 and other answers, but as I am only interested in appending a script, and not load a script file, I am not sure how to implement this, or whether these methods would work.

I know due to Angular security reasons, I cannot simply add it to my component HTML, so was thinking of using ngAfterViewInit() and ngOnDestroy() to inject and remove the script respectively.

Something like this to add the external script tags:

// Create the element

var script = document.createElement("script");

// Add script markup

script.innerHTML = "<script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=7e..."></script>";

// Append

document.body.appendChild(script);

I am a bit fuzzy regarding the usage of script.innerHTML = "<script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=7e..."></script>", and whether I am using it correctly.(?)

Alternatively, using this (if this would work, how can I add the script id (id="ze-snippet"):

  constructor(private renderer2: Renderer2, @Inject(DOCUMENT) private document) {}

  ngOnInit() {
    const s = this.renderer2.createElement('script');
    s.type = 'text/javascript';
    s.src = 'https://static.zdassets.com/ekr/snippet.js?key=7e...';
    s.text = ``;
    this.renderer2.appendChild(this.document.body, s);
  }

Any help would be appreciated!



Solution 1:[1]

Here is my question answered:

My alternate option above, using Renderer, worked perfectly. I simply had to add my id attribute.

This is my code with my imports:

import { Component, OnInit, Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-contact-us-page',
  templateUrl: './contact-us-page.component.html',
  styleUrls: ['./contact-us-page.component.scss']
})
export class ContactUsPageComponent implements OnInit {

  constructor(private renderer2: Renderer2, @Inject(DOCUMENT) private document) {}

  ngOnInit() {
    const s = this.renderer2.createElement('script');
    s.type = 'text/javascript';
    s.id = 'ze-snippet';
    s.src = 'https://static.zdassets.com/ekr/snippet.js?key=7e...';
    s.text = ``;
    this.renderer2.appendChild(this.document.body, s);
  }

}

Hope this helps someone else!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 onmyway