因为iOS要废弃UIWebView的原因,所以打算将公司项目的UIWebView重构掉,将WebViewJavascriptBridge从我也不知道是第几版的=升级到最新版本,用了两天的时间了解了项目整个交互过程,记录一下。
初始化及注入
//初始化,内部拦截webview的代理
_javascriptBridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webView];
//将非javascriptBridg拦截的url代理转出来
[_javascriptBridge setWebViewDelegate:self];
以前的注入是放在了网页加载完成时,并通过计数实现锁(这里卡了好久)
而现在的是在html代码里加上
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)

页面加载完成后WVJBIframe.src 会再次跳转,WkWebView执行decidePolicyForNavigationAction,Bridge会在此对url进行拦截,如果是,在注入WebViewJavascriptBridge_JS的js字符串,生成WebViewJavascriptBridge js对象,否则回调到WebViewDelegate
交互
js调OC:

OC调JS:

网友评论