uniapp h5 页面 tabbar页面阻止实体键退出

2,535 阅读1分钟

uniapp h5 页面 tabbar页面阻止实体键退出

h5页面在tabbar页面点击手机的实体键时会直接关闭浏览器 为了阻止关闭可以用以下代码

在main.js挂载到实例上
     // 阻止实体键返回_跳转
    Vue.prototype.POP = function() {
    	uni.switchTab({
	    url: '/pages/index/index'
         });
    }

    // 阻止实体键返回_监听
    Vue.prototype.addPOP = function(fn) {
    	if (window.history && window.history.pushState) {
    	    console.log('支持监听返回键');
    	    history.pushState(null, null, document.URL);
      	    window.addEventListener('popstate', fn, false); 
    	}
    }
    // 阻止实体键返回_卸载 
    Vue.prototype.removePOP = function(fn) {
    	window.removeEventListener('popstate', fn, false);
    }
在tabbar页面的onShow 和 onHide 生命周期分别调用监听和卸载方法
    onShow() {
	this.addPOP(this.POP);
    },
    onHide() {
    	this.removePOP(this.POP);
    },