[英]removeChild not working in chrome extension
I'm trying to remove all the link elements with a rel tag of "stylesheet" using node.removeChild
from a webpage but it will not work. 我正在尝试从网页上使用node.removeChild
删除带有rel标签为“ stylesheet”的所有链接元素 ,但它将无法正常工作。 I know chrome extensions have some limitations for security reasons but I don't seem to find if this problem is caused by these limitations or not. 我知道chrome扩展出于安全原因有一些限制,但是我似乎没有发现此问题是否由这些限制引起。
If I log styles[i].parentElement
it gives me the body element so that's working correctly. 如果我记录了styles[i].parentElement
它给了我body元素,因此可以正常工作。
Any help would be greatly appreciated. 任何帮助将不胜感激。
manifest.json: manifest.json:
{
"manifest_version": 2,
"name": "Leho Styler",
"description": "This extension gives leho a whole new styling to better please the eye.",
"version": "0.1.0",
"content_scripts": [
{
"matches": [
"https://leho.howest.be/*",
"https://leho.howest.be/*/*",
"http://leho.howest.be/*",
"http://leho.howest.be/*/*"
],
"css": [
"reset.css",
"leho.css"
],
"js": ["leho.js"]
}
]
} }
leho.js (content script) leho.js (内容脚本)
var styles = document.getElementsByTagName('link');
function init() {
for (var i = 0; i < styles.length; i++) {
if (styles[i].rel == "stylesheet") {
styles[i].parentElement.removeChild(styles[i]);
}
}
}
init();
First of all, change the Query to var styles = document.querySelectorAll ("link[rel='stylesheet']")
- this gets rid of the unnecessary if-block. 首先,将查询更改为var styles = document.querySelectorAll ("link[rel='stylesheet']")
-这摆脱了不必要的if块。 Second, are you sure the DOM is loaded when init() is called? 其次,您确定在调用init()时已加载DOM吗? For this, instead of calling init directly, try adding this line: document.addEventListener ("DOMContentLoaded", init);
为此,而不是直接调用init,请尝试添加以下行: document.addEventListener ("DOMContentLoaded", init);
- this calls init once the DOM is available. -一旦DOM可用,它将调用init。 As far as I know, this can also be done inside the manifest file, though I do not know what the default is. 据我所知,这也可以在清单文件中完成,尽管我不知道默认值是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.