Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecuteScript method

Basically I'm trying to do a little chrome extension following Google documentation. I'd like to inject a script every time the extension button is clicked. This is my manifest so far:

    {
  "name": "Example",
  "manifest_version": 2,
  "version": "1.0",
  "permissions": [
    "tabs"
  ],
  "description": "My Chrome extension.",
  "browser_action": {
    "default_icon": "icon.png"
  },
   "background": {
    "scripts": ["background.js"]
  }
}

And this is my background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(tab.id, {code: "content_script.js"});
});

The problem is that the content_script is not fired, even trying with such a simple alert("aaa");

Can you please tell me what I'm doing wrong? I can't figure it out.

like image 635
fillobotto Avatar asked Jun 09 '13 16:06

fillobotto


1 Answers

In order to execute a content script on a page, you must request the correct host permissions in your manifest file.

Since you want to insert a content script on click of a browser action button, it suffices to request the activeTab permission. Furthermore, you can drop the tabs permission, to reduce the number of permission warnings to zero!

{
  "name": "Example",
  "manifest_version": 2,
  "version": "1.0",
  "permissions": [
    "activeTab"
  ],
  "browser_action": {
    "default_icon": "icon.png"
  },
   "background": {
    "scripts": ["background.js"]
  }
}

(The activeTab permission has been introduced in Chrome 26. If you need to support Chrome 25 and earlier, add the *://*/* or <all_urls> permissions to the manifest file).

Note: If you add a callback to chrome.tabs.executeScript, you would have received a useful error message in chrome.runtime.lastError.message:

Cannot access contents of url "http....." Extension manifest must request permission to access this host.

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, {
        file: "content_script.js"
    }, function() {
        if (chrome.runtime.lastError) {
            console.error(chrome.runtime.lastError.message);
        }
    });
});
like image 195
Rob W Avatar answered Oct 04 '22 13:10

Rob W