jAckOdE
jAckOdE

Reputation: 2500

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

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

Upvotes: 7

Views: 16368

Answers (6)

Pravin
Pravin

Reputation: 61

Sample code for this is available here,you can check it....very usefull

http://ramkulkarni.com/blog/framework-for-interacting-with-embedded-webview-in-ios-application/

Upvotes: 0

Tim Coulter
Tim Coulter

Reputation: 459

I created an iOS/JS library to help make this easier -- that is, communication in both directions using similar methods. You can check it out here: https://github.com/tcoulter/jockeyjs

Upvotes: 4

Murali
Murali

Reputation: 188

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.

Upvotes: 7

dplusm
dplusm

Reputation: 3548

[webView loadHTMLString:@"<script src=\"filename.js\"></script>" 
      baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];

NSString *result = [webView stringByEvaluatingJavaScriptFromString:@"function(parameter)"];

Give feedback to iOS

window.location = customprefix://function/parameter=value

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([[URL scheme] isEqualToString:@"customprefix"]) {
        // handle function name and paramters
    }
}

I also wrote a guide on how to call and handle different javascript functions from within iOS. http://www.dplusmpage.com/2012/07/20/execute-javascript-on-ios/

Upvotes: 1

Bj&#246;rn Kaiser
Bj&#246;rn Kaiser

Reputation: 9912

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]];

Upvotes: 11

Johan Kool
Johan Kool

Reputation: 15927

Let the javascript load a custom URL, which your app intercepts. It than can parse it, prepare the data and pass it on to your webpage via stringByEvaluatingJavaScriptFromString:.

Upvotes: 1

Related Questions