Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between iOS's native app and webpage's javascript

Tags:

javascript

ios

I have a webpage loaded in a UIWebView, and a javascript function of the page needs to data from native iOs app, a NSString. How can a Js function access the data in native app?

Thanks,

lvreiny

like image 913
jAckOdE Avatar asked Nov 29 '11 08:11

jAckOdE


2 Answers

You can execute JavaScript in your UIWebView from Obj-C. Simply call [webView stringByEvaluatingJavaScriptFromString:@"myJavaScript"];.

I could imagine a setup like this:

Webpage

<html>
   <head>
      <script type="text/javascript">
         function callmeFromObjC(para1) {
             // do something
             alert(para1);
         }
      </script>
   </head>
   <body>
   </body>
</html>

Objective-C

NSString *myParameter = @"myParameter";
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"callmeFromObjC('%@')", myParameter]];
like image 120
Björn Kaiser Avatar answered Sep 30 '22 20:09

Björn Kaiser


With WebViewJavaScriptBridge you can achieve two way communication between javaScript and iOS.

Check this link below for WebViewJavaScriptBridge .

I used this bridge for one of my application for communication between iOS and JS and also vice versa.

https://github.com/marcuswestin/WebViewJavascriptBridge.

like image 30
Murali Avatar answered Sep 30 '22 19:09

Murali