chrome.tabs.executeScript not working?

2019-01-11 23:21发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

You actually don't need and don't want the 'tabs' permission for executeScript.

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

Should be enough