shouldStartLoadWithRequest is not called when using AJAX/XMLHttpRequest

iphone, iphone-sdk-3.0

Solution

If you'd like to have a cleaner way of transferring data from JavaScript to Objective-C you could follow these steps:

- Once you have JS data you want to send back to Objective-C then within JS store it in some globally accesible variable e.g. `var myTempData = ...`

- Use the above-mentioned technique of `document.location = 'myapp://fire-some-event'`

- Once in your Objective-C code execute `[myWebView stringByEvaluatingJavaScriptFromString:@"myTempData"]`.

- I think you're done, watch for threading/object-to-string-via-json-encoding.

Problem

I am trying to send method invocations from JavaScript to Objective-C and vice versa. Everything works fine for window.location triggered urls, which are catched by shouldStartLoadWithRequest. Now if I try to use an AJAX call instead, shouldStartLoadWithRequest is not called. Is there a way to do this? Mainly I do not want to be restricted to the max URL size on data that can be passed from JavaScript to Objective-C. My UIWebViewDelegate implements: ``` - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *url = [[request URL] absoluteString]; NSRange urlrange = [url rangeOfString:@"myScheme://"]; if(urlrange.length > 0){ NSLog(@"this is an objective-c call, do not load link: %@", [url substringWithRange:NSMakeRange(urlrange.location, [url length])] ); return NO; } else { NSLog(@"not an objective-c call, load link: ", url ); return YES; } } ``` My JavaScript calls: ``` // works window.location.href = "myScheme://readyHref"; // fails var xmlHttpReq = false; if (window.XMLHttpRequest) { xmlHttpReq = new XMLHttpRequest(); } else if (window.ActiveXObject) { xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttpReq.open('GET', "myScheme://readyAJAX", false); xmlHttpReq.send(); ```

Original source