0
我针对的网站几乎是一个Javascript应用程序。所以我需要在加载完成后添加HTML。我试着用MutationObserver,但它仍试图过早执行JavaScript和我碰到下面的错误代码`遗漏的类型错误:无法读取属性“的appendChild”的未定义页面加载完成后在Google Chrome浏览器扩展中运行javascript
我的代码
manifest.json的
{
"manifest_version": 2,
"name": "Test",
"version": "1.0",
"description": "Test Description",
"content_scripts": [{
"js": ["content.js"],
"run_at" : "document_idle",
"matches": ["https://pastvu.com/p/*"]
}]
}
content.js
new MutationObserver(function(mutations, observer) {
addHtml();
observer.disconnect();
}).observe(document.querySelector('body'), {childList: true});
function addHtml(){
var newDiv = document.createElement("div");
newDiv.setAttribute("class","tltp-wrap");
var newLink = document.createElement('a');
newLink.setAttribute('href','http://www.google.com');
var linkButton = document.createElement('span');
linkButton.setAttribute('class','glyphicon glyphicon-map-marker');
newLink.appendChild(linkButton);
newDiv.appendChild(newLink);
document.getElementsByClassName("toolsBtm")[0].appendChild(newDiv);
}
Here is the我针对的页面。正如你可以看到这样
<body>
<script type="text/javascript" src="/js/module/appMain.js?__=wfDkO"></script>
</body>
的<body>
看起来我的目标是要等到身体负荷的html或至少unitil .toolsBtm
DIV存在。
我改变content.js
这和仍然没有运气
new MutationObserver(function(mutations, observer) {
var bodyLoaded = document.getElementsByClassName('toolsBtm');
if (bodyLoaded.length > 0) {
alert('a');
addHtml();
}
}).observe(document.querySelector('body'), {childList: true});
function addHtml(){
var newDiv = document.createElement("div");
newDiv.setAttribute("class","tltp-wrap");
var newLink = document.createElement('a');
newLink.setAttribute('href','http://www.google.com');
var linkButton = document.createElement('span');
linkButton.setAttribute('class','glyphicon glyphicon-map-marker');
newLink.appendChild(linkButton);
newDiv.appendChild(newLink);
document.getElementsByClassName("toolsBtm")[0].appendChild(newDiv);
}
您是否尝试过使用''run_at“:”document_end“'? –
@FiriceNguyen'document_end'不晚于'document_idle'。 – Xan
@FiriceNguyen是的,我做了 –