chrome - 如何使用dom和js在popup.html中显示图像

时间:2013-05-07 13:41:11

标签: javascript image google-chrome dom popup

我正在做一个项目,我需要在Chrome扩展程序弹出显示当前所选标签网站的所有图像,我尝试了很多东西,但弹出窗口总是显示为一个没有任何内容的小弹出窗口。

以下是代码:

Dom.js:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
 if (request.action == "getDOM")
sendResponse({dom: document.body.getElementsByTagName("img")});
 else
   sendResponse({}); // Send nothing..
});

的manifest.json:

{
"manifest_version": 2,
"name": "PrintIt",
"version": "1.0",
"description": "Partilha conteudo com redes sociais",
"browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
},
"permissions": [
    "tabs"
],
"content_scripts": [{
    "matches": [
        "http://www.google.com/*"
    ],
    "js": [
        "dom.js"
    ]
}]

}

Popup.html:

<html>
 <head>
 <script>
chrome.tabs.getSelected(null, function(tab) {
  // Send a request to the content script.
  chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
  document.write(response.dom);
  });
});
 </script>
 </head>
 <body>
 </body>
</html>

我做了console.log(response.dom),我在estension控制台中得到了以下错误:

Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:236
chromeHidden.Port.dispatchOnDisconnect miscellaneous_bindings:236
Error in event handler for 'undefined': Cannot read property 'dom' of
undefined TypeError: Cannot read property 'dom' of undefined
 at chrome-extension://cfboppmcojfddlkbpohfnnnkogpeflgk/popup.js:4:23
 at miscellaneous_bindings:281:11
 at chrome.Event.dispatchToListener (event_bindings:390:21)
 at chrome.Event.dispatch_ (event_bindings:376:27)
 at chrome.Event.dispatch (event_bindings:396:17)
 at Object.chromeHidden.Port.dispatchOnDisconnect (miscellaneous_bindings:239:27) event_bindings:380

1 个答案:

答案 0 :(得分:0)

前段时间我遇到了同样的问题。只是禁止在popup.html中放置脚本代码,因此它无法正常工作。将代码完全放在dom.js中,一切都应该没问题。