mpUpdate.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * 微信小程序正式版更新:先开本地缓存包、再异步下载新包。
  3. * 新包就绪后强制重启,避免用户长期停留在旧界面。
  4. * 仅正式版有版本概念;开发版/体验版无更新流程。
  5. *
  6. * @see docs/superpowers/specs/2026-09-26-mp-weixin-force-update-design.md
  7. */
  8. const SHOW_DEBOUNCE_MS = 30 * 1000
  9. let listenersBound = false
  10. let readyModalShown = false
  11. let failedModalShown = false
  12. let lastCheckAt = 0
  13. function bindUpdateListeners(updateManager) {
  14. if (listenersBound) return
  15. listenersBound = true
  16. updateManager.onCheckForUpdate((res) => {
  17. console.log('[mpUpdate] onCheckForUpdate hasUpdate=', !!(res && res.hasUpdate))
  18. })
  19. updateManager.onUpdateReady(() => {
  20. if (readyModalShown) return
  21. readyModalShown = true
  22. uni.showModal({
  23. title: '更新提示',
  24. content: '新版本已准备好,需要重启以使用最新功能',
  25. showCancel: false,
  26. confirmText: '立即重启',
  27. success: (res) => {
  28. if (res.confirm) {
  29. updateManager.applyUpdate()
  30. }
  31. }
  32. })
  33. })
  34. updateManager.onUpdateFailed(() => {
  35. if (failedModalShown) return
  36. failedModalShown = true
  37. uni.showModal({
  38. title: '更新失败',
  39. content: '新版本下载失败,请删除小程序后重新搜索打开,或检查网络后重试',
  40. showCancel: false
  41. })
  42. })
  43. }
  44. export function checkMpUpdate() {
  45. // #ifdef MP-WEIXIN
  46. const now = Date.now()
  47. if (lastCheckAt && now - lastCheckAt < SHOW_DEBOUNCE_MS) {
  48. return
  49. }
  50. lastCheckAt = now
  51. if (typeof uni.canIUse !== 'function' || !uni.canIUse('getUpdateManager')) {
  52. return
  53. }
  54. const updateManager = uni.getUpdateManager()
  55. bindUpdateListeners(updateManager)
  56. // #endif
  57. }