Files
shanxia2.0/miniprogram/utils/mpUpdate.js
T
2026-09-26 11:59:39 +08:00

67 lines
1.7 KiB
JavaScript

/**
* 微信小程序正式版更新:先开本地缓存包、再异步下载新包。
* 新包就绪后强制重启,避免用户长期停留在旧界面。
* 仅正式版有版本概念;开发版/体验版无更新流程。
*
* @see docs/superpowers/specs/2026-09-26-mp-weixin-force-update-design.md
*/
const SHOW_DEBOUNCE_MS = 30 * 1000
let listenersBound = false
let readyModalShown = false
let failedModalShown = false
let lastCheckAt = 0
function bindUpdateListeners(updateManager) {
if (listenersBound) return
listenersBound = true
updateManager.onCheckForUpdate((res) => {
console.log('[mpUpdate] onCheckForUpdate hasUpdate=', !!(res && res.hasUpdate))
})
updateManager.onUpdateReady(() => {
if (readyModalShown) return
readyModalShown = true
uni.showModal({
title: '更新提示',
content: '新版本已准备好,需要重启以使用最新功能',
showCancel: false,
confirmText: '立即重启',
success: (res) => {
if (res.confirm) {
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(() => {
if (failedModalShown) return
failedModalShown = true
uni.showModal({
title: '更新失败',
content: '新版本下载失败,请删除小程序后重新搜索打开,或检查网络后重试',
showCancel: false
})
})
}
export function checkMpUpdate() {
// #ifdef MP-WEIXIN
const now = Date.now()
if (lastCheckAt && now - lastCheckAt < SHOW_DEBOUNCE_MS) {
return
}
lastCheckAt = now
if (typeof uni.canIUse !== 'function' || !uni.canIUse('getUpdateManager')) {
return
}
const updateManager = uni.getUpdateManager()
bindUpdateListeners(updateManager)
// #endif
}