直接上代碼,修改app.js 的 onLaunch
方法
onLaunch() { this.autoUpdate() }, autoUpdate:function(){ console.log(new Date()) const self=this // 獲取小程序更新機制兼容 if (wx.canIUse('getUpdateManager')) { const updateManager = wx.getUpdateManager() //1. 檢查小程序是否有新版本發布 updateManager.onCheckForUpdate(function (res) { // 請求完新版本信息的回調 if (res.hasUpdate) { //2. 小程序有新版本,則靜默下載新版本,做好更新准備 updateManager.onUpdateReady(function () { console.log(new Date()) wx.showModal({ title: '更新提示', content: '新版本已經准備好,是否重啟應用?', success: function (res) { if (res.confirm) { //3. 新的版本已經下載好,調用 applyUpdate 應用新版本並重啟 updateManager.applyUpdate() } else if (res.cancel) { //如果需要強制更新,則給出二次彈窗,如果不需要,則這里的代碼都可以刪掉了 wx.showModal({ title: '溫馨提示~', content: '本次版本更新涉及到新的功能添加,舊版本無法正常訪問的哦~', success: function (res) { self.autoUpdate() return; //第二次提示后,強制更新 if (res.confirm) { // 新的版本已經下載好,調用 applyUpdate 應用新版本並重啟 updateManager.applyUpdate() } else if (res.cancel) { //重新回到版本更新提示 self.autoUpdate() } } }) } } }) }) updateManager.onUpdateFailed(function () { // 新的版本下載失敗 wx.showModal({ title: '已經有新版本了喲~', content: '新版本已經上線啦~,請您刪除當前小程序,重新搜索打開喲~', }) }) } }) } else { // 如果希望用戶在最新版本的客戶端上體驗您的小程序,可以這樣子提示 wx.showModal({ title: '提示', content: '當前微信版本過低,無法使用該功能,請升級到最新微信版本后重試。' }) } }, /** * 下載小程序新版本並重啟應用 */ downLoadAndUpdate: function (updateManager){ var self=this wx.showLoading(); //靜默下載更新小程序新版本 updateManager.onUpdateReady(function () { wx.hideLoading() //新的版本已經下載好,調用 applyUpdate 應用新版本並重啟 updateManager.applyUpdate() }) updateManager.onUpdateFailed(function () { // 新的版本下載失敗 wx.showModal({ title: '已經有新版本了喲~', content: '新版本已經上線啦~,請您刪除當前小程序,重新搜索打開喲~', }) }) },