NativeH5 solution for Native interaction with H5

Source: Internet
Author: User

NativeH5 solution for Native interaction with H5
1. Directly load pages in native code1. Specific cases

Loading local/network HTML5 as function overview page

2. Sample Code

// Local

  1. -(Void) loadLocalPage :( UIWebView *) webView
  2. {
  3. NSString * htmlPath = [[NSBundle mainBundle] pathForResource: @ "demo" ofType: @ "html"];
  4. NSString * appHtml = [NSString stringWithContentsOfFile: htmlPath encoding: NSUTF8StringEncodingerror: nil];
  5. NSURL * baseURL = [NSURLfileURLWithPath: htmlPath];
  6. [WebView loadHTMLString: appHtmlbaseURL: baseURL];
  7. }

 

// Network

-(Void) loadWebPage :( UIWebView *) webView

  1. {
  2. NSURL * url = [NSURLURLWithString: @ "http://www.baidu.com"];
  3. NSURLRequest * request = [NSURLRequestrequestWithURL: url];
  4. [WebView loadRequest: request];
  5. }

 

 

3. Additional operations

In iOS, the container that carries the webpage is UIWebView, which can be used as a proxy to listen To webpage loading;

During the loading process of B, we can also obtain the meta value in the webpage, such as the Code:

NSString * Invalid URL = [messWebViewstringByEvaluatingJavaScriptFromString: @ "document. getElementsByName (\" invalid URL \ ") [0]. content"];

 

The value corresponding to the URL of the response is obtained from meta;

C intercepts the requests currently initiated so that native can implement corresponding control, such as code:

  1. -(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) requestnavigationType :( UIWebViewNavigationType) navigationType
  2. {
  3. NSString * requestString = [[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
  4. If ([requestString hasPrefix: @ "http: // customersharetrigger"]) {
  5. // Perform some operations
  6. Return NO;
  7. }
  8. Return YES;
  9. } // You can listen to this request for control;

 

 

Ii. native code operation page elements 1. Case studies

After h5.

2. Sample Code

A. Obtain the url of the current page.

  1. -(Void) webViewDidFinishLoad :( UIWebView *) webView {
  2. NSString * currentURL = [webView stringByEvaluatingJavaScriptFromString: @ "document. location. href"];
  3. }

 

 

B. Obtain the page title:

  1. NSString * currentURL = [webViewstringByEvaluatingJavaScriptFromString: @ "document. location. href"];
  2. NSString * title = [webviewstringByEvaluatingJavaScriptFromString: @ "document. title"];

 

C. Modify the value of the interface element.

  1. NSString * js_result = [webViewstringByEvaluatingJavaScriptFromString: @ "document. getElementsByName ('q') [0]. value = 'zhu Yulin ';"];

D. Form submission:

  1. NSString * js_result2 = [webView stringByEvaluatingJavaScriptFromString: @ "document. forms [0]. submit ();"];
3. Code Description

The stringByEvaluatingJavaScriptFromString method can embed javascript code snippets into the page. This method enables iOS to interact with webpage elements in UIWebView, such as the preceding code snippets.

The function is very powerful and relatively simple to use. With this function, we can easily operate on page elements, insert a JS method directly, and then call this method for execution;

Iii. native code processing: Local H5 + JS1. specific cases

The graph needs to be dynamically displayed. If the drawing is loaded directly, it is very slow. Therefore, the local placement template is used, parameters are passed in, and the template is automatically drawn to improve the experience and speed up the drawing;

2. Sample Code
  1. -(Void) loadWebPage :( UIWebView *) webView
  2. {
  3. NSURL * localPathURL = [[NSBundlemainBundle] URLForResource: @ "detail" withExtension: @ "html" subdirectory: @ "htmlResources"];
  4. NSString * localPathUrl = [localPathURLabsoluteString];
  5. NSString * localParamPathUrl = [NSStringstringWithFormat: @ "% @? Symbol = % @ & t = % f ", localPathUrl, self. stockCode, self. time];
  6. NSURL * requestURL = [NSURLURLWithString: localParamPathUrl];
  7. [WebView loadRequest: [NSURLRequestrequestWithURL: requestURL];
  8. }

 

 

3. Code Description

A here we need to drag the H5 template using an absolute path, that is, select CreateFolder Reference. Only in this way can we ensure that H5 can be called to use the local JS Code. Otherwise, the loading will fail. This was originally found for many reasons, finally, the problem was selected during the drag-in process;

B. If you want to add parameters, convert them to string and then to URL;

4. Interaction between native code and web pages 1. Specific cases

Native code and H5 call methods, PASS Parameters, and callback data;

2. Third-Party implementation

WebViewJavascriptBridge, the open-source library perfectly solves the interaction between native code and H5;

3. Sample Code

1. initialize a webview (viewdidload)

  1. UIWebView * webView = [[UIWebView alloc] initWithFrame: self. view. bounds];
  2. [Self. view addSubview: webView];

 

 

2. associate this webview with WebViewJavascriptBridge (viewdidload)

  1. If (_ bridge) {return ;}
  2. [WebViewJavascriptBridge enableLogging];
  3. _ Bridge = [WebViewJavascriptBridgebridgeForWebView: webView webViewDelegate: self handler: ^ (id data, WVJBResponseCallback responseCallback ){
  4. NSLog (@ "ObjC received message from JS: % @", data );
  5. ResponseCallback (@ "Response formessage from ObjC ");
  6. }];

 

Now webview is connected to js. The following describes the mutual transfer of methods and their parameters.

 

(1) js oc adjustment method (you can pass a value to the oc method through data, and then return the value to js using responseCallback)

  1. [_ BridgeregisterHandler: @ "testObjcCallback" handler: ^ (id data, WVJBResponseCallback responseCallback ){
  2. NSLog (@ "testObjcCallback called: % @", data );
  3. ResponseCallback (@ "Response fromtestObjcCallback ");
  4. }];

 

 

Note the testObjcCallback method. The name of html must be the same as that of ios. Of course, this name can be customized on both sides. Simple and clear.

 

(2) Adjust js methods in oc (data can be used to pass values and response can be used to accept the return values in js)

 
  1. Id data =@ {@ "greetingFromObjC": @ "Hi there, JS! "};
  2. [_ BridgecallHandler: @ "testJavascriptHandler" data: data responseCallback: ^ (idresponse ){
  3. NSLog (@ "testJavascriptHandlerresponded: % @", response );
  4. }];

 

 

Note that testJavascriptHandler is also a method identifier.

 

(3) passing oc values to js (using response to accept returned values)

 
  1. [_ Bridge send: @ "Astring sent from ObjC to JS" responseCallback: ^ (id response ){
  2. NSLog (@ "sendMessage got response: % @", response );
  3. }];

 

 

(4) passing oc values to js (no return value)

  1. [_ Bridge send: @ "A string sent from ObjC after Webview hasloaded."];

V. Summary

There are various forms of interaction between Native and H5. As H5 matures, the future trend is that the two are inseparable, making apps more flexible and effective, it also improves the development efficiency and iteration cycle to a certain extent and is a required solution for enterprise-level mobile application development.

Related Article

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.