JSbridge在Vue的封装与交互

JSbridge: https://github.com/lzyzsd/JsBridge

JSbridge.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
let isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1;
let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

//这是必须要写的,用来创建一些设置
function setupWebViewJavascriptBridge(callback) {
//Android使用
if (isAndroid) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady',
function () {
callback(WebViewJavascriptBridge)
},
false
);
}
console.log('tag', '安卓')
sessionStorage.phoneType = 'android'
}

//iOS使用
if (isiOS) {
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);
console.log('tag', 'ios');
sessionStorage.phoneType = 'ios'
}
}

//注册回调函数,第一次连接时调用初始化函数(Android需要初始化,ios不用)
setupWebViewJavascriptBridge(function (bridge) {
if (isAndroid) {
//初始化
bridge.init(function (message, responseCallback) {
var data = {
'Javascript Responds': 'Wee!'
};
responseCallback(data);
})
}
})

export default {
// js调APP方法 (参数分别为:app提供的方法名 传给app的数据 回调)
callHandler(name, data, callback) {
setupWebViewJavascriptBridge(function (bridge) {
bridge.callHandler(name, data, callback)
})
},
// APP调js方法 (参数分别为:js提供的方法名 回调)
registerHandler(name, callback) {
setupWebViewJavascriptBridge(function (bridge) {
bridge.registerHandler(name, function (data, responseCallback) {
callback(data, responseCallback)
})
})
}
}

main.js中引入

1
2
import Bridge from './config/JSbridge.js'
Vue.prototype.$bridge = Bridge

组件中使用

方法名和app开发人员沟通好,这里js调app,app提供的方法是callNative;app调js,js提供的方法是callJs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//注册方法
mounted() {
this.registerJs()
},

//js调app
sendMsg() {
let msg = this.msg
this.$bridge.callHandler('callNative', msg, (res)=>{
alert('获取app响应数据:' + res)
this.test = res
})
},

//app调js
registerJs() {
this.$bridge.registerHandler('callJs', (data, responseCallback) => {
alert('app主动调用js方法,传入数据:' + data)
responseCallback(data)
})
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :