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).
I have two questions relating OneTrust:
- How can I reliably check if OneTrust is present in the project?
- If OneTrust is present in the project, what is a good way to wait for OneTrust to have finished loading completely?
I already tried to do something like this:
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.
2
Answers
The answer I needed I found thanks to @emiel-zuurbier 's answer.
OptanonWrapper function within the OneTrust script implementation with my custom event:
Check for OneTrust being available:
Function to wait for OneTrust custom init event and invoking a callback:
What the final implementation in my init function looks like:
OneTrust itself doesn’t come with any JS tools to let you know whever the banner has been loaded and is ready for use. You’ll have to either listen for the
load
event on the<script>
tag of the OneTrust script or dispatch a custom event within theOptanonWrapper
callback.This will allow you to run your code whenever OneTrust actually is ready instead of polling.