如何在 chrome.scripting.executeScript 上调用一个调用其他函数的函数

kel*_*and 7 google-chrome-extension chrome-extension-manifest-v3

我试图在 chrome.scripting.executeScript 调用中的“func”参数中调用函数内部的外部函数:

await chrome.scripting.executeScript({
    target: {tabId: tabId},
    func: async () => {
        //call a extern function here
    }
})
Run Code Online (Sandbox Code Playgroud)

在这次通话中我得到“ReferenceError:[函数名称]未定义”

我想知道是否可能,如果可以,怎么可能?

Nab*_*.Z. -1

在使用的上下文中chrome.scripting.executeScript,参数中传递的函数func在内容脚本环境中执行,该环境与扩展程序的后台脚本和网页上的任何其他脚本隔离。因此,您无法从内容脚本环境直接调用扩展后台脚本中定义的外部函数。

然而,有一些方法可以实现内容脚本和后台脚本之间的通信。一种常见的方法是在内容脚本和后台脚本之间使用chrome.runtime.sendMessagechrome.runtime.onMessage发送消息。

以下示例说明了如何使用消息传递从内容脚本调用后台脚本中定义的外部函数:

背景.js:

// Define the external function in the background script
function externalFunction(argument) {
  console.log("External function called from content script with argument:", argument);
  return "Response from background!";
}

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.action === "callExternalFunction") {
    const result = externalFunction(message.argument);
    sendResponse(result);
  }
});
Run Code Online (Sandbox Code Playgroud)

内容脚本.js:

// Send a message to the background script to call the external function with an argument
chrome.scripting.executeScript({
  target: { tabId: tabId },
  func: () => {
    chrome.runtime.sendMessage({
      action: "callExternalFunction",
      argument: "Hello from content script!"
    }, function(response) {
      console.log("Response from background script:", response);
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

请记住"background"在您的manifest.json中声明权限以允许内容脚本和后台脚本之间的通信:

清单.json:

{
  "manifest_version": 3,
  "name": "Your Extension Name",
  "version": "1.0",
  "description": "Your extension description",
  "permissions": [
    "tabs",
    "activeTab",
    "scripting",
    "background"
  ],
  "action": {
    "default_popup": "popup.html"
  }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,内容脚本使用 向后台脚本发送带有参数的消息chrome.runtime.sendMessage。后台脚本使用以下方式侦听消息chrome.runtime.onMessage,当它收到具有指定操作的消息时,它会使用externalFunction提供的argument.

使用参数处理函数后,后台脚本使用该sendResponse函数发回响应,该响应将作为回调函数的参数在内容脚本中接收。

内容脚本中的控制台输出将显示从后台脚本收到的响应。

这样,您可以在内容脚本和后台脚本之间进行有效的通信,包括从内容脚本调用后台脚本中定义的函数以及来回传递参数。

内容脚本和后台脚本之间进行通信