如何在页面的 Javascript 执行后加载内容脚本? [英] How to get a content script to load AFTER a page's Javascript has executed?

查看:30
本文介绍了如何在页面的 Javascript 执行后加载内容脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的扩展程序应该加载一个内容脚本 searchTopic.js,只有在它注入的页面已经完全加载之后(是的,我在扩展程序清单中将run_at"设置为document_end"),但实际上它在所有 DOM 对象创建之前加载(关键的对象是通过页面中的一些 Javascript 创建的).所以,问题是,我怎样才能等到页面的 Javascript 执行完毕?这是我的清单:

My extension is supposed to load a content script, searchTopic.js, only after the page it's injected into has already fully loaded (yes, I have set "run_at" to "document_end" in the extension manifest), but in fact it's loading before all the DOM objects have been created (the crucial ones are created via some Javascript in the page). So, the question is, how can I wait until the page's Javascript has executed? Here's my manifest:

"content_scripts": [
  {
  "run_at": "document_end",
  "matches": ["https://groups.google.com/forum/*"],
  "js": ["searchTopic.js"]
  }
],

推荐答案

"run_at": "document_end" 等价于 DOMContentLoaded. 也就是说,它在加载 static HTML 之后触发,但在慢速图像之前触发和缓慢完成 javascript.

"run_at": "document_end" is the equivalent to DOMContentLoaded. That is, it fires after the static HTML is loaded, but before slow images and slow finishing javascript.

因此,您不能仅通过单独设置清单来设置内容脚本以在页面的 JS 之后触发.您必须在内容脚本中为此编写代码.

So you cannot set a content script to fire after the page's JS, just by setting the manifest alone. You must code for this in the content script itself.

对于内容脚本,"run_at": "document_end" 将在 onload 事件之前触发(与默认的 document_idle 不同 - 它可以在不可预测的时间开火).

For content scripts, "run_at": "document_end" will fire before the onload event (unlike the default document_idle -- which can fire at unpredictable times).

因此,第一步是在您的内容脚本 (searchTopic.js) 中等待 load 事件和类似代码:

So, the first step is to wait for the load event with code like this in your content script (searchTopic.js):

window.addEventListener ("load", myMain, false);

function myMain (evt) {
    // DO YOUR STUFF HERE.
}


如果您关心的脚本需要一段时间才能完成,您将不得不根据具体情况轮询某些条件.例如:


In the case where the script you care about takes a while to finish, you will have to poll for some condition on a case-by-case basis. For example:

window.addEventListener ("load", myMain, false);

function myMain (evt) {
    var jsInitChecktimer = setInterval (checkForJS_Finish, 111);

    function checkForJS_Finish () {
        if (    typeof SOME_GLOBAL_VAR != "undefined"
            ||  document.querySelector ("SOME_INDICATOR_NODE_css_SELECTOR")
        ) {
            clearInterval (jsInitChecktimer);
            // DO YOUR STUFF HERE.
        }
    }
}

这篇关于如何在页面的 Javascript 执行后加载内容脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