bridge.js
//Android 交互声明
function connectWebViewJSBridgeANDROID(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge);
} else {
document.addEventListener(
"WebViewJavascriptBridgeReady",
function () {
callback(WebViewJavascriptBridge);
},
false
);
}
}
// 判断是不是安卓手机
function isAndroid() {
return /(Android)/i.test(navigator.userAgent);
}
let $bridge = {
// js调用native
callhandler(name, data, callback) {
if (isAndroid()) {//Android
connectWebViewJSBridgeANDROID(function (bridge) {
bridge.callHandler(name, data, callback)
})
} else {//iOS
window.webkit.messageHandlers[name].postMessage(data)
}
},
first(){
connectWebViewJSBridgeANDROID(function (bridge) {
bridge.init(function (message, responseCallback) {
if (responseCallback) {
responseCallback(message);
}
});
})
},
// native调用js
registerHandler(name, callback) { //Android方法
connectWebViewJSBridgeANDROID(function (bridge) {
bridge.registerHandler(name, function (message, responseCallback) {
callback(message, responseCallback)
});
})
},
}
$bridge.first()
export default $bridge
main.js
import Bridge from './jsbridge/bridge'
Vue.prototype.$bridge = Bridge
home.vue
<template>
<div class="home">
<div @click="clickScanQRCode">扫描二维码</div>
</div>
</template>
<script>
export default {
methods: {
// 扫描二维码
clickScanQRCode() {
// scan_type 0:直接打开扫描结果 1:返回扫描结果
this.$bridge.callhandler("scanQRCode", { scan_type: 1 }, function(
response
) {
this.$toast.center(response);
});
},
/** 以下iOS返回结果 */
// 扫描二维码返回结果
scanQRCodeHandler(param) {
this.$toast.center(param);
}
},
mounted() {
/** 以下iOS返回结果 */
// 扫描二维码返回结果
window.scanQRCodeHandler = this.scanQRCodeHandler;
},
created() {
//安卓调用js返回结果
// 扫描二维码返回结果
this.$bridge.registerHandler(
"scanQRCodeHandler",
(data) => {
this.$toast.center(data);
responseCallback(data);
}
);
}
};
</script>
iOS
使用的是WKWebView
#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIScrollViewDelegate>
@property (nonatomic, strong) WKWebView *wkWebView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 创建设置对象
WKPreferences *preference = [[WKPreferences alloc]init];
//最小字体大小 当将javaScriptEnabled属性设置为NO时,可以看到明显的效果
preference.minimumFontSize = 0;
//设置是否支持javaScript 默认是支持的
preference.javaScriptEnabled = YES;
// 在iOS上默认为NO,表示是否允许不经过用户交互由javaScript自动打开窗口
preference.javaScriptCanOpenWindowsAutomatically = YES;
config.preferences = preference;
_wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) configuration:config];
_wkWebView.UIDelegate = self;
_wkWebView.navigationDelegate = self;
_wkWebView.scrollView.delegate = self;
_wkWebView.allowsBackForwardNavigationGestures = true;
[_wkWebView goBack];
[_wkWebView goForward];
// NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
// NSURL *url = [NSURL fileURLWithPath:path];
NSURL *url = [NSURL URLWithString:@"http://10.1.129.182:8082/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_wkWebView loadRequest:request];
[_wkWebView reload];
[self.view addSubview:_wkWebView];
// 注册
[_wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"scanQRCode"];
}
- (BOOL)webView:(WKWebView *)webView shouldPreviewElement:(WKPreviewElementInfo *)elementInfo{
return true;
}
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
NSLog(@"createWebViewWithConfiguration");
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"body = %@",message.body);
NSLog(@"name = %@",message.name);
if ([message.name isEqualToString:@"scanQRCode"]) {
[self scanQRWithInformation:message.body];
}
}
-(void)scanQRWithInformation:(NSDictionary *)dic
{
if (![dic isKindOfClass:[NSDictionary class]]) {
return;
}
//在这里写扫码操作的代码
NSLog(@"dic = %@",dic);
//OC调用JS
[_wkWebView evaluateJavaScript:@"scanQRCodeHandler('扫码成功')" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"result = %@",result);
NSLog(@"error = %@",error);
}];
}
@end
android
// js调用安卓
webView.registerHandler("scanQRCode",(data,function) ->{
try{
JSONObject object = new JSONObject(data);
int type = object.getInt("scan_type")
}catch(JSONException e){
e.printStackTrace()
}
})
// 安卓调用js result是参数
WebView.callHandler("scanQRCodeHandler",result,data - >{})