0

I have the sample JS functionality below (simplified for example).


function getConsentStatus(cat, catSub, catSubCheck){
// case statement which checks
// some cookies and JS objects
//returns true/false
}
return getConsentStatus(event.cat, event.catSub, event.catSubCheck);

I want to delay the executing until either the "OptanonConsent" cookie exists or the "OnetrustActiveGroups" object exists. I don't need code on how to check the cookie/object. How is it possible to delay the value from being returned in the "getConsentStatus" function until the cookie/object exists? I'm assuming, I'd need this check to be the initial check in the function and only have the rest of the function execute until one of those two conditions exists? Any ideas or help welcomed! Thanks!

Nick.Mc
  • 18,304
  • 6
  • 61
  • 91
Michael Johns
  • 419
  • 3
  • 21
  • Javascript is single threaded - do you really want to block all javascript operations? – Nick.Mc Jul 24 '23 at 03:53
  • In more helpful terms, you _shouldn't_ do this and it's probably not even really possible given that you need other javavascript to run to inform you of this happening. There are alternatives to this but you have to rethink your approach. This suggests that you need an event handler. – Evert Jul 24 '23 at 03:55
  • @Evert Maybe it would be possible by using worker thread, but indeed it would be... weird : D – Bartłomiej Stasiak Jul 24 '23 at 04:05

1 Answers1

0

You can introduce event listener, which would listen for optanon-consent-or-one-trust-active-groups-spawned CustomEvent:

window.addEventListener(`optanon-consent-or-one-trust-active-groups-spawned`, event => {
  // ... code, which will be executed after spawning of cookie or object.
  // Passed event will contain cookie or object, which you will check here.
  // You can read cookie or object in event.detail
});

However i would divide this event listener into two event listeners, if you want to apply different logic for cookie and object spawn.

You should also emit event in places, in which optanonConsent and oneTrustActiveGroups spawn:

document.dispatchEvent(new CustomEvent(
  `optanon-consent-or-one-trust-active-groups-spawned`, 
  { detail: {} /* <= You will pass cookie or object here */ })
);