前言: 直接打包后, 按一次返回键会直接退出应用, 太不符合使用习惯, 而且手机返回键没发控制页面返回, 体验太差了,于是乎, 找了一半天资料, 终于优化掉了, 直接上干货↓↓↓
第一步: Hbuilder新建一个空白项目
在 pages/index/index.vue编写
<template>
<view class="content">
<web-view webview-styles="webviewStyle"
src='https://baidu.com'></web-view>
</view>
</template>
第二步: 控制veb-view样式,铺满全屏
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh !important;
}
.webviewStyles {
height: 100vh !important;
}
iframe {
height: 100% !important;
}
/*隐藏head标签, 这个很重要, 要不然会在app端出现两个标题栏*/
uni-page-head {
display: none;
}
/*body高度100%*/
uni-page-wrapper {
height: 100% !important;
}
</style>
第三步: 监听返回事件,实现 单击返回,双击退出
<script>
var wv; //计划创建的webview
export default {
data() {
return {
backButtonPress: 0, //2次退出应用计时
webView: '',
}
},
onLoad() {
},
onReady() {
// app初始化时,获取web-viewe对象
var currentWebview = this.$scope.$getAppWebview()
//此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效,非v3编译模式使用this.$mp.page.$getAppWebview()
setTimeout(function() {
wv = currentWebview.children()[0];
}, 1000);
},
methods: {},
//监听返回按键点击事件
onBackPress(options) {
var _this = this;
_this.backButtonPress++;
if (_this.backButtonPress > 1) {
// 双击退出应用
plus.runtime.quit();
} else {
// 单击返回, evalJS 在Webview窗口中执行JS脚本
// web-view对象函数讲解 https://www.html5plus.org/doc/zh_cn/webview.html#plus.webview.WebviewObject
wv.evalJS('window.history.back()')
}
setTimeout(function() {
_this.backButtonPress = 0;
}, 600);
return true;
},
}
</script>
以上就功能就全部实现了, 觉得有用的帮点点赞
网友评论