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

Chrome扩展:侧边栏关闭无可用事件,需在background.js清除存储

解决方案

可以通过Chrome的sidePanel API在background.js中直接监听侧边栏的隐藏事件,无需依赖侧边栏关闭按钮的点击事件,具体实现步骤如下:

1. 配置Manifest权限

确保你的manifest.json中声明了所需权限和侧边栏配置:

{
  "permissions": ["sidePanel", "storage"],
  "side_panel": {
    "default_path": "sidepanel.html" // 替换为你的侧边栏页面路径
  }
}

2. 在background.js中监听侧边栏隐藏事件

通过chrome.sidePanel.onHidden事件捕获侧边栏关闭的时机,然后清除对应存储:

// 监听侧边栏隐藏(关闭)事件
chrome.sidePanel.onHidden.addListener(async () => {
  // 清除指定的侧边栏相关存储项,替换为你的实际存储键名
  await chrome.storage.local.remove(['sidebar_temp_data', 'sidebar_user_state']);
  
  // 若需清除所有侧边栏相关存储(谨慎使用,避免误删其他数据)
  // await chrome.storage.local.clear();
});

兼容旧版本Chrome(<114)

如果你的插件需要兼容Chrome 114以下版本,可以通过监听窗口的onRemoved事件结合窗口类型判断(侧边栏窗口类型为panel):

chrome.windows.onRemoved.addListener(async (windowId) => {
  const windowInfo = await chrome.windows.get(windowId);
  // 验证是否为侧边栏窗口
  if (windowInfo.type === 'panel') {
    await chrome.storage.local.remove(['sidebar_related_keys']);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:39:58