在Chrome扩展程序弹出窗口中获取DOM?

时间:2014-09-24 17:50:11

标签: javascript google-chrome google-chrome-extension

我正在尝试创建一个Chrome扩展程序,在弹出窗口中显示当前页面的DOM。

作为热身,我尝试在getBackgroundPage().dummy中添加一个字符串,这个 popup.js脚本可见。但是,当我尝试在getBackgroundPage().domContent中保存DOM时,popup.js只会将其视为undefined

知道这里可能出现什么问题吗?

我查看了this related post,但我无法弄清楚如何使用该帖子中的课程代码。


代码:

background.js

chrome.extension.getBackgroundPage().dummy = "yo dummy"; 

function doStuffWithDOM(domContent) {
    //console.log("I received the following DOM content:\n" + domContent);
    alert("I received the following DOM content:\n" + domContent);
    //theDomContent = domContent;
    chrome.extension.getBackgroundPage().domContent = domContent;
}

chrome.tabs.onUpdated.addListener(function (tab) {
    //communicate with content.js, get the DOM back...
    chrome.tabs.sendMessage(tab.id, { text: "report_back" }, doStuffWithDOM); //FIXME (doesnt seem to get into doStuffWithDOM)
});

content.js

/* Listen for messages */
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    /* If the received message has the expected format... */
    if (msg.text && (msg.text == "report_back")) {
        /* Call the specified callback, passing 
           the web-pages DOM content as argument */

        //alert("hi from content script"); //DOESN'T WORK ... do we ever get in here?
        sendResponse(document.all[0].outerHTML);
    }
});

popup.js

document.write(chrome.extension.getBackgroundPage().dummy); //WORKS.
document.write(chrome.extension.getBackgroundPage().domContent); //FIXME (shows "undefined")

popup.html

<!doctype html>
<html>
  <head>
    <title>My popup that should display the DOM</title>       
    <script src="popup.js"></script>
  </head>
</html>

的manifest.json

{
"manifest_version": 2,
"name":    "Get HTML example w/ popup",
"version": "0.0",

"background": {
    "persistent": false,
    "scripts": ["background.js"]
},
"content_scripts": [{
    "matches": ["<all_urls>"],
    "js":      ["content.js"]
}],
"browser_action": {
    "default_title": "Get HTML example",
    "default_popup": "popup.html"
},

"permissions": ["tabs"]
}

1 个答案:

答案 0 :(得分:0)

您的chrome.tabs.onUpdated语法错误。

在background.js

chrome.tabs.onUpdated.addListener(function(id,changeInfo,tab){
    if(changeInfo.status=='complete'){ //To send message after the webpage has loaded
        chrome.tabs.sendMessage(tab.id, { text: "report_back" },function(response){
           doStuffWithDOM(response);
        });
    }
})