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

Getting DOM in Chrome extension popup?

本文关键字:获取 DOM 窗口 Chrome 扩展      更新时间:2023-09-26

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

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

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

我看了这篇相关的文章,但我不太清楚如何将文章中的经验教训用于我的代码。


代码:

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"]
}

您弄错了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);
        });
    }
})