2

I want to get userId from Hotjar but I need to make sure Hotjar is loaded. How can I dependent a function to Hotjar loaded something like using .then() to wait for promise.

<Hotjar Code>
.
.
.
<End of Hotjar Code>

let x = hj.globals.get('userId').split('-').shift()

Now I get the error TypeError: Cannot read property 'get' of undefined

Mohammad Taherian
  • 1,622
  • 1
  • 15
  • 34
  • Hey, did you had a chance to try out the `window` solution? Is it working for you or do you still need an answer to your question? – Christoph Kluge Feb 20 '20 at 13:47

1 Answers1

1

Referencing another SO question which is close to your question: Capturing Hotjar User ID in Google Tag Manager & Google Analytics

Anyway you could check if this property exists and if it's a function. At least this is how I solved it.

One thing might be that you need to wait for the DOM to be available:

document.addEventListener("DOMContentLoaded", function () {
    hj.globals.get('userId').split('-').shift()
};

Another thing might be that you need to check if the script was loaded at all.

if (window.hj && typeof (window.hj) === "function") {
    hj.globals.get('userId').split('-').shift()
}

With both in mind I would perhaps suggest the following code to be very save about it.

document.addEventListener("DOMContentLoaded", function () {
    if (window.hj && typeof (window.hj) === "function") {
        hj.globals.get('userId').split('-').shift()
    }
};
Christoph Kluge
  • 1,947
  • 8
  • 23
  • 2
    Thank you for the comment. This is not what I'm looking for. I can check that with this condition `if (hj.globals)` . I want to use something like `.then()` to make sure first part was added and then this part happen. – Mohammad Taherian Feb 20 '20 at 13:49
  • 1
    Thank you for updating code. I will check it and let you know the result. – Mohammad Taherian Feb 20 '20 at 13:52
  • It's a pleasure! I'm trying to understand where you come from and where want to go. I assumed `` is the hotjar-script which you got directly from hotjar. Is this right? – Christoph Kluge Feb 20 '20 at 13:54
  • Yes, exactly. The script that is gotten from hotjar. – Mohammad Taherian Feb 20 '20 at 15:06
  • @MohammadTaherian did the document.addEventListener('DOMContentLoaded') helped? I've also added another question on SO which seems very close to your question. – Christoph Kluge Feb 20 '20 at 15:15