Search code examples
google-chrome-extension

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).


Solution

  • 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.