js获取网络时间(不是本机系统时间,防止用户篡改本机时间蒙混过关)

const currentTime = ''
const signInTime = '2023/08/07 09:20:25'
const resData = await new Promise((resolve) => {
  let xhr = new XMLHttpRequest();
  if( !xhr ){
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhr.open("HEAD",location.href,true);
  xhr.onreadystatechange=() => {
    if( xhr.readyState == 4 && xhr.status == 200 ){
      currentTime = this.dateTimeFormate(xhr.getResponseHeader("Date"))
      if (parseInt(new Date(currentTime)-signInTime)/1000/60/60 < 2) {
        this.$vux.confirm.show({
          title: "温馨提示",
          content: "时间不足2小时,有被判断为无效的风险,是否确定需要签退?",
          onConfirm() {
            resolve(false)
          },
          onCancel: () => {
            resolve(true)
          },
        });
      } else {
        resolve(false)
      }
    }
  }
  xhr.send(null);
})

dateTimeFormate(date){
  if(!date){
   return
  }else{
    var d = new Date(date);
    var year = d.getFullYear();
    var month = ('0' + (d.getMonth() + 1)).slice(-2);
    var day = ('0' + (d.getDate())).slice(-2);
    var hour = ('0' + (d.getHours())).slice(-2);
    var minutes = ('0' + (d.getMinutes())).slice(-2);
    var seconds = ('0' + (d.getSeconds())).slice(-2);
    return year + "/" + month + "/" + day + " " + hour + ":" + minutes + ":" + seconds;
  }
}

你可能感兴趣的:(javascript,前端)