如何从Chrome扩展弹窗重复调用注入页面的myFunc1函数?
解决Chrome扩展Manifest V3中弹窗调用页面注入函数的问题
问题核心原因是:chrome.scripting.executeScript 默认运行在隔离的内容脚本上下文,而你通过content.js注入的inject.js属于页面的主世界上下文,两个上下文的window对象完全独立,因此无法直接访问主世界的window.myFunc1。
以下是两种可行的解决方案:
方法1:让执行脚本直接运行在主世界
调用executeScript时指定world: 'MAIN'参数,让脚本直接进入页面主世界上下文,即可直接访问window.myFunc1。
示例代码(popupGPX.js):
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { chrome.scripting.executeScript({ target: {tabId: tabs[0].id}, func: () => { // 此时运行在主世界,可直接调用myFunc1 window.myFunc1(); }, world: 'MAIN' // 关键参数,指定主世界上下文 }); });
如果是调用外部脚本文件,同样适用:
chrome.scripting.executeScript({ target: {tabId: tabs[0].id}, files: ['call-myfunc.js'], world: 'MAIN' });
注意:需确保manifest.json中已声明scripting权限。
方法2:通过内容脚本做中转通信
若不想让弹窗脚本直接进入主世界,可借助content.js作为中间层,通过自定义事件实现通信:
- content.js:监听弹窗消息,触发主世界自定义事件
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === 'triggerMyFunc1') { window.dispatchEvent(new CustomEvent('callMyFunc1')); sendResponse({status: '已触发'}); } });
- inject.js:监听自定义事件,执行目标函数
window.addEventListener('callMyFunc1', () => { window.myFunc1(); });
- popupGPX.js:向content.js发送调用指令
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { chrome.tabs.sendMessage(tabs[0].id, {action: 'triggerMyFunc1'}, (res) => { console.log(res.status); }); });
注意:自定义事件名称需唯一,避免与网站自身事件冲突。
内容的提问来源于stack exchange,提问作者JanBN
相关产品推荐
相关产品推荐

