The interaction between OC and JS (iOS and H5)

Source: Internet
Author: User

在开发过程中,经常会出现需要iOS移动端与H5混编的使用场景。 iOS中加载html网页, 可以使用UIWebView或WKWebView. 本篇博客将介绍两种控件使用过程中如何实现OC与JS的交互。
UIWebViewDelegateprotocol Method//The page is about to start loading-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (Nsurlrequest *Request Navigationtype: (Uiwebviewnavigationtype) Navigationtype; //Web page starts loading- (void) Webviewdidstartload: (UIWebView *) WebView; //Web page loading complete- (void) Webviewdidfinishload: (UIWebView *) WebView; //Page load failed- (void) WebView: (UIWebView *) WebView didfailloadwitherror: (Nserror *) error; //UIWebView comes with a method that can directly invoke the JS code (converted to a string type of JS code)-(Nullable NSString *) stringbyevaluatingjavascriptfromstring: (NSString *) script; //For example, modify the Text property inside the id ' HTML ' tag[Web stringbyevaluatingjavascriptfromstring:@"document.getElementById (' HTML '). innertext= ' Modify content '"]; //You can also execute multiple lines of JS code[Web stringbyevaluatingjavascriptfromstring:@"var div = document.getElementById (' html '); div.innertext = ' Modify content '"];

Using JavaScriptCore for Interactive
JavaScriptCore Classes and protocols:

 JSContext:给JavaScript提供运行的上下文环境 JSValue:JavaScript和Objective-C数据和方法的桥梁 JSManagedValue:管理数据和方法的类 JSVirtualMachine:处理线程相关,使用较少 JSExport:这是一个协议,如果采用协议的方法交互,自己定义的协议必须遵守此协议
1  加入JavaScriptCore 这个framework 2  引入头文件<JavaScriptCore/JavaScriptCore.h> 3  在VC里面加入一个JSContext属性    @property (strong, nonatomic) JSContext *context;    JSContext是什么那? 我们看一下api里面的解释
 is a JavaScript execution environment. All JavaScript execution takes place within a context, and all JavaScript values is tied to a context.
大概意思是说:JSContext是一个JS的执行环境,所有的JS执行都发生在一个context里面, 所有的JS value都绑定到context里面具体使用
 //Initialize ContextSelf.context = [WebView valueforkeypath:@"DocumentView.webView.mainFrame.javaScriptContext"]; //OC Call JS//(1) For example, a method in the script of HTMLfunction Dolike (a,b,c) {}//This method is called through OCNSString* method =@"Dolike"; Jsvalue* function =[Self.context Objectforkeyedsubscript:method];//This a,b,c is the OC call JS when the parameters to the JS pass[function Callwitharguments:@[a,b,c]];//JS call oc//For example, there is a label on the page, click on the button to call the Jump method, where 3 is the parameters passed in<button onclick="Jump (' 3 ')"> Point Me </button>//when clicking on the button in the page, trigger the Jump method, in OC with the following code can capture the jump method, and get JS to pass the parameter ' 3 'self.context[@" Jump"] = ^ (NSString *str) { //here the str value is ' 3 ' (the parameter that JS is passed to OC when it calls OC) };

Wkwebview:
Speaking of Wkwebview, the first thing to say is Wkwebview advantage

1 more features that support HTML5
2 officially declared scrolling refresh rate of up to 60fps and built-in gestures
3 The Uiwebviewdelegate and UIWebView were split into 14 classes and 3 protocols, and many of the previously inconvenient functions were implemented
4 Safari the same JavaScript engine
5 Consumes less memory

Class:

Wkbackforwardlist: A list of previously visited Web pages that can be accessed through back and forward actions. A    page in the back list of the Wkbackforwardlistitem:webview.    wkframeinfo: Contains layout information for a Web page.    wknavigation: Contains the loading progress information for a Web page.    wknavigationaction: Contains information that may allow changes in the navigation of a Web page to determine whether a navigation change has been made.    Wknavigationresponse: Contains information about the return content that may allow the navigation of a page to be changed to determine whether or not to make a navigation change.    wkpreferences: Summarizes a WebView's preferences.    Wkprocesspool: Represents a Web content load pool.    Wkusercontentcontroller: Provides a way to use JavaScript post information and inject script.    Wkscriptmessage: Contains the information sent by the Web page.    Wkuserscript: Represents a user script that can be accepted by a Web page.    wkwebviewconfiguration: Initializes the settings of the WebView.    wkwindowfeatures: Specifies the window properties when a new page is loaded.

Agreement:

      Wknavigationdelegate: Provides a way to track the main window page loading process and determine whether the main window and child windows are loading new pages.      Wkscriptmessagehandler: Provides a callback method for receiving messages from a Web page.      Wkuidelegate: Provides a method callback that displays a Web page with native controls.

