JSBridge

JSBridge 是一种 webview 侧和 native 侧进行通信的手段

source:https://zhuanlan.zhihu.com/p/381459761

1. 实现原理
app的native端拦截webview 的url请求来互相通信

2. 实现步骤

2.1 js端

setupWebViewJavascriptBridge方法的作用,将回调callback放入window.WVJBCalls数组中,没有则创建之。
```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)

}```

2.2 app端
(1)拦截了所有的 URL 请求并拿到 url
(2)^^^
(3)继续判断,如果是isBridgeLoadedURL,那么会执行injectJavascriptFile方法,会向 webview 中再次注入一些逻辑,其中最重要的逻辑就是,在 window 对象上挂载一些全局变量和WebViewJavascriptBridge属性
(4)继续判断,如果是 isQueueMessageURL,那么这就是个处理消息的回调,需要执行一些消息处理的方法

詳解圖

你可能感兴趣的:(JSBridge)