From 1327d536a3d0a66dee78762f0a6b4f19bebbc0d9 Mon Sep 17 00:00:00 2001 From: Alf Eaton Date: Fri, 11 Oct 2024 13:20:39 +0100 Subject: [PATCH] Use the whole Hotjar snippet (#21017) GitOrigin-RevId: 3935d671bdf5299b720f319fd7d8c6879d1819b9 --- .../js/infrastructure/hotjar-snippet.js | 15 ++++++++++++ .../web/frontend/js/infrastructure/hotjar.ts | 24 +++++++++---------- 2 files changed, 26 insertions(+), 13 deletions(-) create mode 100644 services/web/frontend/js/infrastructure/hotjar-snippet.js diff --git a/services/web/frontend/js/infrastructure/hotjar-snippet.js b/services/web/frontend/js/infrastructure/hotjar-snippet.js new file mode 100644 index 0000000000..c937ad09f6 --- /dev/null +++ b/services/web/frontend/js/infrastructure/hotjar-snippet.js @@ -0,0 +1,15 @@ +// tracking code from https://help.hotjar.com/hc/en-us/articles/115009336727-How-to-Install-Your-Hotjar-Tracking-Code +export const initializeHotjar = (hotjarId, hotjarVersion) => + (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=') diff --git a/services/web/frontend/js/infrastructure/hotjar.ts b/services/web/frontend/js/infrastructure/hotjar.ts index f024ce472f..c72b8fd1eb 100644 --- a/services/web/frontend/js/infrastructure/hotjar.ts +++ b/services/web/frontend/js/infrastructure/hotjar.ts @@ -1,9 +1,12 @@ import getMeta from '@/utils/meta' import { isSplitTestEnabled } from '@/utils/splitTestUtils' import { debugConsole } from '@/utils/debugging' +import { initializeHotjar } from '@/infrastructure/hotjar-snippet' const { hotjarId, hotjarVersion } = getMeta('ol-ExposedSettings') +let hotjarInitialized = false + if (hotjarId && hotjarVersion && isSplitTestEnabled('hotjar')) { const loadHotjar = () => { // consent needed @@ -11,22 +14,17 @@ if (hotjarId && hotjarVersion && isSplitTestEnabled('hotjar')) { return } - // avoid inserting twice - if (document.getElementById('hotjar')) { + if (!/^\d+$/.test(hotjarId) || !/^\d+$/.test(hotjarVersion)) { + debugConsole.error('Invalid Hotjar id or version') return } - debugConsole.log('Loading Hotjar') - - const url = new URL(`https://static.hotjar.com/c/hotjar-${hotjarId}.js`) - url.searchParams.set('sv', hotjarVersion) - - const script = document.createElement('script') - script.src = url.toString() - script.async = true - script.id = 'hotjar' - - document.head.append(script) + // avoid inserting twice + if (!hotjarInitialized) { + debugConsole.log('Loading Hotjar') + hotjarInitialized = true + initializeHotjar(hotjarId, hotjarVersion) + } } // load when idle, if supported