【问题标题】:Getting DOM in Chrome extension popup?在 Chrome 扩展弹出窗口中获取 DOM?
【发布时间】:2014-11-19 07:49:56
【问题描述】:

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

作为热身,我尝试在getBackgroundPage().dummy 中放入一个字符串,而这个popup.js 脚本可见。但是,当我尝试将 DOM 保存在 getBackgroundPage().domContent 中时,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>

ma​​nifest.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"]
}

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-03-03
      • 2011-09-27
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2012-05-07
      相关资源
      最近更新 更多