Chrome extension that runs code when ajax requests happen
When you say...
I figured out another way to do this based on when the DOM changes, but that made loads take a long time, there is just too much going on in the DOM to do it that way. I need to listen for AJAX requests and run my code again when they finish.
...where you using Mutation Events or Mutation Observers? Because I thought Observers where ment to fix that. Ive never done anything with Observers before and used Mutation Summary. It seemed able to do what you want except it didnt start observing until the document was ready/idle (not sure which) so you might have to do a scan on document ready and then fire the observer.
Here's what my test code looked like (in a content script)...
handleChanges = function(summaries) {
// There may be more things to ignore
var ignore = {
SCRIPT: true,
NOSCRIPT: true,
CDATA: true,
'#comment': true
}
summaries.forEach(function(summary) {
summary.added.forEach(function(node) {
if (!ignore[node.nodeName] || (node.parentNode && !ignore[node.parentNode.nodeName]) && node.nodeValue.trim()) {
node.nodeValue='PAEz woz ere - '+node.nodeValue;
}
})
})
}
var observer = new MutationSummary({
callback: handleChanges,
// required
rootNode: document,
// optional, defaults to window.document
observeOwnChanges: false,
// optional, defaults to false
queries: [{
characterData: true
}]
});
And another way of checking for a XMLHttpRequest is to hijack it, simply it can look like (in a content script at document start).....
function injectScript(source) {
var elem = document.createElement("script"); //Create a new script element
elem.type = "text/javascript"; //It's javascript
elem.innerHTML = source; //Assign the source
document.documentElement.appendChild(elem); //Inject it into the DOM
}
injectScript("("+(function() {
function bindResponse(request, response) {
request.__defineGetter__("responseText", function() {
console.warn('Something tried to get the responseText');
console.debug(response);
return response;
})
}
function processResponse(request,caller,method,path) {
bindResponse(request, request.responseText);
}
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, path, async) {
var caller = arguments.callee.caller;
this.addEventListener('readystatechange', function() {
if (this.readyState === 4)
processResponse(this,caller,method,path);
}, true);
return proxied.apply(this, [].slice.call(arguments));
};
}).toString()+")()");
...which I learn't at the mega awesome Supper Happy Fun Blog.
But as you probably know now, thats not enough for ajax driven sites. Normally you have to write something specific for the site or maybe the Mutation Observer will meet your needs.