【问题标题】:Chrome Extension, Inject HTML then continue loading pageChrome 扩展,注入 HTML 然后继续加载页面
【发布时间】:2016-05-31 00:40:11
【问题描述】:

我正在编写的扩展程序在页面加载开始时触发内容脚本,使用:

"run_at":   "document_start"

这很好用。但是,我需要“注入”一些东西,然后继续渲染初始页面。如果我的动作脚本只包含:

alert("Hello World");

警报将触发,页面将继续呈现。相反,如果动作脚本包含:

document.write("<span>Hello World!</span>");

这将写“Hello World!”但不会继续渲染页面。我知道“document.write”几乎从来都不是一个好工具,但它似乎是正确的工具,因为(a)它在 DOM 的其余部分之前编写,并且(b)dom 中没有要“更改”为的元素进行注射。

我认为这很好地解释了这种情况。但我将提供更多背景信息。最终,我想“注入”一个 iframe,它将加载到相关页面的“前面”。尝试为我的扩展程序的用户提供特定网站的替代用户体验。

【问题讨论】:

  • 我建议您在 document_end 运行脚本并修改完整加载的 DOM,而不是尝试在“飞行中”修改它
  • 我不明白这是一个建设性的评论。我在问如何做某事。我完全同意通常最好使用您建议的方法。但就我的目的而言,它不起作用。我尝试加载的页面大约需要 2 分钟才能完全加载。我的脚本的全部目的是允许用户界面在页面加载时开始执行某些操作。
  • 在我个人看来,Message Passing 可以很好用。这篇相关的 SO 帖子 - Message Passing Example From Chrome Extensions 可能会有所帮助。
  • @Teyam 这有什么关系?
  • In the case of "document_start", the files are injected after any files from css, but before any other DOM is constructed or any other script is run. 所以,当DOM 尚不存在时,您正在尝试修改它。

标签: javascript html google-chrome dom google-chrome-extension


【解决方案1】:

好吧,我认为写入文档没有什么意义之前 &lt;body&gt; 甚至存在,但是您可以使用 DOM 操作而不是 document.write

var el = document.createElement("span");
el.textContent = "Hello, World!";
document.documentElement.appendChild(el);

这不会阻塞后续的DOM解析。

如果你想符合标准的页面结构并将其添加到body元素中,可以添加一个MutationObserver来等待它(虽然这可能不如"document_end"注入):

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});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2011-08-04
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多