You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript判断用户是否已接受OneTrust Cookie授权?

判断OneTrust Cookie授权状态(非SDK方式)

OneTrust会将用户的Cookie授权选择存储在浏览器Cookie中,你可以直接读取并解析这个Cookie来获取用户的历史选择,无需依赖SDK方法。

核心思路

OneTrust默认会生成名为OptanonConsent的Cookie,里面包含了用户的授权状态、Cookie组选择等信息。我们只需读取这个Cookie,解析其中的字段就能判断用户是否同意或拒绝了Cookie。

实现代码

// 读取指定名称的Cookie
function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

// 解析OneTrust授权Cookie的内容
function parseOneTrustConsent() {
  const consentCookie = getCookie('OptanonConsent');
  if (!consentCookie) return null;

  // 解析Cookie中的URL编码参数
  const params = new URLSearchParams(consentCookie);
  const groupStatus = params.get('groups')?.split(',').reduce((acc, item) => {
    const [groupId, status] = item.split(':');
    acc[groupId] = status === '1'; // 1表示同意,0表示拒绝
    return acc;
  }, {});

  return {
    // 是否有至少一个Cookie组被同意
    hasAnyConsent: params.get('groups')?.includes(':1'),
    // 是否所有Cookie组都被拒绝
    allRejected: !params.get('groups')?.includes(':1'),
    // 各Cookie组的具体授权状态(键为组ID,值为布尔值)
    groupStatus,
    // 授权时间戳
    datestamp: params.get('datestamp'),
    // OneTrust版本
    version: params.get('version')
  };
}

// 使用示例
const userConsent = parseOneTrustConsent();
if (userConsent) {
  if (userConsent.allRejected) {
    // 用户拒绝了所有Cookie,这里可以展示授权提示
    alert('授权必要/功能性Cookie可提升您的网站体验');
  } else if (userConsent.hasAnyConsent) {
    // 用户同意了至少部分Cookie
    console.log('用户已授权部分Cookie');
    // 可单独检查特定组的授权状态,比如检查组2是否同意
    if (userConsent.groupStatus['2']) {
      console.log('分析类Cookie已授权');
    }
  }
} else {
  // 用户尚未做出任何授权选择
  console.log('用户未完成Cookie授权选择');
}

注意事项

  • Cookie名称:默认是OptanonConsent,如果你在OneTrust后台修改了Cookie前缀,需要对应调整Cookie名称(比如前缀为MyShop时,Cookie名为MyShopOptanonConsent)
  • Cookie组ID:groupStatus中的数字对应你在OneTrust后台配置的Cookie组ID,需要和实际配置匹配才能准确判断特定类型Cookie的授权状态
  • 格式稳定性:这种方式依赖OneTrust的Cookie格式,虽然该格式相对稳定,但如果OneTrust未来变更存储逻辑,可能需要调整解析代码

内容的提问来源于stack exchange,提问作者Darren Gates

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 09:58:10