等待document.body存在 [英] wait for document.body existence
问题描述
我写了一个chrome扩展,在页面加载之前有效(使用属性run_at:document_start
)。
问题是我想在网页正文创建后立即添加 div
标记。
在那之前 document.body
为空,所以我不能为它添加标签。
I wrote a chrome extension that works before the page is loaded (using the attribute "run_at": "document_start"
).
The problem is that I want to add a div
tag to the webpage body as soon as it is created.
Before that document.body
is null so I can't append tags to it.
我不关心身体的全负荷,我只需要它存在。
I don't care about full load of the body, I just need it to be existent.
我正在尝试找到在html中创建 body
标记时收到警报的最佳方法(未加载)完全,刚刚创建)。我可以写这个案例的事件处理程序吗?
I am trying to find the best way to be alerted when the body
tag in html is created (not loaded fully, just created). Is there any event handler for this case that I can write?
另外,我不想使用 jQuery
或任何其他非内置库。
Also, I don't want to use jQuery
or any other non built-in library.
谢谢!
推荐答案
您可以在上使用变异观察者 document.documentElement
侦听其 childList
的更改,并查看添加的内容是否为 body
。
You could use a mutation observer on document.documentElement
listening for changes to its childList
and looking to see whether the thing that got added is body
.
示例:实时复制
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script>
(function() {
"use strict";
var observer = new MutationObserver(function() {
if (document.body) {
// It exists now
document.body.insertAdjacentHTML(
"beforeend",
"<div>Found <code>body</code></div>"
);
observer.disconnect();
}
});
observer.observe(document.documentElement, {childList: true});
})();
</script>
</head>
<body>
<div id="foo"></div>
</body>
</html>
这篇关于等待document.body存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!