onLaunch: async function (options) { this.init() //var _this = this; let menuButtonObject = wx.getMenuButtonBoundingClientRect(); const res = await wx.cloud.callFunction({name: 'getServerTime'}); // 使用await等待异步请求结果 console.log('服务器时间:',res.result) const cloudTimeStamp = res.result;// 需要从res中取出result console.log('服务器时间:',cloudTimeStamp) // 获取小程序系统时间戳 const systemTimeStamp = Date.now(); console.log('运行环境系统时间:',systemTimeStamp) // 计算时间戳差值,单位为秒 const diff = Math.abs(cloudTimeStamp - systemTimeStamp) / 1000; console.log('时间差值:',diff) // 如果时间戳差值大于一定值,则认为小程序系统时间被篡改 if (diff > 100) { wx.showToast({ title: '小程序系统时间被篡改,请检查时间设置', icon: 'none', }); return; } wx.getSystemInfo({ success: res => { let statusBarHeight = res.statusBarHeight, navTop = menuButtonObject.top, navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; this.globalData.navHeight = navHeight; this.globalData.navTop = navTop; this.globalData.windowHeight = res.windowHeight; }, fail(err) { console.log(err); } }) },怎么修改这个函数让diff大于100时,停止运行小程序
时间: 2023-12-02 12:06:22 浏览: 37
你可以在函数的开头部分添加一个判断,如果diff大于100则直接return,代码如下:
```
onLaunch: async function (options) {
this.init()
let menuButtonObject = wx.getMenuButtonBoundingClientRect();
const res = await wx.cloud.callFunction({name: 'getServerTime'});
const cloudTimeStamp = res.result;
const systemTimeStamp = Date.now();
const diff = Math.abs(cloudTimeStamp - systemTimeStamp) / 1000;
if (diff > 100) {
wx.showToast({
title: '小程序系统时间被篡改,请检查时间设置',
icon: 'none',
});
return; // 添加这行代码
}
wx.getSystemInfo({
success: res => {
let statusBarHeight = res.statusBarHeight,
navTop = menuButtonObject.top,
navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
this.globalData.navHeight = navHeight;
this.globalData.navTop = navTop;
this.globalData.windowHeight = res.windowHeight;
},
fail(err) {
console.log(err);
}
})
}
```
当diff大于100时,会弹出一个提示框,并且直接return,停止运行小程序。