I'm trying to detect when any ajax call finishes in my UIWebView. I modified the code in this answer: JavaScript detect an AJAX event to the best of my abilities. Here is my attempt:
var s_ajaxListener = new Object();
s_ajaxListener.tempOnReadyStateChange = XMLHttpRequest.prototype.onreadystatechange;
s_ajaxListener.callback = function () {
window.location='ajaxHandler://' + this.url;
};
XMLHttpRequest.prototype.onreadystatechange = function() {
alert("onreadystatechange called");
s_ajaxListener.tempOnReadyStateChange.apply(this, arguments);
if(s_ajaxListener.readyState == 4 && s_ajaxListener.status == 200) {
s_ajaxListener.callback();
}
}
I'm injecting this into the webView but the alert is never firing. If I place an alert at the beginning or end of the script, it'll fire so I'm fairly certain there are no syntax errors.
I'm not a JS guy so I'm hoping this is a trivial problem.
Putting a generic onreadystatechange
in XMLHttpRequest.prototype
didn't work for me. However the code you linked to can be easily adapted to invoke a custom function whenever that event occurs:
var s_ajaxListener = {};
s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
// callback will be invoked on readystatechange
s_ajaxListener.callback = function () {
// "this" will be the XHR object
// it will contain status and readystate
console.log(this);
}
XMLHttpRequest.prototype.open = function(a,b) {
if (!a) var a='';
if (!b) var b='';
s_ajaxListener.tempOpen.apply(this, arguments);
s_ajaxListener.method = a;
s_ajaxListener.url = b;
if (a.toLowerCase() == 'get') {
s_ajaxListener.data = b.split('?');
s_ajaxListener.data = s_ajaxListener.data[1];
}
}
XMLHttpRequest.prototype.send = function(a,b) {
if (!a) var a='';
if (!b) var b='';
s_ajaxListener.tempSend.apply(this, arguments);
if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a;
// assigning callback to onreadystatechange
// instead of calling directly
this.onreadystatechange = s_ajaxListener.callback;
}
http://jsfiddle.net/s6xqu/
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