Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox Extension: Error calling executeScript on file but not code

I'm trying to execute a script in a new tab when that tab is opened.

In my background script I have:

var listener = function (tab) {
    browser.tabs.executeScript(null, { file: "content_scripts/contentScript.js" });
}

browser.tabs.onCreated.addListener(listener);

In contentScript.js:

function foo() {
    console.log("Executed");
}

foo();

From this I get the following error:

Error: Permission denied to access property "chrome"

If I simply execute code rather than call a js script, ex:

browser.tabs.executeScript(null, { code: "console.log("Executed") });

This does not cause the error. Any idea what is causing this?

like image 927
dds9 Avatar asked May 24 '16 17:05

dds9


1 Answers

It doesn't work properly because apparently this bug has not been fixed and still exists in Firefox 59.

You can work around the issue by letting the tab load for some milliseconds before running executeScript on it.

I have tested this an it works for me:

(Remember that this does not work for new blank tabs as in "about:newtab". These can not be accessed for security reasons.)

background.js

var listener = function (tab) {
    setTimeout(()=>{
        browser.tabs.executeScript(tab.id, {file: "/content_scripts/contentScript.js"}).then(()=>{
            console.log("Executed!")
        }).catch(err=>{
            console.error("Not executed:")
            console.error(err)
        })
    },1000) // Add a delay because of this bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1254003
}

browser.tabs.onCreated.addListener(listener);

content_scripts/contentScript.js

function foo() {
    console.log("Executed");
    alert("Executed!");
}

foo();

manifest.json

{

  "description": "Test executeScript api",
  "manifest_version": 2,
  "name": "ExecuteScript-Test",
  "version": "1.0",

  "permissions": [
    "activeTab",
    "tabs",
    "<all_urls>"
  ],

  "background": {
    "scripts": ["background.js"]
  }

}
like image 66
Forivin Avatar answered Sep 19 '22 06:09

Forivin