chrome.scripting.executeScript - 意外属性:“参数”

Ric*_*mer 5 javascript google-chrome google-chrome-extension

我正在尝试将 chrome.scripting.executeScript 用于我在 ManifestV3 中构建的 chrome 扩展,并在此处遵循 Google 文档(见下图):

在此处输入图片说明

我添加了一个“参数”属性以将当前选项卡的标题传递给我的函数。但是,我收到以下错误消息:

TypeError: Error in invocation of scripting.executeScript(scripting.ScriptInjection injection, optional function callback): Error at parameter 'injection': Unexpected property: 'arguments'.

这是我的代码:

chrome.tabs.query({ active: true }, function (tabs) {
  let tab = tabs[0];
  chrome.scripting.executeScript(
    {
      target: { tabId: tab.id },
      function: myFunction,
      arguments: [tab.title],
    },
    (injectionResults) => displaySearch(injectionResults[0].result)
  );
});
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激,谢谢!

小智 7

使用的属性名称不正确。新的 API 使用属性“args”。例如:

function greet(greeting) {
   console.log(`${greeting}, World!`);
}

chrome.scripting.executeScript({
     target: {tabId: tab.id},
     function: greet,
     args: ['Hello']
});

Output: Hello, World!
Run Code Online (Sandbox Code Playgroud)

您可以在这里找到更多信息。


小智 4

在他们使用chrome.storage实现该功能之前,您可以使用一个解决方法。您需要做的是首先使用 保存参数chrome.storage.sync.set(),然后在使用 注入的函数中检索它chrome.storage.sync.get()

chrome.storage.sync.set({ myVariable: valueOfVariable });

chrome.tabs.query({ active: true }, function (tabs) {
  let tab = tabs[0];
  chrome.scripting.executeScript(
    {
      target: { tabId: tab.id },
      function: myFunction,
    }
  );
});

function myFunction() {
  chrome.storage.sync.get(["myVariable"], ({ myVariable }) => {
    // Do stuff
  });
}
Run Code Online (Sandbox Code Playgroud)