chrome扩展的background.js 文件无法调用同文件中的函数?-灵析社区

代码大师

chrome扩展的background.js 文件无法调用同文件中的函数,我基于 manifest v3 创建了一个 chrome extension,具体代码如下 manifest.json { "manifest_version": 3, "name": "achromeextension", "version": "1.0", "description": "", "permissions": ["contextMenus", "activeTab", "scripting"], "background": { "service_worker": "background.js" }, "icons": { "48": "icon.png" } } background.js 的代码如下 chrome.runtime.onInstalled.addListener(() => { chrome.contextMenus.create({ id: "chromeextensiondemo", title: "chromeextensiondemo", contexts: ["selection"] }); }); chrome.contextMenus.onClicked.addListener((info, tab) => { if (info.menuItemId === "chromeextensiondemo") { chrome.scripting.executeScript({ target: { tabId: tab.id }, function: callmenow, args: [info.selectionText] }); } }); function showcontentpop(input) { return output; } function callmenow(selectedText) { const resultText = showcontentpop(selectedText); alert(resultText); } 但现在遇到的问题是,提示错误,错误信息是 showcontentpop is not defined. 请问这个该怎么处理? 能正常调用函数 showcontentpop

阅读量:18

点赞量:0

问AI
这是 chrome 扩展开发中一定要理解的一个问题:浏览器扩展里存在多个互相隔离的上下文环境。 。大约包含: 1. background script 2. content script 3. 目标页面 4. popup/side panel 页面 所以你在 background 环境里声明的函数,自然在目标页面里无法使用。 解决方案有两个,我建议你使用 content script,把你需要的函数注入到 content 环境,然后用过 "postMessage" 调用。