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
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.
You need scripting permissions to access scripting APIs. Add scripting
to your manifest.js
file.
"permissions": ["scripting", ...]
You either need to migrate to manifest v3 or use chrome.tabs.executeScript
instead of chrome.scripting.executeScript
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With