Search code examples
objective-ciosuiwebviewuiwebviewdelegate

Javascript to Obj-c request.. returning value back to Javascript


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.


Solution

  • 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.