Intercept Ajax calls in UIWebview - iOS


Step 1

/*
Steps to follow

1. Copy the following code.
2. Paste in text file.
3. Save as ajax_handler.js
4. keep this file in your resource folder

var s_ajaxListener = new Object();
s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
s_ajaxListener.callback = function () {
    window.location='mpAjaxHandler://' + this.url;
};

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;
    s_ajaxListener.callback();

}


Step 2

//.m file
@interface WebViewController ()
{
}
@property (weak, nonatomic) IBOutlet UIWebView *aWebView;

@end

@implementation WebViewController

static NSString *JSHandler;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    JSHandler = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"ajax_handler" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil];

}

#pragma mark - Web Delegates - 

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [webView stringByEvaluatingJavaScriptFromString:JSHandler];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[request.URL absoluteString] containsString://ajex function name]) {


        //do something
        return NO;

    }
    
    return YES;
}

Comments