Listen to the H5 browser return event, solve the problem of listening to the webview H5 return event, trigger H5 to pass parameters to the applet (valid for personal testing)

In the browser, there will be a need to click the back, back, previous page and other buttons to realize the need to close the page, adjust to the specified page, confirm to leave the page, or perform some other operations. You can use the popstate event to monitor the return, back, and previous page operations.

1. Briefly introduce the operations in history

1.window.history.back(), back

2.window.history.forward(), forward

3.window.history.go(num), forward or backward the specified number of historical records

4.window.history.pushState(state, title, utl), create a history entity in the page. Added directly to history.

Parameters: state: store an object, you can add relevant information, you can use history.state to read the content.
title: The title of the history record.
url: The link to the created history. You will be redirected to this link when performing history operations.

5.window.history.replaceState(), modify the current history entity.

6. popstate event, the event triggered when the history entity changes.

7.window.history.state, will get the state object in the history entity.

2. Listen to the H5 browser return event and pass parameters to the applet at the same time

Requirements: When not operating on the H5 page, return to the applet and trigger the display of the pop-up box

Problem: In the successful callback method of the applet, trigger to open the H5 page (via webview), if you click the physical return button in the upper left corner of the H5 page, you will return to the applet, and you will not be able to trigger the jump to the H5 page again

Solution:
1. Monitor the physical return button on the H5 page
2. Pass parameters to the applet when returning;
3. Receive parameters in the applet, judge by the parameters, pull up the pop-up box to prompt to jump again

Cancel the default return action:

1.添加一条 history 实体作为替代原来的 history 实体
function pushHistory(){
    
    
  var state = {
    
    
       title: "title",
       url: "#"     
    }
  window.history.pushState(state, "title", "#");   
}
pushHistory()
2.监听 popstate 事件

window.addEventListener("popstate", function(){
    
    
    //doSomething
}, false)

used in the project

H5 page code:

1. Install WeChat SDK

npm install weixin-js-sdk –save

2. Introduce WeChat SDK into the page

import wx from 'weixin-js-sdk'

3. The H5 page monitors and returns, and passes parameters to the applet


 mounted () {
    
    
    const that = this
    // 监听返回
    this.pushHistory()
    window.addEventListener('popstate', function (e) {
    
    
      // 为了避免只调用一次
      that.pushHistory('title1')
      // 自定义方法, 直接关闭网页或返回小程序上一页
      that.goBack()
    },
    false
    )
  },
methods:{
    
    
// 添加一条 history 实体作为替代原来的 history 实体
    pushHistory (str = 'title', url = '#') {
    
    
      const state = {
    
    
        title: str,
        url
      }
      window.history.pushState(state, state.title, state.url)
    },
    goBack () {
    
    
      wx.miniProgram.navigateBack()
      // postMessage给小程序传递参数,只有当小程序页面退出和当前页面销毁的情况下才会触发传参
      wx.miniProgram.postMessage({
    
     data: {
    
     passWord: this.passwordValue } })
    },
}

Code in the applet:

1. Receive the H5 page parameter on the webview page, and pass the parameter to the previous page of the applet through the page stack

<template>
	<view>
		<web-view :src="url" @message="handleMessage"></web-view>
	</view>
</template>

<script>
	import apiUrl from '@/utils/commonUrl.js';
	export default {
    
    
		data() {
    
    
			return {
    
    
				url: '',
			};
		},
		onLoad(option) {
    
    
			this.url = apiUrl.videoUrl + "?t=" + new Date().getTime() + '&message=' + option.message
		},
		methods:{
    
    
			handleMessage(res){
    
    
				let pages = getCurrentPages(); //获取所有页面栈实例列表
				let nowPage = pages[pages.length - 1]; //当前页页面实例
				let prevPage = pages[pages.length - 2]; //上一页页面实例
				prevPage.$vm.passwordValue = res.detail.data[res.detail.data.length - 1].passWord; //修改上一页data里面的参数值 
			},
		}
	}
</script>

<style lang="scss">

</style>

2. Before jumping to the webview page, the page watch monitors the parameter changes and triggers the display of the pop-up box

<!-- 请输入密码 -->
		<view class="success-box" v-if="passwordsubmitIshow">
			<view class="contain-top">
				温馨提示
			</view>
			<view class="success-text1">
				请前往重置密码
			</view>
			<button class="bottom-submit" @click="passwordConfirm">确认</button>
		</view>
watch: {
    
    
	'passwordValue': {
    
    
		handler(newVal) {
    
    
			if (newVal == 0) {
    
    
				this.passwordsubmitIshow = true;
			} else if (newVal == 1) {
    
    
				this.passwordsubmitIshow = false;
			}
		},
		deep: true
	},
},

achieve effect

When the H5 page is not in operation or the operation is not completed, return to the applet and trigger the display of the pop-up box

insert image description here
insert image description here

3. Listen to the H5 browser return event on the specified page, clear the listening event when the page is destroyed, and pass parameters to the applet at the same time

When there is only one page in H5, the above method can be used normally; but when there are many pages in H5, you need to add the returned listening event and the returned cancel listening event on the specified page

Example: code in H5 project

  mounted () {
    
    
    // 监听返回
    this.pushHistory()
    if (this.personList.token != '') {
    
    
      window.addEventListener('popstate', this.goBack, false)
    }
  },
  // 页面销毁时,清除返回监听事件
  beforeDestroy () {
    
    
    window.removeEventListener('popstate', this.goBack, false)
  },
  methods: {
    
    
    // 插入浏览器历史
    pushHistory (str = 'title', url = '#/detail') {
    
    
      const state = {
    
    
        title: str,
        url
      }
      window.history.pushState(state, state.title, state.url)
    },
    goBack () {
    
    
      // 为了避免只调用一次
      this.pushHistory('title1')
      // 自定义方法, 当页面路由为指定页面时,执行监听的方法
      if (window.location.href == 'https://cbstest.ncbmip.com/minip/rongshu/index.html#/detail') {
    
    
        wx.miniProgram.navigateBack()
        wx.miniProgram.postMessage({
    
     data: {
    
     passWord: this.passwordValue } })
      }
    },

Guess you like

Origin blog.csdn.net/m0_47791238/article/details/131340145