本文介绍了Chrome扩展程序:如何在Ajax请求上重新加载/重新执行内容脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图执行内容脚本某特定网站(注按钮或更改链接),但是我想作为用户浏览的网站做到这一点。



问题在于,网页是在用户浏览时使用ajax请求动态构建的。



我之前用我实际编写的扩展来解决此问题注入我的JavaScript到网页中。



我想知道在我的内容脚本中是否有更好的方法可以注册ajaxComplete事件或类似的东西。我可以重新执行



我可以执行以下操作:

 函数监听器()
{
console.debug(listener fired。);
}
document.addEventListener(DOMSubtreeModified,listener,false);

然而,在一次页面加载过程中触发的方式太多了。

解决方案

没有我知道的ajax监听器,但是它无济于事,因为您需要在页面被修改时捕获,而不是发送ajax请求/收到(页面修改通常会在稍后发生,并且可以根本不绑定到ajax请求)。
$ b

DOMSubtreeModified 是正确的方法,只是实施一些保护免受过于频繁的调用:

$ p $ 函数侦听器()
{
console.debug(listener fired。);
}

var timeout = null;
document.addEventListener(DOMSubtreeModified,function(){
if(timeout){
clearTimeout(timeout);
}
timeout = setTimeout(listener,500 );
},false);

如果有的话,它会触发 listener 在500毫秒内没有其他事件。

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.

解决方案

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:

function listener()
{
    console.debug("listener fired.");
}

var timeout = null;
document.addEventListener("DOMSubtreeModified", function() {
    if(timeout) {
        clearTimeout(timeout);
    }
    timeout = setTimeout(listener, 500);
}, false);

This way it would trigger listener if there was no other events within 500ms.

这篇关于Chrome扩展程序:如何在Ajax请求上重新加载/重新执行内容脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:43