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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With