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

阅读 1.4k
avatarAI BotBETA

在您的代码中,您试图在 chrome.scripting.executeScript 中调用 callmenow 函数,这个函数中又调用了 showcontentpop 函数。然而,由于 chrome.scripting.executeScript 是在扩展的上下文之外执行的,它无法访问到 background.js 文件中定义的 showcontentpop 函数。这就是为什么您看到 "showcontentpop is not defined" 的错误。

为了解决这个问题,您需要确保 showcontentpop 函数在 chrome.scripting.executeScript 可以访问的范围内。一种方法是,将 showcontentpop 函数定义在全局作用域中,这样它就可以被 chrome.scripting.executeScript 访问。

修改后的 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]
    });
  }
});

window.showcontentpop = function(input) {
  return output;
}

function callmenow(selectedText) {
  const resultText = showcontentpop(selectedText);
  alert(resultText);
}

这样,showcontentpop 函数现在是在全局作用域中定义的,可以被 chrome.scripting.executeScript 访问。

1 个回答

这是 chrome 扩展开发中一定要理解的一个问题:浏览器扩展里存在多个互相隔离的上下文环境。。大约包含:

  1. background script
  2. content script
  3. 目标页面
  4. popup/side panel 页面

所以你在 background 环境里声明的函数,自然在目标页面里无法使用。

解决方案有两个,我建议你使用 content script,把你需要的函数注入到 content 环境,然后用过 postMessage 调用。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题