Chrome扩展程序,插入HTML然后继续加载页面 [英] Chrome Extension, Inject HTML then continue loading page
问题描述
我正在写的扩展在页面加载开始时触发一个内容脚本,使用:
The extension I am writing triggers a content script on the start of page load, using:
"run_at": "document_start"
这个功能很好。但是,我需要注入某些东西,然后继续渲染初始页面。如果我的动作脚本只包含:
This works just fine. However, I need to "inject" something and then continue rendering the initial page. If my action script simply contains:
alert("Hello World");
警报将触发,页面将继续呈现。相反,如果操作脚本包含:
The alert will fire and the page will continue rendering. In contrast if the action script contains:
document.write("<span>Hello World!</span>");
这将写Hello World!但不会继续呈现页面。我知道document.write几乎不是一个很好的工具,但它似乎是正确的工具,因为(a)它在DOM的其余部分之前的写作,(b)dom中没有元素来改变实现注射。
This will write "Hello World!" but will not continue rendering the page. I know that "document.write" is almost never a good tool, but it seemed like the right tool because (a) its writing BEFORE the rest of the DOM and (b) there are no elements in the dom to "change" to effectuate the injection.
我认为这样做很好地解释了。但我会提供一点点上下文。最终我想注入一个iframe,将加载在页面的前面的问题。尝试为特定网站提供其他用户体验的扩展用户。
I think that explains the situation fairly well. But I'm going to provide a little more context. Ultimately I want to "inject" an iframe that will load "in front" of the page in question. Trying to provide users of my extension with an alternative user experience for a particular website.
推荐答案
嗯,我看不到太多在 < body>
之前写入的文档即使存在,但是您可以使用DOM操作来执行此操作,而不是 document.write
:
Well, I don't see much point writing to the document before <body>
even exists, but you can do this with DOM manipulation as opposed to document.write
:
var el = document.createElement("span");
el.textContent = "Hello, World!";
document.documentElement.appendChild(el);
这不会阻止后续的DOM解析。
This will not block the subsequent DOM parsing.
如果要符合标准页面结构并将其添加到body元素,可以添加 MutationObserver
等待它(虽然这可能不会比document_end
注入):
If you want to conform to a standard page structure and add it to the body element, you can add a MutationObserver
to wait for it (though this may not be better than "document_end"
injection):
var observer = new MutationObserver(function(mutations) {
mutations.find(function(mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
if(mutation.addedNodes[i].nodeName === "BODY") {
var el = document.createElement("span");
el.textContent = "Hello, World!";
// Clunky way to prepend a node
mutation.addedNodes[i].insertBefore(el, mutation.addedNodes[i].firstChild);
observer.disconnect();
return true; // Early termination of find()
}
}
});
});
observer.observe(document.documentElement, {childList: true});
这篇关于Chrome扩展程序,插入HTML然后继续加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!