IOS高级工程师成长之路 -- 基础篇《UIWebview之WebViewJavascriptBridge》

一. 使用方法:
1.Import the header file and declare an ivar property:

import "WebViewJavascriptBridge.h"

...
@property WebViewJavascriptBridge* bridge;

  1. Instantiate WebViewJavascriptBridge with a WKWebView, UIWebView (iOS) or WebView (OSX):
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];

  2. Register a handler in ObjC, and call a JS handler:
    [self.bridge registerHandler:@"ObjC Echo" handler:^(id data, WVJBResponseCallback responseCallback) {
    NSLog(@"ObjC Echo called with: %@", data);
    responseCallback(data);
    }];
    [self.bridge callHandler:@"JS Echo" data:nil responseCallback:^(id responseData) {
    NSLog(@"ObjC received response: %@", responseData);
    }];

  3. Copy and paste setupWebViewJavascriptBridge into your JS:
    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 = 'https://bridge_loaded';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
    }

  4. Finally, call setupWebViewJavascriptBridge and then use the bridge to register handlers and call ObjC handlers:setupWebViewJavascriptBridge(function(bridge) {
    /* Initialize your app here */

    bridge.registerHandler('JS Echo', function(data, responseCallback) {
    console.log("JS Echo called with:", data)
    responseCallback(data)
    })
    bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) {
    console.log("JS received response:", responseData)
    })
    })

二. API定义
ObjC API

  1. [WebViewJavascriptBridge bridgeForWebView:(WKWebVIew/UIWebView/WebView*)webview
  2. [bridge registerHandler:(NSString*)handlerName handler:(WVJBHandler)handler]
  3. [bridge callHandler:(NSString)handlerName data:(id)data]
    [bridge callHandler:(NSString
    )handlerName data:(id)data responseCallback:(WVJBResponseCallback)callback]
  4. [bridge setWebViewDelegate:(id)webViewDelegate]
    Optionally, set a WKNavigationDelegate/UIWebViewDelegate if you need to respond to the [web view's lifecycle events]

三. Javascript API

  1. bridge.registerHandler("handlerName", function(responseData) { ... })
  2. bridge.callHandler("handlerName", data)
    bridge.callHandler("handlerName", data, function responseCallback(responseData) { ... })
  3. bridge.disableJavscriptAlertBoxSafetyTimeout()
    Calling bridge.disableJavscriptAlertBoxSafetyTimeout() has the same effect as calling [bridge disableJavscriptAlertBoxSafetyTimeout]; in ObjC.

你可能感兴趣的:(IOS高级工程师成长之路 -- 基础篇《UIWebview之WebViewJavascriptBridge》)