Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'executeScript' of undefined

I follow the 'Getting started' tutorial of chrome extensions, but I get the below error.

I search google, somebody say can't access 'executeScript' in content.js, but the error is from popup.js.

I had tried change 'chrome.scripting.executeScript' to 'chrome.tabs.executeScript', it didn't work too.

error image

manifest.json

{
    "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
}

popup.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;
};

The whole extension code

reference: chrome developers -> Getting started

like image 446
Aleksander Hayes Avatar asked Dec 28 '20 10:12

Aleksander Hayes


4 Answers

The permissions in your manifest.json is missing one item, which is "scripting".

It should look like this:

…
"permissions": ["storage", "declarativeContent", "activeTab", "scripting"],
…

This is actually seen on the Getting Started page here.

like image 131
Weybansky Avatar answered Oct 22 '22 19:10

Weybansky


You need scripting permissions to access scripting APIs. Add scripting to your manifest.js file.

"permissions": ["scripting", ...]
like image 27
Yuvaraj Anbarasan Avatar answered Oct 22 '22 17:10

Yuvaraj Anbarasan


You either need to migrate to manifest v3 or use chrome.tabs.executeScript instead of chrome.scripting.executeScript

like image 4
Nadia Chibrikova Avatar answered Oct 22 '22 18:10

Nadia Chibrikova


In my case, the exception log "Cannot read property 'executeScript' of undefined" was pretty misleading.

With correct manifests, it happened, and it was because of typo in the to be injected function, like below.

document.body.style.backgrounColor = color;

corrected it to document.body.style.backgroundColor = color;

and it worked.

like image 1
Jinho Avatar answered Oct 22 '22 17:10

Jinho