I am having difficulty adjusting several of my TypeScript files to load depending on OneTrust, whether it's available or not on pageload, and if available, only loading certain TypeScript scripts when specific cookies have been set. Some of the projects that also rely on that codebase might not use OneTrust currently and so the scripts for this project should still load normally when OneTrust is not available (will be changed in the future, though).
const isActive = typeof window !== 'undefined' && typeof window.OptanonWrapper === 'function';
or
const isOneTrustActive = typeof window !== 'undefined' && typeof window.OneTrust === 'object';
Sadly, the objects usually are not reliably finished setting up and thus indicates OneTrust not being available:
typeof window.OneTrust === 'undefined' (should be 'object')
typeof window.OnetrustActiveGroups === 'undefined' (should be 'string')
Those are only available shortly after my scripts check for them being available.
I haven't found an event of OneTrust that fires when OneTrust is finished successfully loading.
I know there is a callback function of OneTrust that will be fired whenever the cookies have changed, which works perfectly:
window.OneTrust.OnConsentChanged(callback)
Is there something like that for OneTrust finishing loading initially as well? I couldn't find anything like it.
The answer I needed I found thanks to @emiel-zuurbier 's answer.
function OptanonWrapper() {
const event = new Event('onetrustloaded');
document.dispatchEvent(event);
window.OneTrustLoaded = true;
}
export const isOneTrustActive = (): boolean => {
return typeof window !== 'undefined' && typeof window.OptanonWrapper === 'function';
};
export const isOneTrustLoaded = (): boolean => {
// Set OneTrustLoaded window variable if not yet available --> not yet ready
if (!(typeof window.OneTrustLoaded === 'boolean')) {
window.OneTrustLoaded = false;
}
return window.OneTrustLoaded;
};
export const initOneTrustCallback = (immediateCallback: any, onChangeCallback: any): void => {
// OneTrust finished loading?
if (!isOneTrustLoaded()) {
document.addEventListener('onetrustloaded', () => {
window.OneTrustLoaded = true;
// Initial check for cookie state to either activate videos or not - without reloading page
immediateCallback();
// OneTrust OnConsentChanged will be called by OneTrust when cookies have been changed
window.OneTrust.OnConsentChanged(onChangeCallback);
});
return;
}
// Initial check for cookie state to either activate videos or not - without reloading page
immediateCallback();
// OnConsentChanged will be called by OneTrust when cookies have been changed (listener)
window.OneTrust.OnConsentChanged(onChangeCallback);
};
/* Init */
((): void => {
if (!isOneTrustActive()) {
// Initialize normal components and functions here without considering OneTrust cookies...
return;
}
// Initial OneTrust init
initOneTrustCallback(initFunction, onChangeFunction);
})();