如何可靠检测OneTrust及等待其完全加载的技术咨询
OneTrust 检测与加载等待解决方案
问题背景
需根据页面加载时OneTrust的存在状态,以及(若存在时)特定Cookie/ consent分组的设置情况,控制TypeScript脚本的加载逻辑;同时兼容未接入OneTrust的项目,确保脚本正常加载。
核心问题与解决方案
1. 可靠检测OneTrust是否存在
直接即时检测window.OneTrust或OptanonWrapper会因异步加载导致误判,建议采用轮询+超时的方案,覆盖异步加载场景:
// 检测OneTrust是否存在(带超时机制) function checkOneTrustExists(timeout = 10000, interval = 200): Promise<boolean> { return new Promise((resolve) => { const startTime = Date.now(); const checkTimer = setInterval(() => { // 同时验证核心方法是否可用,避免检测到未初始化的空对象 const exists = typeof window !== 'undefined' && typeof window.OneTrust === 'object' && typeof window.OneTrust.OnConsentChanged === 'function'; if (exists || Date.now() - startTime >= timeout) { clearInterval(checkTimer); resolve(exists); } }, interval); }); }
2. 等待OneTrust完全加载完成
OneTrust未公开加载完成事件,但可以通过两种方式实现可靠等待:
方案一:结合OnConsentChanged回调
OneTrust初始化完成后,即使用户未操作弹窗,OnConsentChanged通常会触发一次;同时OnetrustActiveGroups会有初始值,可结合这两点判断:
async function waitForOneTrustReady(timeout = 10000): Promise<boolean> { const exists = await checkOneTrustExists(timeout); if (!exists) return false; // 已初始化完成的直接返回 if (typeof window.OnetrustActiveGroups === 'string') { return true; } return new Promise((resolve) => { let timeoutId: NodeJS.Timeout; const consentHandler = () => { clearTimeout(timeoutId); // 移除监听避免重复触发 window.OneTrust.OnConsentChanged(consentHandler); resolve(true); }; window.OneTrust.OnConsentChanged(consentHandler); // 超时兜底 timeoutId = setTimeout(() => { window.OneTrust.OnConsentChanged(consentHandler); resolve(false); }, timeout); }); }
方案二:轮询检测OnetrustActiveGroups
OnetrustActiveGroups是OneTrust初始化完成的核心标志之一,直接轮询该值的状态:
async function waitForOneTrustReady(timeout = 10000, interval = 200): Promise<boolean> { const exists = await checkOneTrustExists(timeout); if (!exists) return false; return new Promise((resolve) => { const startTime = Date.now(); const checkTimer = setInterval(() => { const isReady = typeof window.OnetrustActiveGroups === 'string'; if (isReady || Date.now() - startTime >= timeout) { clearInterval(checkTimer); resolve(isReady); } }, interval); }); }
整合使用示例
// 加载目标脚本的函数 function loadYourScript() { // 这里写你的脚本加载逻辑,比如动态import或创建script标签 import('./your-target-script.ts').then(module => { // 初始化脚本逻辑 module.init(); }); } // 条件加载主逻辑 async function handleConditionalLoad() { const oneTrustReady = await waitForOneTrustReady(); if (!oneTrustReady) { // 未接入OneTrust或加载超时,直接加载脚本 loadYourScript(); return; } // 检查是否符合特定Cookie/分组要求(替换为你的实际判断逻辑) const hasRequiredConsent = window.OnetrustActiveGroups.includes('TARGET_GROUP_ID'); if (hasRequiredConsent) { loadYourScript(); } } // 页面加载完成后执行 if (typeof window !== 'undefined') { window.addEventListener('DOMContentLoaded', handleConditionalLoad); }
内容的提问来源于stack exchange,提问作者Tobias
相关产品推荐
相关产品推荐

