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

咨询:Cypress无法清除Usercentrics相关localStorage对象的解决办法

解决Cypress中无法清除Usercentrics分区localStorage的问题

问题原因

你遇到的https://app.usercentrics.eu相关存储属于浏览器分区存储(Partitioned Storage),这是浏览器为第三方跨域资源实现的隔离存储机制。普通的localStorage.clear()或Cypress自带的cy.clearLocalStorage()仅能操作当前主域的存储,无法直接访问第三方分区的存储内容。

可行解决思路

1. 使用Cypress全量清除命令

直接调用cy.clearAllLocalStorage(),这个方法会清除所有域的localStorage(包括第三方分区存储):

cy.clearAllLocalStorage()

2. 通过浏览器Storage API操作分区存储

如果全量清除无效,可以借助浏览器的StorageManager API直接删除目标存储分区:

cy.window().then(async (win) => {
  const storageBuckets = await win.navigator.storage.getDirectory();
  for await (const bucket of storageBuckets) {
    if (bucket.name.includes('usercentrics')) {
      await bucket.remove();
    }
  }
})

3. 重置浏览器上下文

通过重置整个浏览器会话来清除所有存储,相当于模拟浏览器重启:

cy.clearAllSessionStorage()
cy.clearAllLocalStorage()
cy.reload(true) // 强制刷新忽略缓存

或者在访问页面时直接清除所有存储:

cy.visit('/', {
  force: true,
  onBeforeLoad: (win) => {
    win.localStorage.clear();
    win.navigator.storage.clear();
  }
})

4. 调用Usercentrics官方API重置

Usercentrics提供了官方方法重置用户同意状态,直接调用全局对象方法即可:

cy.window().then((win) => {
  if (win.Usercentrics) {
    win.Usercentrics.resetConsent();
  }
})

验证清除结果

可以添加断言确认清除是否成功:

cy.window().then((win) => {
  const usercentricsKeys = Object.keys(win.localStorage).filter(key => key.includes('usercentrics'));
  expect(usercentricsKeys).to.be.empty;
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:09:25