Suggestions on how to communicate with JS running in UIWebView on an obj-c hosting application?

I plan to have an iphone application for the shell with uiwebview, with the bulk of my application running through javascript in uiwebview.

Now I know that it is easy to communicate from obj-c to javascript using stringByEvaluatingJavaScriptFromString, however, is there a good recommended way to communicate from javascript to obj-c?

thanks

+6
javascript objective-c iphone uiwebview
source share
4 answers

I always use an approach in which the application translates to a special URL:

window.location = "myapp://somemessage/someargument"; 

And when the application catches this in the following function:

 -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSURL *url = [request URL]; if ( [[url scheme] isEqualToString:@"myapp"] ) { [self handleJSEvent:url]; return NO; } return YES; } 

In addition, depending on what you need, you can use some kind of event queue that you retrieve using JSON.stringify(events) in response to a message sent to the application using the method described above. For communication from an application with js, JSON is also very suitable.

If there is a standard or standard way to do this, I explicitly skipped it.

+12
source share

There is a very good method for calling javascript inside a UIWebView:

 [webView stringByEvaluatingJavaScriptFromString:@"yourJSFunction('some_data');"]; 

callbacks are best done as MVDS mentioned through Url:

 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
+2
source share

I just created a library that will facilitate this post for you, mainly using the method described by mvds and Ondrej. Includes two-way communication, jQuery event-style, with additional JSON payloads with multiple listeners. Check this out: https://github.com/tcoulter/jockeyjs

+2
source share

Perhaps changing the hash of the url?

+1
source share

All Articles