【发布时间】:2015-10-16 07:48:32
【问题描述】:
我正在尝试将 <img> 元素附加到我的 chrome 扩展的内容脚本中的 <span> 中。但是,似乎只有当我追加到document 的body 时,追加才有效,如content-script.js 中所述。要重现这一点,请单击以下链接并打开开发工具:
搜索<img>,其id 为seenIcon。它将在附加到 body 时定义,但在所有其他情况下 undefined。
manifest.json
{
"manifest_version": 2,
"name": "Finn.no Property Blacklist",
"description": "Hides finn.no property search results that you've marked as \"seen\".",
"version": "1.0",
"permissions": [
"activeTab",
"http://kart.finn.no/*",
"storage"
],
"content_scripts": [
{
"matches": ["http://kart.finn.no/*"],
"js": ["content-script.js"]
}
],
"web_accessible_resources": [
"*.png"
]
}
content-script.js
console.log("content script!")
function getIconSpanIfExists() {
var spanClassName = "imagePoi";
var matchingElements = document.getElementsByClassName(spanClassName);
if (matchingElements.length > 1) {
console.error(failureMessage("wasn't expecting more than one element with class name " + spanClassName));
return null;
}
if (matchingElements.length === 0) {
return null;
}
return matchingElements[0].parentNode;
}
function htmlReady() {
return getIconSpanIfExists();
}
function addIcons() {
var iconSpan = getIconSpanIfExists();
// Append into body - works.
// var icon = document.createElement("img");
// icon.id = "seenIcon";
// icon.src = chrome.extension.getURL("seen.png");
// document.body.appendChild(icon);
// console.log("appended " + icon.id + " into body");
// Append into span - doesn't work, even though it says childNodes.length is 2.
var icon = document.createElement("img");
icon.id = "seenIcon";
icon.src = chrome.extension.getURL("seen.png");
icon.style.left = "200px";
icon.style.top = "200px";
iconSpan.appendChild(icon);
console.log("appended " + icon.id + " into span with class imagePoi" + " new children: " + iconSpan.childNodes.length);
// Modify innerHTML of span - doesn't work, even though innerHTML has the icon.
// iconSpan.innerHTML += "\n<img id=\"seenIcon\""
// + "src=\"" + chrome.extension.getURL("seen.png") + "\""
// + "style=\"left: 200px; top: 200px;\">";
// console.log(iconSpan.parentNode.id, iconSpan.innerHTML);
}
function init() {
console.log("initialising content script");
if (!htmlReady()) {
console.log("not all HTML is loaded yet; waiting");
var timer = setInterval(waitForHtml, 200);
function waitForHtml() {
console.log("waiting for required HTML elements...");
if (htmlReady()) {
clearInterval(timer);
console.log("... found them!");
addIcons();
}
}
return;
}
}
if (document.readyState === "complete") {
console.log("document is complete")
init();
} else {
console.log("document is not yet ready; adding listener")
window.addEventListener("load", init, false);
}
seen.png
为什么更改没有反映在 DOM 中?
【问题讨论】:
标签: javascript html dom google-chrome-extension content-script