【发布时间】:2016-04-21 04:31:52
【问题描述】:
我有一个 Chrome 扩展程序,我想等到元素加载完毕后再将内容注入页面。
我正在尝试注入一个按钮:
myButton = document.createElement('button');
myButton.class = 'mybutton';
document.querySelector('.element_id').appendChild(myButton)
我在内容脚本的顶部有这个。它曾经工作得很好,但后来它停止工作了。显示的错误是:
Uncaught TypeError: Cannot read property 'appendChild' of null
为了等待类 id .element_id 的元素加载,我尝试使用 MutationObserver
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (!mutation.addedNodes) return
for (var i = 0; i < mutation.addedNodes.length; i++) {
if (mutation.addedNodes[i].parentNode == document.querySelector('#outer-container')) {
myButton = document.createElement('button');
myButton.class = 'mybutton';
document.querySelector('.element_id').appendChild(myButton)
}
var node = mutation.addedNodes[i]
}
})
})
observer.observe(document.body, {
childList: true
, subtree: true
, attributes: false
, characterData: false
})
当我使用突变观察器时,页面会加载一个名为outer-container的外部div元素,我无法直接比较类.element_id。 .element_id 类在外部 div 中嵌套了许多层。
但是,上述方法不起作用,我仍然收到 null 属性错误。
有没有更好的方法在注入之前等待某些元素被加载(异步加载)?
【问题讨论】:
标签: javascript google-chrome-extension mutation-observers