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

如何在Content Script中检测Side Panel的打开与关闭状态?

如何在Content Script中检测Chrome Side Panel的开闭状态?

你可以用两种更优雅的方式替代轮询方案,避免频繁通信的低效问题:

方案一:利用Side Panel页面的卸载事件

在Side Panel页面脚本中监听beforeunload事件,面板关闭时主动更新会话存储中的状态:

Side Panel 脚本实现

// 面板打开时标记状态
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
await chrome.storage.session.set({ [`TAB_${tabs[0].id}`]: 'sidepanel-open' });

// 面板关闭时更新状态
window.addEventListener('beforeunload', async () => {
  const activeTabs = await chrome.tabs.query({ active: true, currentWindow: true });
  if (activeTabs[0]) {
    await chrome.storage.session.set({ [`TAB_${activeTabs[0].id}`]: 'sidepanel-closed' });
  }
});

Content Script 读取状态

无需轮询,直接从会话存储中读取对应标签页的面板状态:

(async () => {
  const currentTab = await chrome.tabs.getCurrent();
  const statusResult = await chrome.storage.session.get([`TAB_${currentTab.id}`]);
  const panelStatus = statusResult[`TAB_${currentTab.id}`] || 'sidepanel-closed';
  // 根据状态执行业务逻辑
  console.log('侧边栏状态:', panelStatus);
})();

方案二:使用官方Side Panel事件(Chrome 114+)

Chrome 114及以上版本提供了chrome.sidePanel.onShown和chrome.sidePanel.onHidden事件,可在后台服务工作者中直接监听面板的显示/隐藏状态,这是最可靠的官方方案:

Background Service Worker 脚本实现

// background.js
chrome.sidePanel.onShown.addListener(async (tab) => {
  await chrome.storage.session.set({ [`TAB_${tab.id}`]: 'sidepanel-open' });
});

chrome.sidePanel.onHidden.addListener(async (tab) => {
  await chrome.storage.session.set({ [`TAB_${tab.id}`]: 'sidepanel-closed' });
});

Content Script 读取状态

直接读取会话存储即可,无需额外通信:

(async () => {
  const currentTab = await chrome.tabs.getCurrent();
  const statusResult = await chrome.storage.session.get([`TAB_${currentTab.id}`]);
  const panelStatus = statusResult[`TAB_${currentTab.id}`] || 'sidepanel-closed';
  // 业务逻辑处理
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:35:13