Chrome 扩展:如何根据 Ajax 请求重新加载/重新执行内容脚本
我正在尝试执行某个网站的内容脚本(插入按钮或更改链接),但是我想在用户浏览网站时执行此操作。
问题在于网页是在用户浏览时通过 ajax 请求动态构建的。
我之前在我编写的扩展中通过将 JavaScript 实际注入到网页中解决了这个问题。
我想知道是否有更好的选择,可以在我的内容脚本中注册 ajaxComplete 事件或类似的事件,以便我可以重新执行。
我可以执行以下操作:
function listener()
{
console.debug("listener fired.");
}
document.addEventListener("DOMSubtreeModified", listener, false);
但是,在一页加载期间会触发太多次。
I'm trying to execute a content script for a certain site (inject a button or change the link) however I would like to do this as the user browses the website.
The problem is that the web page is built dynamically with ajax requests as the user browses.
I had solved this earlier in an extension I had written by actually injecting my JavaScript into the web page.
I was wondering whether there is a better alternative of just being able to register for an ajaxComplete event or something similar in my content script so that I can re-execute.
I can do the following:
function listener()
{
console.debug("listener fired.");
}
document.addEventListener("DOMSubtreeModified", listener, false);
However that fires way too many times during one page load.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,没有ajax侦听器,但无论如何它都没有多大帮助,因为您需要捕获页面被修改的时间,而不是发送/接收ajax请求的时间(页面修改通常发生在稍后,并且不能与ajax请求绑定)根本没有)。
DOMSubtreeModified
是正确的方法,只需实施一些保护,防止过于频繁的调用:这样,如果 500 毫秒内没有其他事件,它将触发
listener
。There is no ajax listener that I am aware of, but it wouldn't help much anyway as you need to catch when page is modified, not ajax request is sent/received (page modification usually happens later and can be not tied to ajax request at all).
DOMSubtreeModified
is the right way to go, just implement some protection from too frequent calls:This way it would trigger
listener
if there was no other events within 500ms.我发现的最佳答案有点有趣,涉及一些消息传递内容脚本和background.html 文件之间。
我将发布代码然后解释:
Background.html
content_script.js
您想要解决在 DOM 更改时更新或重新执行脚本的问题。幸运的是,DOM 更改涉及 URL 更改(尽管是 AJAX DOM 更改来更新页面)。
然而,URL 更改会触发 onUpdated 事件。然而,每个选项卡都会触发这些“事件”,我们希望确保我们只关心与内容脚本匹配的事件(您可以在清单中指定匹配项!)。
通过将消息传递给当前选项卡中正在执行的 content_script,我们询问“你是我的内容脚本吗?如果是,请重新启动。”
The best answer I found was a bit interesting and involved a bit of message passing in between the content scripts and the background.html file.
I'll post the code then explain:
Background.html
content_script.js
You want to solve updating or re-executing the script on DOM changes. Luckily the DOM changes involved a URL change (although it was AJAX DOM changes to update the page).
The URL change however fires a onUpdated event. However every tab is firing these "events" and we want to make sure we only care about the one in which we have matched our content scripts too (you can specify a match in the manifest!).
By passing a messgae to the content_script being executed in the current tab, we are asking "Are you my content script? If so, please re-start."