content.js in iframe from chrome-extension popup

2019-01-12 07:59发布

问题:

I am trying to interact with an iframe located in a chrome-extension popup. I know content.js can be injected in all frame using the manifest.json but it's working with frame inside a webpage and not inside the extension's popup.

Is it doable ? I tried many things but I didn't find a solution yet.

my manifest :

{
"name" :"test",
"version": "1.0",
"manifest_version": 2,
"description" :"Scraping Facebook",
"permissions": [
  "cookies",
  "background",
  "tabs",
  "http://*/*",
  "https://*/*",
  "storage",
  "unlimitedStorage"
],
"icons": { "128": "images/pint.png" },
"content_scripts": [
  {
    "matches": [
      "http://*/*",
      "https://*/*"
    ],
    "js": ["jquery-3.1.0.min.js","content.js"],
    "run_at":"document_end"
  }
],
"web_accessible_resources": [
    "http://*/*",
    "https://*/*",
    "styles/*",
    "fonts/*"
],
"background": {
    "scripts": ["background.js"]
  },
"browser_action" :
    {
        "default_popup": "popup.html",
        "default_title": "test"
    }
}

回答1:

Use "all_frames": true in your content script declaration to inject it into an iframe inside the popup:

"content_scripts": [{
    "matches": [ "http://example.com/*" ],
    "js": [ "content.js" ],
    "all_frames": true
}],

Then you can use messaging: the content script initiates it, and the popup script registers a listener.

  • Trivial one-time sendMessage:

    content.js:

    chrome.runtime.sendMessage('test', function(response) {
        console.log(response);
    );
    

    popup.js:

    chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
        console.log('popup got', msg, 'from', sender);
        sendResponse('response');
    });
    
  • Long-lived port:

    content.js:

    var port = chrome.runtime.connect({name: 'test'});
    port.onMessage.addListener(function(msg, port) {
        console.log(msg);
    });
    port.postMessage('from-iframe');
    

    popup.js:

    var iframePort; // in case you want to alter its behavior later in another function
    
    chrome.runtime.onConnect.addListener(function(port) {
        iframePort = port;
        port.onMessage.addListener(function(msg, port) {
            console.log(msg);
        });
        port.postMessage('from-popup');
    });
    

And popup.html:

<html>
  <head>
    <script src="popup.js"></script>
  </head>
  <body>
    <iframe width="500" height="500" src="http://example.com"></iframe>
  </body>
</html>