0
我试图从内容脚本传递一个div作为消息到我的background.js
铬扩展,根据什么是described officially here by Google。chrome扩展消息传递空格div
代码考虑的是相当简单:
的manifest.json
有关部分:
{
"name": "Proof of conecpt extension",
"version": "0.0.0.1",
"permissions": [
"activeTab", "storage","tabs"
],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["js/lib/jquery.1.9.0.min.js", "js/content.js"],
"css": ["css/style.css"]
}],
"background":{"scripts":["js/background.js"]},
}
content.js
:
window.onload = function() //init
{
div = document.querySelector("div"); //get the first div in each page for example
chrome.runtime.sendMessage({firstDiv: div.innerHTML});
console.log("message sent.");
}
background.js
:
chrome.runtime.onMessage.addListener(//receive messages
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
console.log(request);
});
这在大多数情况下都能正常工作,我看到了从内容脚本传递的第一个div innerHTML消息。然而,在StackOverfow.com例如,我得到的背景剧本控制台上输出:
from a content script:http://stackoverflow.com/
Object {firstDiv: ""}
信息传递,但似乎第一个div是空的。这显然是错误的信息,因为当我使用Chrome的devtools和手动型“格”在控制台扩展上下文,我看到:
<div id="notify-container"></div>
这究竟是为什么?这是一个安全功能吗?
您需要使用'outerHTML'而不是'innerHTML' https://developer.mozilla.org/zh-CN/docs/Web/API/element.outerHTML – rsanchez
傻傻的我。你是对的。谢谢!发布这个答案,我会接受它。 – user1555863