在Chrome扩展弹出窗口中获取DOM
Getting DOM in Chrome extension popup?
我正在尝试创建一个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);
});
}
})
相关文章:
- Ember.js-获取DOM元素的模型数据
- 如何获取dom元素的代码行号
- 如何使用d3.jsj或jquery获取DOM
- 如何获取dom修改的选择框的当前所选选项
- 获取DOM中属性名称以某个字符串开头的所有HTML元素
- 在插入符号位置获取DOM元素
- 使用 jQuery 获取 DOM 元素的 XPath
- 获取DOM元素的性能差异
- 在 GWT 中按属性获取 DOM 元素
- Chrome扩展程序获取DOM文本并在弹出窗口中显示.html然后单击按钮
- jQuery:在具有相同类的对象列表中获取 DOM 中的对象编号
- 是否可以从外部样式表中获取 dom 元素的特定 css 属性的值,而不是从计算的样式表中获取
- 获取 DOM 中的拉斐尔 id 属性
- 如何获取 dom 元素的当前 html
- 如何在 YUI 事件处理程序中获取 DOM 节点
- 如何在javascript中获取DOM元素内容的二进制表示
- 使用 JavaScript 从 AJAX 响应中获取 DOM 元素
- 从字符串中获取 DOM
- 如何在电子应用程序中从浏览器窗口获取DOM树
- 哞.无法在 iframe 中获取 DOM 元素