uniapp H5项目 自动刷新

261 阅读1分钟

场景与功能

开发的H5项目,用户访问过网站后浏览器会将网站的一些资源缓存起来

这时候就算我们更新了项目也可能会出现用户访问网站时还是使用旧资源的情况

功能:

一进入项目就自动刷新一次

代码

 refreshPage() {
				sessionStorage.setItem('uni_refresh_page', new Date().getTime()); // 记录已刷新状态

				const url = new URL(window.location.href);
				url.searchParams.set('uni_refresh_page', new Date().getTime()); // 添加时间戳,防止缓存

				window.location.replace(url.toString());
			}

使用建议:

可以在App.vue文件中找到onLaunch生命周期函数,添加上

// #ifdef H5
			if (!sessionStorage.getItem('uni_refresh_page')) {
				this.refreshPage();
			} else {
				// 删除url中的uni_refresh_page参数
				const url = new URL(window.location.href);
				url.searchParams.delete('uni_refresh_page');
				window.history.replaceState({}, '', url.toString());
			}
			// #endif