Chrome扩展通过chrome.windows创建的弹窗如何获取主窗口当前激活标签页
核心问题
你当前的代码存在两处错误:
- 在弹窗上下文中调用
chrome.tabs.query时传入的currentWindow: true,指代的是你新弹出的独立popup窗口,因此查询到的是弹窗自身的标签,而非触发扩展的浏览器主窗口的激活标签。 - 通过
chrome.scripting.executeScript注入到网页的函数运行在网页隔离上下文,没有权限直接访问扩展的chrome.storageAPI,无法直接读取存储的颜色值。
快速修复方案
直接修改弹窗内的onClick函数即可适配需求:
const onClick = async (e) => { if (e && e.preventDefault) e.preventDefault(); // 将currentWindow替换为lastFocusedWindow,查询最后一次聚焦的主浏览器窗口的激活标签 const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true, }); // 先在弹窗上下文(有权限访问扩展存储)读取颜色值,再传入注入函数 const { color } = await chrome.storage.sync.get("color"); await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: (targetColor) => { document.body.style.backgroundColor = targetColor; }, args: [color] // 通过args参数将颜色传递给注入的函数 }); };
更稳定的实现方案
如果要避免弹窗打开后用户切换窗口导致操作错标签,可以在打开弹窗时就把当前激活标签的ID传递过去:
- 首先修改
background.js里打开弹窗的逻辑:
chrome.action.onClicked.addListener(async (activeTab) => { // 点击扩展图标时拿到的activeTab就是当前激活的目标标签,将ID拼到弹窗URL中 await chrome.windows.create({ url: chrome.runtime.getURL(`popup.html?activeTabId=${activeTab.id}`), type: "popup", }); });
- 再修改弹窗内的逻辑,直接读取URL中的标签ID使用:
// 从弹窗URL中提取目标标签ID const getTargetTabId = () => { const params = new URLSearchParams(window.location.search); return Number(params.get("activeTabId")); }; const onClick = async (e) => { if (e && e.preventDefault) e.preventDefault(); const tabId = getTargetTabId(); const { color } = await chrome.storage.sync.get("color"); await chrome.scripting.executeScript({ target: { tabId }, func: (targetColor) => { document.body.style.backgroundColor = targetColor; }, args: [color] }); };
你现有的manifest.json配置已经包含了所需的全部权限,无需额外修改。
内容的提问来源于stack exchange,提问作者Marcus Jason
相关产品推荐
相关产品推荐

