微信小程序判斷當前是否最新版本並且更新


在app.js中添加以下代碼,並且在onLaunch中調用,每次更新后會彈出更新的提示框,點擊確定即可更新為最新版本

 

  autoUpdate: function() {
    let _this = this
    // 獲取小程序更新機制的兼容,由於更新的功能基礎庫要1.9.90以上版本才支持,所以此處要做低版本的兼容處理
    if (wx.canIUse('getUpdateManager')) {
      // wx.getUpdateManager接口,可以獲知是否有新版本的小程序、新版本是否下載好以及應用新版本的能力,會返回一個UpdateManager實例
      const updateManager = wx.getUpdateManager()
      // 檢查小程序是否有新版本發布,onCheckForUpdate:當小程序向后台請求完新版本信息,會通知這個版本告知檢查結果
      updateManager.onCheckForUpdate(function(res) {
        // 請求完新版本信息的回調
        if (res.hasUpdate) {
          // 檢測到新版本,需要更新,給出提示
          wx.showModal({
            title: '更新提示',
            content: '檢測到新版本,是否下載新版本並重啟小程序',
            success: function(res) {
              if (res.confirm) {
                // 用戶確定更新小程序,小程序下載和更新靜默進行
                _this.downLoadAndUpdate(updateManager)
              } else if (res.cancel) {
                // 若用戶點擊了取消按鈕,二次彈窗,強制更新,如果用戶選擇取消后不需要進行任何操作,則以下內容可忽略
                wx.showModal({
                  title: '提示',
                  content:
                    '本次版本更新涉及到新功能的添加,舊版本將無法正常使用',
                  showCancel: false, // 隱藏取消按鈕
                  confirmText: '確認更新', // 只保留更新按鈕
                  success: function(res) {
                    if (res.confirm) {
                      // 下載新版本,重啟應用
                      _this.downLoadAndUpdate(updateManager)
                    }
                  }
                })
              }
            }
          })
        }
      })
    } else {
      // 在最新版本客戶端上體驗小程序
      wx.showModal({
        title: '提示',
        content: '當前微信版本過低,無法使用該功能,請升級到最新微信版本后重試'
      })
    }
  },
  // 下載小程序最新版本並重啟
  downLoadAndUpdate: function(updateManager) {
    wx.showLoading()
    // 靜默下載更新小程序新版本,onUpdateReady:當新版本下載完成回調
    updateManager.onUpdateReady(function() {
      wx.hideLoading()
      // applyUpdate:強制當前小程序應用上新版本並重啟
      updateManager.applyUpdate()
    })
    // onUpdateFailed:當新版本下載失敗回調
    updateManager.onUpdateFailed(function() {
      // 下載新版本失敗
      wx.showModal({
        title: '已有新版本',
        content: '新版本已經上線了,請刪除當前小程序,重新搜索打開'
      })
    })
  }

  轉載自https://juejin.cn/post/6844904007173931021


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM