chrome.scripting.executeScript 传递参数

Joe*_*ore 2 javascript google-chrome-extension

我的 Chrome 扩展程序的文件中有以下代码popup.js

chrome.scripting.executeScript({
  target: { tabId: tab.id },
  function: myFunc,
});


function myFunc() {
  // do something
}
Run Code Online (Sandbox Code Playgroud)

但是,我想从executeScriptto传递一个参数myFunc。像这样的事情:

chrome.scripting.executeScript({
  argument: {"arg1", "arg2"}
  target: { tabId: tab.id },
  function: connectCmd,
});


function myFunc(arg1: string, arg2: string) {
  // do something
}
Run Code Online (Sandbox Code Playgroud)

或同等的东西。有什么办法可以做到这一点吗?

wOx*_*xOm 7

根据文档, (参数数组)属性args自 Chrome 92 起可用。

  • 这些参数必须是 JSON 可序列化的,即字符串、数字、布尔值、null、由上述类型组成的数组/对象。简而言之,注入的代码将看到与您通过运行看到的相同的内容,JSON.parse(JSON.stringify(args))这意味着您无法传输类、Set、Map 和其他重要对象。
  • 您可以func在 Chrome 92+ 中使用属性,这是function.
chrome.scripting.executeScript({
  args: ['foo', 'bar']
  target: { tabId: tab.id },
  func: myFunc,
});

function myFunc(arg1, arg2) {
  console.log(arg1, arg2); // will print `foo bar` in console of the web page
}
Run Code Online (Sandbox Code Playgroud)

在旧版 Chrome 中,您必须使用消息传递