Skip to content

Commit

Permalink
fix: check for window's existance
Browse files Browse the repository at this point in the history
  • Loading branch information
olavoparno committed Apr 27, 2021
1 parent 9e99719 commit 8976a27
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/dependencies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,23 @@ export function hotjarInitScript(
hotjarId: number,
hotjarVersion: number
): boolean {
const hasWindow = typeof window !== 'undefined';

if (!hasWindow) return false;

const hotjarScriptCode = `(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${hotjarId},hjsv:${hotjarVersion}};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=');`;
const isAppended = appendHeadScript(hotjarScriptCode, 'hotjar-init-script');

if (isAppended && window && window.hj) {
if (isAppended && hasWindow && window.hj) {
return true;
}

throw Error('Hotjar initialization failed!');
}

export function hotjarStateChangeScript(relativePath: string): void {
if (window && window.hj) {
const hasWindow = typeof window !== 'undefined';
if (hasWindow && window.hj) {
return window.hj('stateChange', relativePath);
}

Expand All @@ -74,15 +79,17 @@ export function hotjarIdentifyScript(
userId: string | null,
userInfo: TUserInfo
): void {
if (window && window.hj) {
const hasWindow = typeof window !== 'undefined';
if (hasWindow && window.hj) {
return window.hj('identify', userId, userInfo);
}

throw Error('Hotjar is not available! Is Hotjar initialized?');
}

export function checkReadyState(): boolean {
if (window && window.hj) {
const hasWindow = typeof window !== 'undefined';
if (hasWindow && window.hj) {
return true;
}

Expand Down

0 comments on commit 8976a27

Please sign in to comment.