javascript - OneTrust:检查项目中是否使用了 OneTrust,并等待其完全加载完成
我在调整我的几个 TypeScript 文件时遇到困难,这些文件需要根据 OneTrust 的情况来决定是否加载,无论它在页面加载时是否可用,如果可用,只有在特定 cookie 设置后才加载某些 TypeScript 脚本。一些也依赖该代码库的项目目前可能不使用 OneTrust,因此当 OneTrust 不可用时,该项目的脚本仍应正常加载(不过将来会有所改变)。
我有两个关于 OneTrust 的问题:
- 我如何才能可靠地检查项目中是否存在 OneTrust?
- 如果项目中存在 OneTrust,有什么好的方法可以等待 OneTrust 完全加载完成?
我已经尝试过做类似的事情:
const isActive = typeof window !== 'undefined' && typeof window.OptanonWrapper === 'function';
或
const isOneTrustActive = typeof window !== 'undefined' && typeof window.OneTrust === 'object';
遗憾的是,这些对象通常没有可靠地完成设置,因此表明 OneTrust 不可用:
typeof window.OneTrust === 'undefined' (should be 'object')
typeof window.OnetrustActiveGroups === 'undefined' (should be 'string')
那些只有在我的脚本检查它们可用之后不久才会可用。
我还没有找到 OneTrust 成功加载完成时触发的事件。
我知道 OneTrust 有一个回调函数,每当 cookie 发生变化时都会触发,这个功能运行得非常完美:
window.OneTrust.OnConsentChanged(callback)
OneTrust 最初加载完成时也有类似的东西吗?我找不到类似的东西。
答案#1
OneTrust 本身不附带任何 JS 工具来让你知道横幅是否已加载并可以使用。你必须要么监听 OneTrust 脚本的 <script> 标签上的 load 事件,要么在 OptanonWrapper 回调中触发自定义事件。
<script type="text/javascript">
function OptanonWrapper() {
const oneTrustLoadedEvent = new CustomEvent('onetrustloaded');
window.dispatchEvent(oneTrustLoadedEvent);
}
</script>
这将允许你在 OneTrust 实际准备好时运行你的代码,而不是不断轮询。
答案#2
我找到我需要的答案,多亏了 @emiel-zuurbier 的回答。
- 更新(2024年7月25日):添加了最终可用功能
我在 OneTrust 脚本实现中使用自定义事件的 OptanonWrapper 函数:
function OptanonWrapper() {
const event = new Event('onetrustloaded');
document.dispatchEvent(event);
window.OneTrustLoaded = true;
}
检查 OneTrust 是否可用:
export const isOneTrustActive = (): boolean => {
return typeof window !== 'undefined' && typeof window.OptanonWrapper === 'function';
};
检查 OneTrust 是否加载完成:
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;
};
等待 OneTrust 自定义初始化事件并调用回调的函数:
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 函数中的最终实现看起来像这样:
/* Init */
((): void => {
if (!isOneTrustActive()) {
// Initialize normal components and functions here without considering OneTrust cookies...
return;
}
// Initial OneTrust init
initOneTrustCallback(initFunction, onChangeFunction);
})();
