IOS interact with the page, look at me enough


With the rapid iterative development trend of mobile APP, the HTML embedded web more and more APP, but in some large and medium-sized APP, especially the business class APP, HTML page has not only satisfied the display function, then HTML can interact with each other, native language transfer value. For example, Ctrip APP in a popular attractions in the web page, click on a scenic spot, you can jump to the original attractions of the details page controller. To this end, I sort out the three most commonly used the most convenient and effective way to interact with the OC JS for everyone to learn exchanges.

The first: JS to OC value.

1 technical solutions: use the JavaScriptCore.framework framework
2 use the scene: the page in the code of a method, such as the click event method, the method of the parameters passed to OC for OC. For example: Ctrip APP a popular attractions in the page, there are a lot of hot spots, click on the image or name of a scenic spot, you can jump to the original attractions of the details page controller.
3 code is as follows:

  • OC to achieve the code: drag into the JavaScriptCore.framework static library, abide by the UIWebViewDelegate proxy agreement.
    in the -webViewDidFinishLoad: method to write the following code:
- (void) webViewDidFinishLoad: (UIWebView *) webView{JSContext *context [webView valueForKeyPath:@ = "documentView.webView.mainFrame.javaScriptContext"]; context[@ "passValue"] = ^{NSArray *arg = [JSContext currentArguments]; for (ID obj in Arg (NSLog) {@ "% @", obj);}}};

Where passValue is the name of the function of the JS, the Arg array which is the function of the passValue JS parameters, that is, JS to pass to the parameters of OC.

  • To achieve the JS Code: function testClick (VaR) {str1=document.getElementById (“text1”).Value; VAR str2=document.getElementById (“text2”).Value; passValue (STR1, STR2);}

In the need to pass the value of the OC function (for example: testClick)) directly call passValue () function, the value can be passed in.


Second: JS to OC value.

