Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: How to reload/re-execute content script on Ajax request

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.

like image 271
Setheron Avatar asked Sep 06 '11 20:09

Setheron


1 Answers

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.

like image 171
serg Avatar answered Oct 13 '22 23:10

serg