Reputation: 491
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.
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;
};
reference: chrome developers -> Getting started
Upvotes: 39
Views: 27273
Reputation: 4779
I found that chrome.scripting.executeScript
works in popup but not in content scripts.
This is a super simple popup example in React. You click on the button and it shows the page title.
export function Popup() {
const [title, setTitle] = useState("");
const onClick = async () => {
const [tab] = await chrome.tabs.query({ currentWindow: true, active: true });
const [res] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => document.title,
});
setTitle(res.result);
};
return (
<div className="popup">
<button onClick={onClick}>Click</button>
{title}
</div>
);
}
Upvotes: 2
Reputation: 49220
Remove and load the extension back! Despite adding "permissions": ["scripting"]
this is what I had to do.
Upvotes: 6
Reputation: 657
You need scripting permissions to access scripting APIs. Add scripting
to your manifest.js
file.
"permissions": ["scripting", ...]
Upvotes: 13
Reputation: 41
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.
Upvotes: 3
Reputation: 706
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.
Upvotes: 59
Reputation: 5036
You either need to migrate to manifest v3 or use chrome.tabs.executeScript
instead of chrome.scripting.executeScript
Upvotes: 6