3

My app has a UIWebView component that calls Obj-c functions using 'webView:shouldStartLoadWithRequest:navigationType:' I parse the request here then call the required Obj-c code.

What I would like to do next is return a value back to the Webview.. e.g. status, message etc..

I've tried a number of solutions at the moment but nothing seems to work. I'm not posting code right now as it's basic enough.

One attempt worth mentioning is using 'stringByEvaluatingJavascriptFromString' that would set global variables in the UIWebView page. I then tried to run an infinite loop (with timeout) that would watch for a change in the global variable. Javascript would then know that a response has come back from the Objective-c function. This doesn't seem to work as the 'infinite loop' doesn't seem to be blocking the javascript thread.

Has anybody come across this problem before.

It looks like there's a function 'windowScriptObject' that may allow me direct access to the UIWebViews script objects. Pity it's not available in iOS, is anybody aware of workarounds for this. Looking into it now..

Thanks.

jim
  • 8,670
  • 15
  • 78
  • 149

2 Answers2

0

Article about this on OS X here.

webView:shouldStartLoadWithRequest:navigationType: is called before the content of the web view is loaded, so there won't be a script object loaded yet. The script object will be loaded when the delegate receives a webView:didClearWindowObject:forFrame: message, and you can then start using [scriptObject evaluateWebScript: @"alert('hello')"] to evaluate javascript and set global variables. What I think your problem is is that there's a race condition between the script object being loaded and your callback, and waiting for the script object should fix the problem.

RC Howe
  • 509
  • 3
  • 16
  • Your solution hinges on 'scriptObject', which is unavailable in iOS unfortunately. – jim Jun 23 '11 at 08:23
  • So use `stringByEvaluatingJavaScriptFromString:` instead. It's a method on UIWebView. It limits execution time to 10 seconds, but you can call it repeatedly from Objective-C to see if anything has changed. – RC Howe Jun 23 '11 at 11:23
0

So i've decided to go down the callback route.

I'll make a call to execute JS code in Obj-C then do nothing in the browser. The next piece of code will be executed in the callback function that is called from Objective-c one all it's work is done.

jim
  • 8,670
  • 15
  • 78
  • 149