Load Mode://Way OneWkwebview *webview =[[Wkwebview alloc] initWithFrame:self.view.bounds]; [WebView loadrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://www.baidu.com"]]]; [Self.view Addsubview:webview]; //Mode twoWkwebviewconfiguration * Configuration =[[Wkwebviewconfiguration alloc] init]; WebView=[[Wkwebview alloc] InitWithFrame:self.view.bounds configuration:configuration]; [WebView loadrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://www.baidu.com"]]]; [Self.view Addsubview:webview]; Protocol Method Introduction:#pragmaMark-wknavigationdelegate//called when the page starts to load- (void) WebView: (Wkwebview *) WebView didstartprovisionalnavigation: (wknavigation *) navigation{}//called when the content starts to return- (void) WebView: (Wkwebview *) WebView didcommitnavigation: (wknavigation *) navigation{}//called after page load is complete- (void) WebView: (Wkwebview *) WebView didfinishnavigation: (wknavigation *) navigation{}//called when a page load fails- (void) WebView: (Wkwebview *) WebView didfailprovisionalnavigation: (wknavigation *) navigation{}//called after receiving a server jump request- (void) WebView: (Wkwebview *) WebView didreceiveserverredirectforprovisionalnavigation: (wknavigation *) navigation{}//after receiving the response, decide whether to jump- (void) WebView: (Wkwebview *) WebView decidepolicyfornavigationresponse: (Wknavigationresponse *) navigationresponse Decisionhandler: (void(^) (wknavigationresponsepolicy)) decisionhandler{NSLog (@"%@", navigationResponse.response.URL.absoluteString); //Allow JumpDecisionhandler (wknavigationresponsepolicyallow);//do not allow jumps//Decisionhandler (wknavigationresponsepolicycancel); } //before sending a request, decide whether to jump- (void) WebView: (Wkwebview *) WebView decidepolicyfornavigationaction: (wknavigationaction *) navigationaction Decisionhandler: (void(^) (wknavigationactionpolicy)) decisionhandler{NSLog (@"%@", navigationAction.request.URL.absoluteString); //Allow JumpDecisionhandler (wknavigationactionpolicyallow);//do not allow jumpsDecisionhandler (wknavigationactionpolicycancel);} #pragmaMark-wkuidelegate//Create a new WebView-(Wkwebview *) WebView: (Wkwebview *) WebView createwebviewwithconfiguration: (wkwebviewconfiguration *) configuration Fornavigationaction: (wknavigationaction *) navigationaction windowfeatures: (Wkwindowfeatures *) windowfeatures{return[[Wkwebview alloc]init];} //Input Box- (void) WebView: (Wkwebview *) WebView runjavascripttextinputpanelwithprompt: (NSString *) prompt DefaultText: (nullable NSString *) DefaultText initiatedbyframe: (Wkframeinfo *) frame Completionhandler: (void(^) (NSString *__nullable result)) completionhandler{Completionhandler (@"http"); } //Confirmation Box- (void) WebView: (Wkwebview *) WebView runjavascriptconfirmpanelwithmessage: (NSString *) message initiatedbyframe: ( Wkframeinfo *) frame Completionhandler: (void(^) (BOOL result)) completionhandler{Completionhandler (YES);}//Warning Box- (void) WebView: (Wkwebview *) WebView runjavascriptalertpanelwithmessage: (NSString *) message initiatedbyframe: (wkframeinfo *) Frame Completionhandler: (void(^) (void)) completionhandler{NSLog (@"%@", message); Completionhandler (); }

The interaction between OC and JS

Wkwebview

Wkwebview's Uidelegate provides three protocol methods that allow the front end to easily intercept JS alert, confirm, prompt methods. In addition, Oc,js intermodulation can be used as follows.

1 OC Call JS

 可以使用webkit这个库
- (void) Evaluatejavascript: (NSString *) javascriptstring Completionhandler: (void(^ _nullable) (_nullable ID, Nserror *_nullable error)) Completionhandler;//For example, OC calls JS method SetName[WebView evaluatejavascript:@"SetName (' Zhang San ')"Completionhandler:nil];//here SetName is the method name defined by JS, the internal ' Zhang San ' is passed to JS parameters. If the SetName method needs to pass in a non-character parameter such as JSON or array, it needs to be converted to a string type using the Format method, calling the Evaluate method. For exampleNSString* para = [NSString stringWithFormat:@"setname ('%@ ')", JSON];

JS Call OC

We're going to use Wkscriptmessagehandler now.

 //First, add attributes to M.@property (nonatomic, strong) Wkusercontentcontroller *USERCC;//1 following the Wkscriptmessagehandler protocol//2 Initializationwkwebviewconfiguration * Config =[[Wkwebviewconfiguration alloc]init]; Self.wkwebviw=[[Wkwebview alloc]initwithframe:self.view.bounds configuration:config]; [Self.wkwebviw loadrequest:[nsurlrequest Requestwithurl:[nsurl URLWITHSTRING:SELF.WEBPAGEURL]]; [Self.view ADDSUBVIEW:SELF.WKWEBVIW]; SELF.USERCC=Config.usercontentcontroller; [SELF.USERCC addscriptmessagehandler:self Name:@"Callosx"]; //This is the equivalent of monitoring the JS callfunction this method[SELF.USERCC addscriptmessagehandler:self name:@"callfunction"]; //when JS emits callfunction This method instruction, we will receive this message in the Wkscriptmessagehandler protocol method . #pragmaMark Wkscriptmessagehandler Delegate-(void) Usercontentcontroller: (Wkusercontentcontroller *) Usercontentcontroller didreceivescriptmessage: (WKScriptMessage *) Message {//In this callback, Message.name represents the method name (' This example is CallFunction '), Message.body represents the parameters that JS has passed to us. }//Finally, the VC must be destroyed when the handler to remove-(void) dealloc{[_usercontentcontroller removescriptmessagehandlerforname:@"callfunction"];}//the corresponding JS code<button onclick="buttonclick (' warm tips ')"> Point Me </button><script>function ButtonClick (string){       //JS calls OC, in the following format//(Window.webkit.messageHandlers.Method_Name.postMessage (PARAMETERTOOC))Window.webkit.messageHandlers.callFunction.postMessage (string)        }       </script>

The interaction between OC and JS (iOS and H5)

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.