Santosh
Santosh

Reputation: 3827

Inject hotjar script into angular page inside head element

I want to add conditions to load this script in the head tag. I need to check if the URL is from our live domain then only it runs otherwise not. I could simply add this script to the head if there was no condition requirement. How I can inject this script in the head tag in angular?

For eg:

window.origin == 'https://www.stackoverflow.com' then inject this script into the head tag otherwise not.

<script>
        (function(h,o,t,j,a,r){
            h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
            h._hjSettings={hjid:*******,hjsv:*};
            a=o.getElementsByTagName('head')[0];
            r=o.createElement('script');r.async=1;
            r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
            a.appendChild(r);
        })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
    </script>

Upvotes: 0

Views: 1486

Answers (1)

Lukasz Gawrys
Lukasz Gawrys

Reputation: 1334

You can handle this in one of your components, preferably in app.component. You could check the URL of course but more elegant would be to have some flag like enableHotjarTracking in your environment.ts file and set it to true only for your production environment.

Then you could call it as follows in your app.component.ts

import { environment } from './environments/environment';
import { DOCUMENT } from '@angular/common';

...

// inject document wrapper
constructor(
 @Inject(DOCUMENT) private document: Document,
){}

ngAfterContentInit() {
  if(environment.enableHotjarTracking) {
          ((h, o, t, j, a, r) => {
            h.hj =
              h.hj ||
              /* tslint:disable:only-arrow-functions */
              function () {
                (h.hj.q = h.hj.q || []).push(arguments);
              };
            h._hjSettings = { hjid: xxxx, hjsv: x };
            a = o.getElementsByTagName('head')[0];
            r = o.createElement('script');
            r.async = 1;
            r.src = t + h._hjSettings.hjid + j + h._hjSettings.hjsv;
            a.appendChild(r);
          })(window as any, this.document, 'https://static.hotjar.com/c/hotjar-', '.js?sv=');
  }
}

You could also keep your hotjar id in the environment file.

Upvotes: 3

Related Questions