iOS端的WebViewJavascriptBridge及dsBridge使用方法

WebViewJavascriptBridge的用法

  • HTML端设置
    先申明交互(// < !--申明交互 -->)
    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)
    }

Native给JS传值(// < !--处理交互 方法名要和ios内定义的对应-- >)

    setupWebViewJavascriptBridge(function (bridge) {
         // 
         bridge.registerHandler('swiftToJs', function (data, responseCallback) {
              var res = JSON.parse(data);
              vm.msg=res
              // 接收到swift传的值后再回调给swift、可不写
              responseCallback('js执行过了');
              })
         })

JS给Native传值(// < !--处理交互 方法名要和ios内定义的对应-- >)

   WebViewJavascriptBridge.callHandler('jsToSwift', this.msg.myAnswer, function (response) {
         // 处理swift过来的回调
        // alert('swift传回的回调:'+response)
   })
  • iOS端设置

先初始化

let bridge = WKWebViewJavascriptBridge(for: self.webView)
WKWebViewJavascriptBridge.enableLogging()
bridge?.setWebViewDelegate(self)

在ViewDidLoad中注册交互方法(接收js传值)

self.webViewBridge.registerHandler("jsToSwift") { [weak self] (data, responseCallback) in
       let dataArray = data as? NSArray
       self?.setMyAnswer(answers: dataArray as! [Int])
}

传值给js

self.webViewBridge.callHandler("swiftToJs", data: jsonStr, responseCallback: { (responseData) in
      YTLog(responseData)
 })

dsBridge的用法

  • HTML端设置
    先通过cdn引入

    
    
    
    
    
    刷题APP

接收Native传值

bridge.register('courseDetailToJs', function (data) {
      let _data = JSON.parse(data)
      var list = that.moneyList
      list = list.concat(_data["data"])
      that.moneyList = that.objInArray(list)
      {#responseCallback('js执行过了');#}
})

给Native传值

bridge.call("courseDetailToNative")
  • iOS端设置

先初始化(注意:这里的object可以是self也可以是新建的JsApi类,但接收传值方法需能在对应的类中找到)

let webView: DWKWebView = DWKWebView()
webView.addJavascriptObject(self, namespace: nil)

接收js传值

/// Js调用Native   不管h5那边有没有传值, (_ arg: String?)都必须写, 否则找不到该方法
@objc func courseDetailToNative(_ arg: String?) {
     ExamCouponView.showCourseCouponView(courseId: _detailModel.uuid, obtainCoupon: { [weak self] (couponArray) in
         self?.courseDetailToJs(data: couponArray)
     })
}

传值给js

/// Native调用Js
fileprivate func courseDetailToJs(data: [Any]) {
    let dataDic = ["data": data]
    // js那边需要的参数格式:   {data: [{discount: 33300, text: "原价立减"}, {discount: 27300, text: "折上立减"}]}
    webView?.callHandler("courseDetailToJs", arguments: [dataDic.formatJSON() as Any])
}

你可能感兴趣的:(iOS端的WebViewJavascriptBridge及dsBridge使用方法)