當小程序發布新的版本后 ,用戶如果之前訪問過該小程序,通過已打開的小程序進入(未手動刪除),則會檢測新版本,提醒用戶更新新的版本

話不多說,上代碼
App({ onLaunch: function () { // 檢查更新 this.autoUpdate() }, 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: '新版本已經上線了,請刪除當前小程序,重新搜索打開', }) }) } })
由於小程序開發版/體驗版沒有“版本”的概念,所以無法在開發版/體驗版上測試版本更新情況,可以在開發工具上,添加編譯模式,勾選最下方的“下次編譯時模擬更新”,但是要注意,這種模式僅供一次編譯,下次編譯需重新設置
