最近在公司有一个原生和H5交互的项目,用到了WebViewJavascriptBridge,下面简单讲解下如何使用以及前端JS如何封装。
什么是JS Bridge
在移动开发中为了加快开发进度(0.0)很多页面会用H5来开发,这样一来可以快速完成节约,二来APP内嵌WebView可以较少APP更新频率。因此,成本现在大多数公司的首选,但是部分功能JavaScript的权限受到严格限制,比如拍照,读写权限,获取GPS等等,这些native功能,这时候我们需要去委托原生去实现,原生实现后再告知js。这个时候就需要一个中间桥梁,于是就有了WebViewJavascriptBridge,简称 JS bridge。
简单使用
在HTML中使用
<html>
<head>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
<style type='text/css'>
html { font-family:Helvetica; color:#222; }
h1 { color:steelblue; font-size:24px; margin-top:24px; }
button { margin:0 3px 10px; font-size:12px; }
.logLine { border-bottom:1px solid #ccc; padding:4px 2px; font-family:courier; font-size:11px; }
</style>
</head>
<body>
<h1>WebViewJavascriptBridge Demo</h1>
<script>
window.onerror = function(err) {
log('window.onerror: ' + err)
}
/*这段代码是固定的,必须要放到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 + ':<br/>' + 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': '标哥的技术博客'})
})
/*JS给ObjC提供公开的API,ObjC端通过注册,就可以在JS端调用此API时,得到回调。ObjC端可以在处理完成后,反馈给JS,这样写就是在载入页面完成时就先调用*/
bridge.callHandler('getUserIdFromObjC', function(responseData) {
log("JS call ObjC's getUserIdFromObjC function, and js received response:", responseData)
})
document.getElementById('blogId').onclick = function (e) {
log('js call objc: getBlogNameFromObjC')
bridge.callHandler('getBlogNameFromObjC', {'blogURL': 'http://www.henishuo.com'}, function(response) {
log('JS got response', response)
})
}
})
</script>
<div id='buttons'></div> <div id='log'></div>
<div>
<input type="button" value="getBlogNameFromObjC" id="blogId"/>
</div>
</body>
</html>
在OC中使用
#import "ViewController.h"
#import "WebViewJavascriptBridge.h"
@interface ViewController () <UIWebViewDelegate>
@property WebViewJavascriptBridge *bridge;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
NSString *appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
[webView loadHTMLString:appHtml baseURL:baseURL];
// 开启日志
[WebViewJavascriptBridge enableLogging];
// 给哪个webview建立JS与OjbC的沟通桥梁
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
[self.bridge setWebViewDelegate:self];
[self renderButtons:webView];
// JS主动调用OjbC的方法
// 这是JS会调用getUserIdFromObjC方法,这是OC注册给JS调用的
// JS需要回调,当然JS也可以传参数过来。data就是JS所传的参数,不一定需要传
// 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);
}];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(@"webViewDidStartLoad");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(@"webViewDidFinishLoad");
}
- (void)renderButtons:(UIWebView*)webView {
UIFont* font = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
UIButton *callbackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[callbackButton setTitle:@"打开博文" forState:UIControlStateNormal];
[callbackButton addTarget:self action:@selector(onOpenBlogArticle:) forControlEvents:UIControlEventTouchUpInside];
[self.view insertSubview:callbackButton aboveSubview:webView];
callbackButton.frame = CGRectMake(10, 400, 100, 35);
callbackButton.titleLabel.font = font;
UIButton* reloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[reloadButton setTitle:@"刷新webview" forState:UIControlStateNormal];
[reloadButton addTarget:webView action:@selector(reload) forControlEvents:UIControlEventTouchUpInside];
[self.view insertSubview:reloadButton aboveSubview:webView];
reloadButton.frame = CGRectMake(110, 400, 100, 35);
reloadButton.titleLabel.font = font;
}
- (void)onOpenBlogArticle:(id)sender {
// 调用打开本demo的博文
[self.bridge callHandler:@"openWebviewBridgeArticle" data:nil];
}
@end
如上代码非常的冗余,我们如何做到代码简洁以及在React中改如何使用
在React的使用
使用方式基于create-react-app 和dva 项目中使用
//index.js 入口注册
setupWebViewJavascriptBridge(() => {
app.start('#root');
})
setupWebViewJavascriptBridge(callback) {
if (!!process.env.REACT_APP_hybrid) {
if (window.WebViewJavascriptBridge) {
callback();
} else {
let u = navigator.userAgent
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
if (isAndroid) {
// android
document.addEventListener('WebViewJavascriptBridgeReady',
() => {
callback();
},
false);
} else if (isIOS) {
window.document.ontouchmove = e => {
document.querySelectorAll("input").forEach((e) => {
e.blur()
})
};
// ios
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback)
}
window.WVJBCallbacks = [callback]
let WVJBIframe = document.createElement('iframe')
WVJBIframe.style.display = 'none'
WVJBIframe.src = 'https://__bridge_loaded__'
document.documentElement.appendChild(WVJBIframe)
setTimeout(() => { document.documentElement.removeChild(WVJBIframe) }, 0)
}
}
} else {
callback()
}
}
//注册原生方法
window.Hybrid = window.Hybrid || {};
function requestHybrid(url, data, callback) {
window.WebViewJavascriptBridge.callHandler(
'POST', { 'param': data, url: url }, (responseData, responseCallback) => {
let res = responseData
let data = {}
try {
data = eval('(' + res + ')')
callback(data)
} catch (error) {
Toast.fail('网络连接错误!', 1);
}
}
)
}
//发送请求
export function POSThybrid(url, data = {}) {
return new Promise((res, rej) => {
requestHybrid(url, data, (response) => {
if (response) {
if (response.code === 0) {
res(response)
} else {
//对错误的各种判断
Toast.fail(response.message, 1);
res({ code: 10000 })
}
}
})
})
}
//原生返回
export function goBack() {
window.WebViewJavascriptBridge.callHandler(
'goBack', {}, (responseData, responseCallback) => { }
)
}
//获取日期
export function getSingleDate() {
return new Promise((res, rej) => {
window.WebViewJavascriptBridge.callHandler(
'getSingleDate', {}, (responseData, responseCallback) => {
res(responseData)
}
)
})
}
//拍照
export function getPhoto() {
return new Promise((res, rej) => {
window.WebViewJavascriptBridge.callHandler(
'getPhoto', {}, (img, responseCallback) => {
if (img) {
res(img)
} else {
rej()
}
}
)
})
}
//获取日历
export function getCalendar() {
window.WebViewJavascriptBridge.callHandler(
'getCalendar', {}, (calendar, responseCallback) => {
if (calendar) {
return calendar;
}
}
)
}
//前端调用
getPhoto = () => {
hybrid.getPhoto().then(res=>console.log("原生拍完照上传后台返回前端的图片地址"+res))
}
<div className="v-back" onClick={this.getPhoto}><Icon type={"left"} /></div>
总结
- WebViewJavaScriptBridge 用于 WKWebView & UIWebView 中 OC 和 JS 交互。
- 分别在OC环境和javascript环境都保存一个bridge对象,里面维持着requestId,callbackId,以及每个id对应的具体实现。
- OC通过javascript环境的window.WebViewJavascriptBridge对象来找到具体的方法,然后执行。
- 把 OC 的方法注册到桥梁中,让 JS 去调用。
- 把 JS 的方法注册在桥梁中,让 OC 去调用。
网友评论