无法读取未定义的属性“executeScript”

Ale*_*yes 1 google-chrome-extension

我按照 chrome 扩展的“入门”教程进行操作,但出现以下错误。

我搜索谷歌,有人说无法访问 content.js 中的“executeScript”,但错误来自 popup.js。

我曾尝试将 'chrome.scripting.executeScript' 更改为 'chrome.tabs.executeScript',它也不起作用。

错误图像

清单文件

{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!",
    "permissions": ["storage", "declarativeContent", "activeTab"],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "page_action": {
        "default_popup": "popup.html"
    },
    "options_page": "options.html",
    "manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)

弹出窗口.js

let changeColor = document.getElementById('changeColor')

chrome.storage.sync.get('color', function(data) {
    changeColor.style.backgroundColor = data.color;
    changeColor.setAttribute('value', data.color)
});

changeColor.addEventListener('click', () =>
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.scripting.executeScript(
      tabs[0].id,
      { function: setColor })
})
);

async function setColor() {
let {color} = await chrome.storage.sync.get(['color']);
document.body.style.backgroundColor = color;
};
Run Code Online (Sandbox Code Playgroud)

整个扩展代码

参考:chrome 开发人员 -> 入门

Yuv*_*san 12

您需要脚本权限才能访问脚本 API。添加scripting到您的manifest.js文件。

"permissions": ["scripting", ...]
Run Code Online (Sandbox Code Playgroud)


小智 10

您的权限manifest.json缺少一项,即"scripting".

它应该是这样的:

…
"permissions": ["storage", "declarativeContent", "activeTab", "scripting"],
…
Run Code Online (Sandbox Code Playgroud)

这实际上可以在此处的“入门”页面上看到

  • 我已经添加了脚本但遇到了相同的错误 (10认同)

Nad*_*ova 6

您需要迁移到清单 v3 或使用chrome.tabs.executeScript而不是chrome.scripting.executeScript