Interaction between JS and OC in UIWebView: Use of WebViewJavascriptBridge and interaction between wkwebviewjs oc

Source: Internet
Author: User

Interaction between JS and OC in UIWebView: Use of WebViewJavascriptBridge and interaction between wkwebviewjs oc
I. Summary

Nowadays, many applications are released on multiple platforms, so many programmers are beginning to use the design model of Hybrid App. It is to embed a webpage into an app. As long as you write a webpage code, you can run it on different systems. In iOS, most apps use WebView to load webpages. Due to functional requirements and other reasons, the Code should not interact with webpages.

Ii. Principles

In iOS, the local Javascript language is called through the instance method stringByEvaluatingJavaScriptFromString: In UIWebView. This method passes in JS Code as a string object.

[webView stringByEvaluatingJavaScriptFromString:@"Math.random();"];

While JS calls local code, there is no ready-made API, but it needs to be implemented indirectly through some methods. By using the proxy method of UIWebView, all network requests initiated by UIWebView can be notified at the Native layer through the delegate function. In this way, we can initiate a custom network request in UIWebView, for example, 'wvjbscheme: // _ BRIDGE_LOADED __'. Therefore, in the delegate function of UIWebView, we intercept the url. If we find it is our custom url, we will not load the content and execute the corresponding call logic.

Iii. Use of WebViewJavascriptBridge

1. Introduction to WebViewJavascriptBridge

WebViewJavascriptBridge supports versions earlier than iOS6 and is used to support native iOS and javascript interaction. Next we will talk about the basic principles of WebViewJavascriptBridge and how to use it, including iOS and JS.

First, let's look at the Webview proxy interception code in WebViewJavascriptBridge. m:

- (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener{    if (webView != _webView) { return; }        NSURL *url = [request URL];    if ([_base isCorrectProcotocolScheme:url]) {        if ([_base isBridgeLoadedURL:url]) {            [_base injectJavascriptFile];        } else if ([_base isQueueMessageURL:url]) {            NSString *messageQueueString = [self _evaluateJavascript:[_base webViewJavascriptFetchQueyCommand]];            [_base flushMessageQueue:messageQueueString];        } else {            [_base logUnkownMessage:url];        }        [listener ignore];    } else if (_webViewDelegate && [_webViewDelegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:request:frame:decisionListener:)]) {        [_webViewDelegate webView:webView decidePolicyForNavigationAction:actionInformation request:request frame:frame decisionListener:listener];    } else {        [listener use];    }}

WebViewJavascriptBridge intercepts scheme through the webview proxy, and then injects the corresponding JS. After blocking, it first uses the-isBridgeLoadedURL: method to determine whether the URL needs to be a bridge URL. If yes, the injectJavascriptFile method is used to inject Javascript. Otherwise, the URL is determined to be a queue message. If yes, the query command JS is executed and the message queue is refreshed. If none of them match, the URL is identified as an unknown message.

 

2. Use of WebViewJavascriptBridge

First, you need to access this framework in JS. This Code remains unchanged.

/*** This is the js access framework function */function setupWebViewJavascriptBridge (callback) {if (window. webViewJavascriptBridge) {return callback (WebViewJavascriptBridge);} if (window. WVJBCallbacks) {return window. WVJBCallbacks. push (callback);} window. WVJBCallbacks = [callback]; var WVJBIframe = document. createElement ('iframe'); WVJBIframe. style. display = 'none'; WVJBIframe. src = 'wvjbscheme: // _ BRIDGE_LOADED _ '; document.doc umentElement. appendChild (WVJBIframe); setTimeout (function () {document.doc umentElement. removeChild (WVJBIframe)}, 0 )}

 

Then the JS function to be called by OC should be registered using bridge. registerHandler in the following function, and the OC method to be called by JS should also be called using bridge. callHandler in the following function.

/*** The JS function called by OC must be registered here. To call the OC method, call */setupWebViewJavascriptBridge (function (bridge) {var uniqueId = 1 function log (message, data) {var log = document. getElementById ('log') var el = document. createElement ('div ') el. className = 'logline' el. innerHTML = uniqueId ++ '. '+ message +': <br/> '+ JSON. stringify (data) if (log. children. length) {log. insertBefore (el, log. children [0])} else {log. appendChild (el) }}// Register a function called by OC without the bridge parameter. registerHandler ('webviewdidload', function () {log ("WebViewDidLoad")}) // registers a function called for OC, receives a parameter from OC and a callback to process the bridge. registerHandler ('Oc _ Call_JS ', function (data, responseCallback) {log ('Oc calls js-', data) var responseData = {'javascript response ': 'Oc successfully called JS! '} Log ('response after js is called-', responseData) responseCallback (responseData)}) document. body. appendChild (document. createElement ('br ') var callbackButton = document. getElementById ('buttons '). appendChild (document. createElement ('button ') callbackButton. innerHTML = 'js _ call_objc' callbackButton. onclick = function (e) {e. preventDefault () log ('js call OC ') // call the OC method bridge here. callHandler ('js _ call_objc', {'foo': 'bar'}, function (response) {log ('js call OC sucess and get OC rsp ', response )})}})

Note that the code in the setupWebViewJavascriptBridge (function (bridge) {} function body cannot be incorrect. Otherwise, no callback is triggered and no logs are printed. (JavaScript is the script language, run to the wrong place to stop running ).

 

In the OC section, first open the logging system of the framework and associate it with webView.

[WebViewJavascriptBridge enableLogging];        _bridge = [WebViewJavascriptBridge bridgeForWebView:webView];

The OC method that JS needs to call should be registered in the OC code

[_ Bridge registerHandler: @ "JS_Call_ObjC" handler: ^ (id data, WVJBResponseCallback responseCallback) {NSLog (@ "JS call OC: % @", data ); responseCallback (@ "response after OC is called: Call successful! ") ;}];

If you want to call a function registered in JS, you can use the instance method callHandler to call it as needed.

Id data =@ {@ "OC call JS": @ "Hi there, JS! "}; [_ Bridge callHandler: @" OC_Call_JS "data: data responseCallback: ^ (id response) {NSLog (@" testJavascriptHandler responded: % @ ", response);}];

 

Iv. Summary

Recently, due to the needs of the project, I was learning and working on the Hybrid App. I used this third party and wrote an article to share it with me. I hope it can help the person who just started, the demo address of the above instance is https://github.com/garenchen/webviewjsbridgedemo. Just Give star ^_^;

Recommended reading:

JSBridge-Web-Native interaction iOS: http://www.jianshu.com/p/9fd80b785de1

Hybrid App development model: http://www.tuicool.com/articles/riE3Yn

WebViewJavascriptBridge: https://github.com/marcuswestin/WebViewJavascriptBridge

 

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.