2016-10-06 27 views
1

我想與位於鉻擴展彈出窗口中的iframe進行交互。我知道content.js可以使用manifest.json注入到所有框架中,但是它可以在網頁中使用框架,而不是在擴展的彈出框中使用。從鉻擴展彈出的iframe中的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" 
    } 
} 
+0

你好,我加了我的manifest.json – hadesMM

+0

你試圖注入的內容腳本成在您自己的分機或其他分機的彈出窗口中有一個iframe?這意味着它是你自己的* popup.html *在你的'browser_action'中,但沒有明確說明。 – Makyen

+0

請[edit]成爲話題:包括一個** complete ** [mcve]複製問題。通常,包含* manifest.json *,一些背景,內容和彈出腳本以及HTML。尋求調試幫助的問題(「**爲什麼不是這個代碼工作?」)必須包括:►期望的行爲,►特定問題或錯誤*和*►在問題中重現問題所需的最短代碼**本身**。沒有明確問題陳述的問題對其他讀者無益。請參閱:「**如何創建[mcve] **」,[我可以在此處詢問哪些主題?](http://stackoverflow.com/help/on-topic)和[問]。 – Makyen

回答

4

使用您的內容腳本聲明它注入到彈出裏面的iframe "all_frames": true

"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'); 
    }); 
    
  • 長壽的端口:

    內容.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> 
+0

謝謝你的詳細解答 – hadesMM