一。需求:微信小程序在使用webview 时,导航栏是不允许自己修改的。对于左上角的返回按钮,如果相要在返回的时候,弹框确定后再返回,微信小程序是没有api支持。在微信小程序的思路上基本无解。
二。解决办法:用于我们的webview 就是直接使用的微信浏览器。我们是可以使用js 相关的 History API. 主要是通过 设置 history.pushState 这个方法来阻止的。
history.pushState API说明:总共是三个参数,前面两个不用管直接用null 即可,第三个代码跳转页面的地址。
首先进入页面时:执行下面代码<script type="text/javascript">window.history.pushState(null, null, null)</script>
上面代码的目的就是添加一条历史记录。用于第三个参数为null,则不会发生跳转,但是会添加一条历史记录。然后加上自己的地址,这样就会存在两条历史记录。假如只有一条历史则不会触发 popstate 事件。
vue相关代码:
data() {return {showConfirmModal: false,clickConfirm: false,isSaved: false // 是否保存的操作}},mounted() {window.addEventListener('popstate', this.handlePopstate)},beforeDestroy() {window.removeEventListener('popstate', this.handlePopstate)},methods: {confirmModal() {this.showConfirmModal = falsethis.clickConfirm = trueuni.navigateBack({delta: history.length})},closeModal() {this.showConfirmModal = falsehistory.pushState(null, null, document.URL)},handlePopstate() {if (!this.clickConfirm && this.isSaved) {history.pushState(null, null, document.URL)this.showConfirmModal = true}},}
showConfirmModal :用于显示弹框参数
clickConfirm :区分是否点击过确定按钮。点击后就一直为true。
当触发popstate事情时,需要先执行下history.pushState如果不执行则无法保留当前页面。当点击确定返回时,也会触发该事情,所以需要加一个参数进行控制。
点击modal 确定按钮则需要返回。微信小程序 直接使用。必须使用history.length不然无法退出。因为 history 的长度是大于1的。
wx.navigateBack({delta: history.length})
问题咨询:加入QQ群:620302448。或者扫描加入。