Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome.tabs.executeScript not working?

I am trying to learn to use the chrome.tabs.executeScript commend. I've created a simple extension with a browser action. My background.html file currently looks like this:

<html>
<script>
    chrome.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.executeScript(null,{code:"document.body.bgColor='red'"});
        chrome.tabs.executeScript(null, {file: "content_script.js"});
    });
</script>
</html>

The "content_script.js" file contains document.body.bgColor='red'.

When pushing the browser action's button nothing happens. Obviously I'm missing something very basic.

I've checked with console.log that indeed control reaches the chrome.tabs.executeScript calls when the browser action is pressed. Otherwise I'm not sure how to even check if my content script's code is run (it seems not; console.log I put in the content script has no effect, but maybe it shouldn't have one even if the script is run successfully).

like image 988
Gadi A Avatar asked Feb 14 '11 19:02

Gadi A


People also ask

Can't establish connection receiving end does not exist Chrome extension?

receiving end does not exist error is fixed by disabling specific Chrome extensions. We have managed to explain the complete process, and you remember the details in the following list: Fixing the unchecked runtime. lasterror: could not establish a connection.


2 Answers

Make sure you have domain and tab permissions in the manifest:

"permissions": [
    "tabs", "http://*/*", "https://*/*"
]

Then to change body color try:

chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});

Also keep in mind that content scripts are not injected into any chrome:// or extension gallery pages.

like image 57
serg Avatar answered Oct 18 '22 02:10

serg


For those of you still having issues, you need to make sure to reload the extension's permissions in Chrome.

Go to chrome://extensions , scroll to your extension, and click on "reload". Make sure that your permissions have been updated by clicking on the permissions link right next to your extension.

like image 40
Abdo Avatar answered Oct 18 '22 00:10

Abdo