iBlehhz
iBlehhz

Reputation: 586

(Angular 2/4/5/6) Adding tawk widget to specific pages in Angular 6

Solution:

I got my solution here How to load external scripts dynamically in Angular?

And I checked for my path in app component to load the script accordingly.

import { Component, OnInit } from "@angular/core";
import { NavigationStart, Router } from "@angular/router";
import { Subscription } from "rxjs";
import { ScriptService } from "./shared/script.service";
import { Location } from "@angular/common";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent implements OnInit {
  constructor(
    router: Router,
    private location: Location,
    public script: ScriptService,
  ) {}

  ngOnInit() {
    if (!this.location.path().includes("admin")) {
      // load script for tawk widget
      this.script.load("tawk").catch(error => console.log(error));
    }
  }
}

Previous Question:

I have difficulties adding the tawk widget to specific components in the angular 6 project. If I add it to index.html page below app-root, it shows up in all pages of the project. Is there any other way of doing it?

Sample code:

<!--Start of Tawk.to Script-->
<script type="text/javascript">
    var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
    (function(){
    var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
    s1.async=true;
    s1.src='https://embed.tawk.to/17f35g40afc2c34e96e75909/default';
    s1.charset='UTF-8';
    s1.setAttribute('crossorigin','*');
    s0.parentNode.insertBefore(s1,s0);
    })();
</script>
<!--End of Tawk.to Script-->

Sample code taken from here ---> Integrating tawk.to into Angular 6 (Angular 2) app

I've tried the following site, Adding JavaScript File to Angular 4 Component but it still shows up for every page. Appreciate your help!

Upvotes: 1

Views: 1600

Answers (1)

bigcat
bigcat

Reputation: 152

the easiest way would be to create a component, and than inside your component's .ts, to append script to the body like so:

onInit(): void {
  const s = this._renderer.createElement('script');
  s.text = `var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
  (function () {
    var s1 = document.createElement("script"), s0 = document.getElementsByTagName("script")[0];
    s1.async = true;
    s1.src = 'https://embed.tawk.to/${id}/default';
    s1.charset = 'UTF-8';
    s1.setAttribute('crossorigin', '${cors}');
    s0.parentNode.insertBefore(s1, s0);
  })();
  this._renderer.appendChild(this._document.body, s);
}

Of course you'll need to inject Document and renderer into constructor

constructor(
  private _renderer: Renderer2,
  @Inject(DOCUMENT) private _document,
) {}

and make sure you set your twalk.to id and cors (${id}, ${cors})

Upvotes: 2

Related Questions