官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/base/update/UpdateManager.html
更新版本的模拟测试:
1. 微信开发者工具上可以通过「编译模式」下的「下次编译模拟更新」开关来调试;
2. 小程序开发版/体验版没有「版本」概念,所以无法在开发版/体验版上测试更版本更新情况;
对于开发者工具,可以这样验证测试:
点击编译模式设置下拉列表,然后点击"添加编译模式",在自定义编译条件弹窗界面,点击下次编译时模拟更新,然后点击确定,重新编译就OK了。
注意:这种方式模拟更新一次之后就失效了,后边再测试仍需要对这种编译模式进行重新设置才可以。
/**
* 小程序检查更新
*/
autoUpdate: function() {
var that = this
// 获取小程序更新机制兼容
if (wx.canIUse('getUpdateManager')) {
const updateManager = wx.getUpdateManager()
//1. 检查小程序是否有新版本发布
updateManager.onCheckForUpdate(function(res) {
// 请求完新版本信息的回调
if (res.hasUpdate) {
// 检测到新版本,需要更新,给出提示
wx.showModal({
title: '更新提醒',
content: '小程序已为您更新到最新版,快来使用吧', //'已检测到新版本,是否下载并重启小程序?',
// 是否显示取消按钮
showCancel: false,
success: function(res) {
if (res.confirm) {
//2. 用户确定下载更新小程序,小程序下载及更新静默进行
that.downLoadAndUpdate(updateManager)
} else if (res.cancel) {
//用户点击取消按钮的处理,如果需要强制更新,则给出二次弹窗,如果不需要,则这里的代码都可以删掉了
wx.showModal({
title: '更新提醒',
content: '本次更新因改动较大,旧版本某些功能可能无法正常访问的哦~',
showCancel:false,//隐藏取消按钮
confirmText:"确认更新",//只保留确定更新按钮
success: function(res) {
if (res.confirm) {
//下载新版本,并重新应用
that.downLoadAndUpdate(updateManager)
}
}
})
}
}
})
} else {
}
})
} else {
// 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
wx.showModal({
title: '错误',
content: '当前微信版本过低,无法使用本小程序,请升级到最新微信版本后重试!'
})
}
},
/**
* 下载小程序新版本并重启应用
*/
downLoadAndUpdate: function (updateManager){
wx.showLoading();
//静默下载更新小程序新版本
updateManager.onUpdateReady(function () {
wx.hideLoading()
//新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate()
})
updateManager.onUpdateFailed(function () {
wx.hideLoading();
// 新的版本下载失败
wx.showModal({
title: '检测到新版本了哦~',
content: '新版本已经上线啦~ 请您删除当前小程序重新打开哦~',
})
})
}