H5連接原生的js
H5ConnectNative.js
export default class H5ConnectNative {
constructor(handleMap) {
this.handleMap = handleMap;
this.bridge = window.WebViewJavascriptBridge;
this._initBridge();
}
_initBridge() {
var context = this;
var getBridge = this._getBridge.bind(this);
if(!this.bridge) {
if(this._isIOS()) {
if(window.WVJBCallbacks) {
return window.WVJBCallbacks.push(getBridge);
}
window.WVJBCallbacks = [getBridge];
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);
} else if(this._isAndroid()) {
document.addEventListener(
'WebViewJavascriptBridgeReady',
function() {
getBridge(window.WebViewJavascriptBridge);
}
)
}
} else {
getBridge(this.bridge);
}
}
_getBridge (bridge) {
this.bridge || (this.bridge = bridge);
if(this._isAndroid()) {
this.bridge.init(function(message, responseCallback) {
//responseCallback();
});
}
this._register();
}
_register () {
if(!this.bridge)
return;
Object.keys(this.handleMap).forEach((field) => {
this.bridge.registerHandler(field, this.handleMap[field]);
});
}
goAppPage (value) {
if(!this.bridge){
return;
}
this.bridge.callHandler('goAPP', value);
}
_isIOS () {
return /ip(hone|ad)/i.test(navigator.userAgent);
}
_isAndroid () {
return /android/i.test(navigator.userAgent);
}
}
vue內main.js
放置在main.js里面 無論任何鏈接進入頁面,都會初始化accessToken。同時,安卓登錄之后,再次調用setAccessToken方法,即可在不刷新頁面的情況下設置accessToken。
import H5ConnectNative from './assets/js/H5ConnectNative.js';
Vue.prototype.h5ConnectNative = new H5ConnectNative({
setAccessToken: function(accessToken) {
//alert("token:"+accessToken);
if(!accessToken) {
localStorage.setItem('token', '');
} else {
localStorage.setItem('token', accessToken);
}
//alert("token:"+localStorage.getItem('token'));
}
});
vue內頁面調用安卓
this.h5ConnectNative.goAppPage(JSON.stringify({returnBtn: "back"}));
注:方便起見,可以在鈎子函數中,如果需要用戶登錄,則調起安卓。
router.beforeEach((to, from, next) => {
{
if(to.meta.requireAuth) {
if(localStorage.getItem("token") != null && localStorage.getItem("token") != '') {
next();
} else {
Vue.prototype.h5ConnectNative.goAppPage(JSON.stringify({
login: "login"
}))
}
} else {
next();
}
}
})