Vue 与 安卓 交互

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();
		}
	}
})
posted @ 2018-05-11 14:36  CalronLoveRonnie  阅读(3325)  评论(0编辑  收藏  举报
AmazingCounters.com