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

后端 未结 6 1767
深忆病人
深忆病人 2021-02-01 11:10

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

相关标签:
6条回答
  • 2021-02-01 11:17

    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]];
    
    0 讨论(0)
  • 2021-02-01 11:18

    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

    0 讨论(0)
  • 2021-02-01 11:18

    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/

    0 讨论(0)
  • 2021-02-01 11:23

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

    0 讨论(0)
  • 2021-02-01 11:29

    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.

    0 讨论(0)
  • 2021-02-01 11:39
    [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/

    0 讨论(0)
提交回复
热议问题