简体   繁体   中英

Can't send data out of executeScript in chrome-extension

I am developing one chrome extension which can extract all the meta tags of the current tab. I am using ReactJs as the main development environment and I have placed my chrome related code in its componentWillMount() method.

componentWillMount() {
const code =
    "let metas = document.getElementsByTagName('meta');" +
    "let newMetas = []" +
    "for (let meta of metas) {" +
    " newMetas.push({name: meta.name, content: meta.content});" +
    "}" +
    "newMetas;";

chrome.tabs.executeScript(null, {
  code: code
}, function (results) {
  console.log(results);  // <=== Here I get 'null' value
  if (!results) {       
    return;
  }      
})}

this is my manifest.json file

    {
  "manifest_version": 2,
  "name": "Northwind",
  "description": "Just a simple all with all northwind employees",
  "version": "1.0",
  "browser_action": {
    "default_icon": "./img/ic-logo.png",
    "default_popup": "./index.html"
  },
  "permissions": [
    "http://www.amazon.com/",
    "tabs"
  ],
  "web_accessible_resources": ["script.js"],
  "content_scripts": [{
      "matches": ["http://www.amazon.com/*"],
      "js": ["app.js"]
    }
  ] 
}

app.js is the build file generated by the react.

I have been reading and searching for this but did not get any clues of why it's not working.

Another issue is that when I put console.log('done') in my script, it's not displayed as well so I guess there is some problem with the config as well.

Thanks so much for your help.

When you are using chrome.tabs.executeScript you have to specify host in the permissions field of the manifest.
It is called programmatic injection :

To insert code into a page, your extension must have cross-origin permissions for the page. It also must be able to use the chrome.tabs module. You can get both kinds of permission using the manifest file's permissions field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM