WebViewJavascriptBridge 使用小结(一)

一 :oc registerHandler 注册方法 js端直接调用 , js注册 方法OC代码直接调用

  // OC端通过responseCallback回调JS端,JS就可以得到所需要的数据
  [self.bridge registerHandler:@"getUserIdFromObjC" handler:^(id data, WVJBResponseCallback responseCallback) {
    NSLog(@"js call getUserIdFromObjC, data from js is %@", data);
    if (responseCallback) {
      // 反馈给JS
      responseCallback(@{@"userId": @"123456"});
    }
  }];
  
  [self.bridge registerHandler:@"getBlogNameFromObjC" handler:^(id data, WVJBResponseCallback responseCallback) {
    NSLog(@"js call getBlogNameFromObjC, data from js is %@", data);
    if (responseCallback) {
      // 反馈给JS
      responseCallback(@{@"blogName": @"技术博客"});
    }
  }];
[self.bridge callHandler:@"getUserInfos" data:@{@"name": @"标哥"} responseCallback:^(id responseData) {
    NSLog(@"from js: %@", responseData);
  }];
  /*这段代码是固定的,必须要放到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 = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
      }
    
      /*与OC交互的所有JS方法都要放在此处注册,才能调用通过JS调用OC或者让OC调用这里的JS*/
      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 + ':
' + JSON.stringify(data) if (log.children.length) { log.insertBefore(el, log.children[0]) } else { log.appendChild(el) } } /* Initialize your app here */ /*我们在这注册一个js调用OC的方法,不带参数,且不用ObjC端反馈结果给JS:打开本demo对应的博文*/ bridge.registerHandler('openWebviewBridgeArticle', function() { log("openWebviewBridgeArticle was called with by ObjC") }) /*JS给ObjC提供公开的API,在ObjC端可以手动调用JS的这个API。接收ObjC传过来的参数,且可以回调ObjC*/ bridge.registerHandler('getUserInfos', function(data, responseCallback) { log("Get user information from ObjC: ", data) responseCallback({'userId': '123456', 'blog': '标哥的技术博客'}) })

二 :bridge 可以使用js全局变量G_IOS_BRIDGE保存 前提得在调用bridge.init方法内给G_IOS_BRIDGE赋值

    
                    
                    

你可能感兴趣的:(WebViewJavascriptBridge 使用小结(一))