iOS dev UIWebView and JavaScript (JS) callback interaction

Source: Internet
Author: User

Reference:http://blog.sina.com.cn/s/blog_693de6100102vi3w.html  a lot about object-c (abbreviation: OC, which is the language used by iOS development app) and  js  Interactive articles are more suitable for  mac development, iOS webview  or something different, reference: http://blog.sina.com.cn/s/blog_693de6100102vhuh.html This article provides a good way to solve the interaction of ideas. Naturally, from OC to JS, you can use  stringByEvaluatingJavaScriptFromString:  to achieve. From JS to OC, using a more ingenious design, UIWebView browser intercepts  url requests, custom URLs to intercept interaction please. --------------------------------------------------------------------------------------------------UIWebView is iOS  SDK the control that renders the mesh, when the page is displayed, we can hack the page and display what we want to display. There is a need to use JavaScript knowledge, and the way UIWebView interacts with JavaScript is stringbyevaluatingjavascriptfromstring: With this approach we can invoke JavaScript via OBJC and inject JavaScript. First we look at how to call javascript:[webview stringbyevaluatingjavascriptfromstring:@ "myFunction ();"];    here MyFunction () is our JavaScript method.   To see what to inject into JavaScript, let's start by writing a javascript:function showalert () that needs to be injected ()  {       alert (' In show alert ');  }   saved as Test.js, and then dragged under xcode  group resource.Then use the code to inject this JS (as in the Viewdidload method) when initializing. nsstring *filepath = [[nsbundle mainbundle] pathforresource:@ "test"  ofType:@ "JS" ];  nsstring *jsstring = [[nsstring alloc] initwithcontentsoffile:filepath] ;  [webview stringbyevaluatingjavascriptfromstring:jsstring];   this to inject the above JS, Then we can call the JS method at any time, how to invoke, the above is introduced.   Then we can use JS to invoke the OBJC method.   Of course, the principle is to use UIWebView Redirect request, pass some commands to our UIWebView, in UIWebView delegate method to receive these commands, and according to the command to execute the corresponding OBJC method. This is equivalent to calling the ObjC method in JavaScript. That's a little bit abstract, just look at the code. First we write a javascript  method as follows: [Javascript] function sendcommand (Cmd,param) {       var url= "TestApp:" +cmd+ ":" +param;      document.location =  url;  }  function clicklink () {      sendcommand (" Alert, "How are you?" ;  }   then call this JS method in your HTML   like: [javascript]  "button"  value= "click me! "  onclick= "Clicklink ()"  />   finally we intercept this redirect request in Uiwebvew: #pragma  mark --     #pragma  mark UIWebViewDelegate    -  (BOOL) WebView: (UIWebView  *) Webview shouldstartloadwithrequest: (nsurlrequest *) Request navigationtype: ( Uiwebviewnavigationtype) navigationtype {       nsstring * Requeststring = [[request url] absolutestring];      nsarray  *components = [requeststring componentsseparatedbystring:@ ":"];       if  ([components count] > 1 && [(nsstring *) [ components objectatindex:0] isequaltostring:@ "TestApp"])  {           if ([(nsstring *) [components objectatindex:1] isequaltostring:@ "alert"])            {               UIAlertView *alert = [[UIAlertView alloc]                                       initwithtitle:@ "Alert from  Cocoa touch " message:[components objectAtIndex:2]                                      delegate:self cancelbuttontitle:nil                                       otherbuttontitles:@ "OK",  nil];              [alert show];           }           return NO;      }      return YES;   }      But there is an open source project that you can look at, which allows JavaScript to call the Objective_c method. Called jsbridge-to-cocoa   http://code.google.com/p/jsbridge-to-cocoa/and two other related projects Webviewjavascriptbridge   and  GAJavaScript  should be studied slowly.   Other functions of inserting JS Code we can encapsulate into a JS function, insert this function into the page execution, the code is as follows:if  ([title compare: @ "Google"]== nsorderedsame )  { [webview stringbyevaluatingjavascriptfromstring:@ "var script =  document_createelement_x_x (' script ');   "script.type =  ' text/javascript ';"   "script.text = " function myfunction ()  {    var field =  Document.getelementsbyName (' q ') [0]; "   "field.value= ' Zhu Qilin ';"   "Document.forms[0].submit ();"   "}"; "   "Document.getelementsbytagname_r (' head ') [0].a (script);"];  [webview stringbyevaluatingjavascriptfromstring:@ "MyFunction ();"]; &NBSP, see the above code: A, first create a script by JS tag, type ' Text/javascript '. b, and then insert a string in this tag, this string is a function: MyFunction, this function to implement the Google auto-search keyword function. c, and then use Stringbyevaluatingjavascriptfromstring to execute the MyFunction function.  1.  General call will be local data, encapsulated, directly as the return value of JS. such as: Obtaining the appcode//of the software gets Appcode nsarray *_plist_paths=nssearchpathfordirectoriesindomains ( Nsdocumentdirectory,nsuserdomainmask,yes); nsstring *_plist_paths_path=[_plist_paths  objectatindex:0]; nsarray *_plist_array= [_plist_paths_path componentsseparatedbystring:@ " /"]; nsstring *_appcode=[[nsstring alloc]init]; for  (NSString *item in  _plist_array)  {  if  ([item length]==36)  {   _appcode=item;    break;  } } nslog (@ "current appcode:%@", _appcode);//injected into JS  nsmutablestring *_getapkcode=[[ nsmutablestring alloc]init]; [_getapkcode appendformat:@ " function  _getapkcode ( {"]; [_getapkcode appendformat:@" return  '%@ '; ", _appcode]; [_getapkcode appendstring: @ " }"]; [self.webview stringbyevaluatingjavascriptfromstring:_getapkcode]; [_getapkcode  release];2. Need to interact with the platform: 1. Make a request with a certain meaning such as: (location.href= "Download"); 2. In Method:-(BOOL) WebView: (uiwebview  *) Webview shouldstartloadwithrequest: (nsurlrequest *) Request navigationtype: ( Uiwebviewnavigationtype) Navigationtype, intercept://testmall:http://192.168.1.20:8083 local test page address nsstring *pre_ download=[nsstring stringwithformat:@ "% @downLoad", testmall]; if ([Url hasprefix:pre_download])  { //download code .... }3.  precautions A. There is an IFRAME nested page, JS injection page injection JS is injected into the browser's HTML, for the internal nested IFRAME Framework page, you cannot call to JS. This is the equivalent of invoking the parent page JS. You can use the Parent+ method name to invoke the JS you injected. Parent.pArent the number of uses, can be multiple, does not affect the execution of JS, if less use of the parent, may cause, can not be adjusted to the JSB you injected. There is an interaction processing method. Recommended use, iphone is only responsible for providing JS interface, do not call the HTML internal or other JS interface   Example: Htmlfunction adddownload () {url= ' Www.XXX. Xxx.zip ';d ownload (URL);//Call the iphone to provide the JS interface Adddownloadtask_ret ();//Get the download results from the iphone download interface, here is a local delay method}// Get iphone Download interface execution download results Function adddownloadtask_ret () {var obj=getdownloadtaskresult ();//Here is an interface for the iphone, Responsible for returning the results of the current download execution if ('!=obj| | Undefined!=obj) {//Invoke some of the local post-processing methods. }else{settimeout ("Adddownloadtask_ret2 ();", 1000);}}   -------------------------------------------------

iOS Dev UIWebView interacts with JavaScript (JS) callbacks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.