来自chrome-extension popup的iframe中的content.js

时间:2016-10-06 16:24:05

标签: iframe google-chrome-extension

我正在尝试与位于Chrome扩展程序弹出窗口中的iframe进行交互。我知道可以使用manifest.json在所有帧中注入content.js,但是它在网页内部使用框架,而不是在扩展程序的弹出窗口内。

可行吗?我尝试了很多东西,但我还没有找到解决方案。

我的清单:

{
"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 个答案:

答案 0 :(得分:8)

在内容脚本声明中使用"all_frames": true将其注入弹出框内的iframe:

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

然后你可以使用messaging:内容脚本启动它,弹出脚本注册一个监听器。

  • 琐碎的一次性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');
    });
    
  • 长寿端口:

    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');
    });
    

popup.html:

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