gpt4 book ai didi

javascript - Chrome 扩展 : the js script fires too early despite run_at: document_idle

转载 作者:行者123 更新时间:2023-11-30 09:49:10 27 4
gpt4 key购买 nike

理论上,如果我设置 run_at,我用来选择页面上元素的 .js 应该在页面完全加载后触发。但似乎并非如此。

在我的 content.js 中,我有

    "content_scripts": [
{
"js": ["extensions/jquery-2.2.2.min.js", "content.js"],
"run_at": "document_idle"
}
]

在我的 content.js 中,我只有:

alert("alert");
console.log("hello");
var fullname2 = $('#topcard').find('.profile-info').find('h1').text();
console.log(fullname2);

警报和第一个 console.log 都有效。第二个控制台日志不记录任何内容,因为选择器未能选择任何内容。我知道这一点,因为如果我为 content.js 代码块添加一个 setTimeout,并等待 2 秒,第二个控制台日志会正确显示 fullname2。

知道为什么 content.js 显然在页面完全加载之前触发,以至于选择器找不到任何东西吗?

最佳答案

run_at: "document_idle" 保证脚本在 DOMContentLoaded 事件之后执行,该事件表明所有 static DOM 内容都已解析且可用。

如果一个元素尚不存在,这意味着稍后将通过页面自己的代码动态添加它。

显然,Chrome 无法预测页面何时(如果有的话!)处于“完成”状态。您需要设置自己的标准(例如“当 #topcard 出现时”)。

话虽如此,您的策略应该如下:

  1. 检查元素是否已经存在。如果是,处理它,你就完成了。

  2. 设置 listener for changes in the document 。这是通过 MutationObserver 完成的,为了简单起见,我强烈推荐 mutation-summary library

关于javascript - Chrome 扩展 : the js script fires too early despite run_at: document_idle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37310596/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com