1 technical solution: use a custom URL method, each click “
2 usage scenarios: a method of web page code, such as click event method, the parameters of the method for OC value, available for OC. For example: Ctrip APP a popular attractions in the page, there are a lot of hot spots, click on the image or name of a scenic spot, you can jump to the original attractions of the details page controller.
3 code is as follows:

  • To achieve the JS Code: function testClick (VaR) {str1=document.getElementById (“text1”).Value; VAR str2=document.getElementById.Value (“text2”); / / “objc://” for the custom protocol head; / / str1& STR2 to be given to the value of OC, with a “:” as “objc://” and “window.location.href= separation” +str1+ “:: / / +str2}”;

In the need to pass the value of the OC function (for example: testClick ()) to write the code in the format.

Where objc:// is a custom protocol header, STR1 and STR2 are passed to OC for the value of JS.

  • OC to achieve the code:
Abide by / / UIWebViewDelegate proxy protocol. - (BOOL) webView: (UIWebView * webView) shouldStartLoadWithRequest: (NSURLRequest *) request navigationType: (UIWebViewNavigationType) navigationType{/ / get "real-time URL *requestStr = [[request.URL NSString absoluteString] stringByRemovingPercentEncoding]; / / find the custom protocol header" objc:// "if in URL ([requestStr hasPrefix:@" objc:// "]") {/ /: / / "as the center URL is divided into two parts, put into an array of arr NSArray *arr [requestStr =" componentsSeparatedByString:@: / / "]; NSLog (@"% @ ", ARR); / / from the latter half of NSString *paramStr = arr[1]; NSLog (@"% @ ", paramStr); / / to" / "to identify part URL segmentation into several parts, into an array of arr2, when the arr2[0] is empty, arr2[1] for the first A passing parameter value, arr2[2] for the second parameters, and so on NSArray *arr2 = [paramStr componentsSeparatedByString:@ "/"]; NSLog (@ "% @", arr2); / / remove parameters, using if (arr2.count) {NSLog (@ "parameters"); [self doSomeThingWithParamA:arr2[1] andParamB:arr2[2]];}else{NSLog (@ "no parameter");} return NO;} return YES;} / / JS value coming from call - (void) doSomeThingWithParamA: (ID) paramA andParamB: (ID) paramB{NSLog (@ "% @% @", paramA, paramB);}

Third: the use of third party libraries to achieve the mutual value of JS and OC.

1 technical proposal: three party WebViewJavascriptBridge library
2 usage scenarios: a method of web page code, such as click event method, the parameters of the method for OC value, available for OC. For example: Ctrip APP a popular attractions in the page, there are a lot of hot spots, click on the image or name of a scenic spot, you can jump to the original attractions of the details page controller. Or the user information will be passed to the original web page, so that its personalized display
3 code is as follows:

OC pass value to JS

  • JS need to implement the code: function setupWebViewJavascriptBridge (callback) if (window.WebViewJavascriptBridge) {{return}; callback (WebViewJavascriptBridge) if (window.WVJBCallbacks) window.WVJBCallbacks.push (callback) {return}; window.WVJBCallbacks = [callback]; VAR = WVJBIframe document.createElement (‘iframe’); WVJBIframe.style.display =’none’; WVJBIframe.src =’wvjbscheme://__BRIDGE_LOADED__’; document.documentElement.appendChild (WVJBIframe (setTimeout); function (document.documentElement.removeChild) {(WVJBIframe)}, 0)} / / call the above definition of function setupWebViewJavascriptBridge (function (bridge) {//OC value to the’testJavascriptHandler’ JS unified both good custom ‘data’OC is the name of a method; pass;’responseCallback’ is after JS received to the OC callback bridge.registerHandler (‘testJavascriptHandler’, function (data, responseCallback) {/ / print OC pass over the value of log (‘ObjC called testJavascriptHandler with’, data) var responseData Says’:’Right back = {‘Javascript} log (‘JS’ atcha! Responding with’, responseData) / / to the OC callback responseCallback (responseData)})
  • OC need to implement the import Code: third party libraries comply with WebViewJavascriptBridge; UIWebViewDelegate; / / set the third party Bridge is available in [WebViewJavascriptBridge enableLogging] webView and bridge _bridge; / / Association = [WebViewJavascriptBridge bridgeForWebView: web]; [_bridge setWebViewDelegate:self]; //OC to JS value, the two sides defined a unified approach to’testJavascriptHandler’; data is the past [_bridge callHandler:@ “testJavascriptHandler” data:@{@ “age”, “20”: @}]; JS value to OC
  • JS need to implement code: / / click on a button when callbackBt.onclick = function (VaR) {str1=document.getElementById (“text1”).Value; VAR str2=document.getElementById (“text2”).Value; //JS to OC value. ‘passValue’is a unified method for both the custom name;’str1’&’str2’ to pass the value of response for OC to receive; JS (‘passValue’, {str1, bridge.callHandler callback str2}, function (response) {})}
  • OC need to implement the import Code: third party libraries comply with WebViewJavascriptBridge; UIWebViewDelegate; / / set the third party Bridge is available in [WebViewJavascriptBridge enableLogging] webView and bridge _bridge; / / Association = [WebViewJavascriptBridge bridgeForWebView: web]; [_bridge setWebViewDelegate:self]; //js to OC value.’passValue’as the unified method of both custom;’data’ JS came to’responseCallback’value; OC received after the value returned to the JS callback [_bridge “passValue” (ID registerHandler:@ handler:^ data, WVJBResponseCallback responseCallback) {/ / print JS pass over the value of NSLog (@ “% @”, data); / / return to the value of JS responseCallback (@ “received”);}];

It should be noted that, regardless of which side to which the value, the value of the method of the name and the corresponding value of the method to receive the name to be consistent.

If you have any questions, you can refer to my CSDN blog, or comment in the comments area, I will answer one by one. If this article helps you, please give me a cup of tea.