一、建立JSbrideg.js文件
var jsBridge = {
isAndroid: null,
isIOS: null,
callHandlerFunc: function(json_data){
var that = this;
var res_data = null;
var nv = null;
// alert("callHandlerFunc");
var u = navigator.userAgent;
that.isAndroid = u.indexOf(‘Android‘) > -1 || u.indexOf(‘Adr‘) > -1; //android终端
that.isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
if(that.isIOS){
// alert("ios");
nv = window.GCWebviewJSBridge;
}else{
nv = window.WebViewJavascriptBridge;
}
nv.callHandler(‘getOS‘, json_data, function (response) {
res_data = response;
});
return res_data;
},
initJsBridge: function(readyCallback){
var that = this;
var u = navigator.userAgent;
var isAndroid = u.indexOf(‘Android‘) > -1 || u.indexOf(‘Adr‘) > -1; //android终端
var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
// 注册jsbridge
function connectWebViewJavascriptBridge(callback) {
if (isAndroid) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
‘WebViewJavascriptBridgeReady‘
, function () {
callback(WebViewJavascriptBridge)
},
false
);
}
return;
}
if (isIOS) {
// alert("ios2222");
if (window.GCWebviewJSBridge) {
return callback(GCWebviewJSBridge);
}
if (window.GCWVJSBCallBacks) {
return window.GCWVJSBCallBacks.push(callback);
}
window.GCWVJSBCallBacks = [callback];
var GCWVJSBIframe = document.createElement(‘iframe‘);
GCWVJSBIframe.style.display = ‘none‘;
GCWVJSBIframe.src = ‘gcwvjsbscheme://__GC_BRIDGE_LOADED__‘;
document.documentElement.appendChild(GCWVJSBIframe);
setTimeout(function() { document.documentElement.removeChild(GCWVJSBIframe)
}, 0);
}
}
// 调用注册方法
connectWebViewJavascriptBridge(function (bridge) {
if (isAndroid) {
bridge.init(function (message, responseCallback) {
console.log(‘JS got a message‘, message);
responseCallback(data);
});
}
// 只有在这里注册过的方法,在原声代码里才能用callHandler的方式调???
//jsbridge_getJsMessage 是与app定义的方法,前端定义好参数传递,通过此方法响应回传给前端想要的数据data
bridge.registerHandler(‘jsbridge_getJsMessage‘, function (data, responseCallback){
var jsdata = JSON.parse(data);
responseCallback(‘native 传过来的是 2:‘ + data);
});
readyCallback();
});
}
}
jsBridge.initJsBridge();
export default {
//发送数据给原生Native App
callHandler(data) {
let json = data;
return jsBridge.callHandlerFunc(json);
},
}
二、注意:在man.js注册使用
import bridge from ‘components/JSbridge‘
Vue.prototype.$bridge = bridge;
当需要与app通信获取用户信息,来在前端做路由权限控制时候,不可以在
router.beforeEach((to, from, next) => {})中调用,因为此时 页面未加载,
window.WebViewJavascriptBridge或者
if(app){
}else{
}
window.GCWebviewJSBridge 都不存在。
本人处理是在 App.vue中
watch:{//监测
‘$route‘(to,from){
let app = window.localStorage.getItem(‘isapp‘); //获取是否app进入
let useid = window.localStorage.getItem(‘user_id‘); //获取useid
if(!useid){
if(to.path == ‘/‘ || to.path == ‘/c‘ || to.path == ‘/a‘ || to.path == ‘/b‘){
return;
}
var json= {"type":101,"videoId":""};
this.$bridge.callHandler(JSON.stringify(json));向app通信,会在注册方法中得到用户信息,把用户id(用户信息)记录缓存中
}
}}