Chrome扩展:尽管run_at:document_idle尽管js脚本启动得太早, [英] chrome extension: the js script fires too early despite run_at: document_idle
问题描述
在我的content.js中,我有
content_scripts :[
{
js:[extensions / jquery-2.2.2.min.js,content.js],
run_at:document_idle
$ b在我的content.js中,我只是简单地说: alert(alert);
console.log(hello); $('。profile-info')。find('h1')。text();
var fullname2 = $('#topcard')。
console.log(fullname2);
警报和第一个console.log均有效。第二个控制台日志不会记录任何内容,因为选择器未能选择任何内容。我知道这一点,因为如果我为content.js代码块添加setTimeout,并等待2秒钟,则第二个控制台日志将正确显示fullname2。
任何想法为什么content.js显然是在页面完全加载之前触发的,这样选择器无法找到任何东西?
解决方案 run_at:document_idle保证脚本在执行后 DOMContentLoaded
事件表明所有静态 DOM内容都被解析并可用。
如果一个元素还没有存在,这意味着它将被动态地添加到页面自己的代码中。
显然,Chrome无法预测何时(如果曾经!)页面处于完成状态。你需要设置你自己的标准(比如何时出现 #topcard
)。
话虽如此,应该如下:
-
检查元素是否已经存在,如果存在,处理它并完成。 / p>
-
In theory, if I set run_at, the .js that I use to select an element on the page should fire after the page is completely loaded. But it doesn't appear to be the case.
In my content.js, I have
"content_scripts": [
{
"js": ["extensions/jquery-2.2.2.min.js", "content.js"],
"run_at": "document_idle"
}
]
In my content.js, I simply have:
alert("alert");
console.log("hello");
var fullname2 = $('#topcard').find('.profile-info').find('h1').text();
console.log(fullname2);
Both the alert and the first console.log works. The second console log doesn't log anything, because the selector failed to select anything. I know this because if I add a setTimeout for the content.js code block, and wait for 2 seconds, the second console log shows the fullname2 correctly.
Any idea why content.js is apparently firing before the page is fully loaded, such that the selector failed to find anything?
解决方案 run_at: "document_idle"
guarantees that the script is executed after DOMContentLoaded
event that signals that all static DOM content is parsed and available.
If an element doesn't exist yet, this means that it's being added later dynamically, by the page's own code.
Obviously, Chrome has no way to predict when (if ever!) a page is in a "finished" state. You need to set your own criteria (like "when #topcard
appears).
Having said that, your strategy should be as follows:
Check if the element already exists. If it does, process it and you're done.
Set up a listener for changes in the document. This is done through MutationObserver
s, and I highly recommend the mutation-summary
library for simplicity.
这篇关于Chrome扩展:尽管run_at:document_idle尽管js脚本启动得太早,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文