uniapp h5 js设置监听:超时未操作返回首页(全局只监听一次,可设置监听事件+检查时间+超时时长)

功能实现:

  1. 可自定义超时时长,检查时间
  2. 超时后跳转首页(/pages/home/index/index);
  3. 如果在首页,则不进行跳转
  4. 监控状态下, 用户有任意操作(包括但不限于点击,滑动,跳转页面等),则重置监听,重新开始算时间
  5. 超时方法及逻辑封装到单独的js文件中
  6. 全局只需在app.vue创建监听,其他页面无需修改

具体代码:

1. 创建timeout.js文件, 代码如下:

javascript 复制代码
export const timeOut = () => {
	let lastTime = null; //最后一次操作时间
	let currentTime = null //当前时间
	let sys_timeout = 3 * 60 * 1000; // 超时时间(我设置了3分钟,可自行修改)
	let check_time = 10 * 1000; //检查时间(每隔多长时间检查一次, 可自行修改)
	let goOut = null; //计时器
	let home_path = 'pages/home/index/index'; //首页地址
	const isTimeOut = () => {
		// 页面上一次的操作时间
		lastTime = uni.getStorageSync('lastOperationTime');
		if (!lastTime) {
			clearInterval(goOut);
		}
		currentTime = new Date().getTime()
		// 判断是否超时
		if ((currentTime - lastTime) > sys_timeout) {
			console.log("超时了")
			return true;
		} else {
			return false;
		}
	}
	const isLoginOut = () => {
		clearInterval(goOut);
		goOut = setInterval(() => {
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			const pagePath = currentPage.route;
			if (isTimeOut()) {
				console.log('当前页面路径为:' + pagePath);
				if (pagePath.indexOf(home_path) == -1) {
					uni.reLaunch({
						url: `/${home_path}`,
					});
				}
			}
		}, check_time);
	}
	isLoginOut();
}

2. 在App.vue文件中加入:

javascript 复制代码
onLaunch: function() {
	console.log('App Launch');

	//超时返回首页
	uni.setStorageSync('lastOperationTime', new Date().getTime()); //设置最后一次操作时间
	timeOut();
	setTimeout(function() {
		const events = ['click', 'mousemove', 'keydown', 'scroll', 'keypress', 'touchstart'];
		var body_ = document.getElementsByTagName('body')[0];
		events.forEach(e => {
			body_.addEventListener(e, function() {
				uni.setStorageSync('lastOperationTime', new Date().getTime()); //设置操作时间
			});
		});
	}, 1000);
}

tips: events 中包含了基本的点击事件, 滑动事件等,具体可自行修改

参考下图

相关推荐
不想吃饭e10 小时前
uniapp-图片,视频上传组件封装
java·uni-app·音视频
子午11 小时前
基于DeepSeek的智能校园教务管理系统~Web管理系统+Vue3+Python+DeepSeek智能问答
前端
change_fate11 小时前
ERR_PNPM_WORKSPACE_PKG_NOT_FOUND In ...
java·服务器·前端
超人不会飞_Jay11 小时前
26.6.3Vue笔记
前端·vue.js·笔记
御坂1002711 小时前
Vue - @change应用实现下拉框联动功能
前端·javascript·vue.js
小雨下雨的雨11 小时前
基于 Electron 运行时的鸿蒙PC桌面应用-安全可靠的随机密码生成工具
前端·javascript·华为·electron·前端框架·鸿蒙
瘦瘦瘦大人11 小时前
Vue 项目实现关闭/刷新浏览器窗口前的离开确认提示
前端·javascript·vue.js
大家的林语冰11 小时前
尤雨溪官宣:Vite+ 全员加盟 Cloudflare,正式进军全栈开发和 AI 部署云平台!
前端·javascript·vite
独特的螺狮粉11 小时前
金属硬度与熔点对照表APP - 通过鸿蒙PC Electron框架完整技术实现指南
前端·javascript·electron·前端框架·开源·鸿蒙
Java_2017_csdn11 小时前
在 Java 中,MessageFormat.format() 和 String.format() 函数对比?
java·开发语言·前端·数据库