問題描述
我編寫了一個 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 web page 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 上的 ">mutation observer 監聽對其 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
.
示例:Live Copy
<!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 存在的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!