|
| 1 | +// eslint-disable-next-line import/prefer-default-export |
| 2 | +export function mpAutoUpdate() { |
| 3 | + /** |
| 4 | + * @description 执行小程序自动更新 |
| 5 | + */ |
| 6 | + console.log('runing mp auto update') |
| 7 | + if (wx.canIUse('getUpdateManager')) { // 获取小程序更新机制兼容 |
| 8 | + const updateManager = wx.getUpdateManager() |
| 9 | + updateManager.onCheckForUpdate((res) => { // 1. 检查小程序是否有新版本发布 |
| 10 | + if (res.hasUpdate) { // 请求完新版本信息的回调 |
| 11 | + // 检测到新版本,需要更新,给出提示 |
| 12 | + wx.showModal({ |
| 13 | + title: '更新提示', |
| 14 | + content: '检测到新版本,是否下载新版本并重启小程序?', |
| 15 | + success(res2) { |
| 16 | + if (res2.confirm) { // 2. 用户确定下载更新小程序,小程序下载及更新静默进行 |
| 17 | + // eslint-disable-next-line no-use-before-define |
| 18 | + downLoadAndUpdate(updateManager) |
| 19 | + } else if (res2.cancel) { // 用户点击取消按钮的处理,如果需要强制更新,则给出二次弹窗,如果不需要,则这里的代码都可以删掉了 |
| 20 | + // wx.showModal({ |
| 21 | + // title: '温馨提示~', |
| 22 | + // content: '本次版本更新涉及到新的功能添加,旧版本无法正常访问的哦~', |
| 23 | + // showCancel: false, // 隐藏取消按钮 |
| 24 | + // confirmText: '确定更新', // 只保留确定更新按钮 |
| 25 | + // success(res3) { |
| 26 | + // if (res3.confirm) { |
| 27 | + // // 下载新版本,并重新应用 |
| 28 | + // // eslint-disable-next-line no-use-before-define |
| 29 | + // downLoadAndUpdate(updateManager) |
| 30 | + // } |
| 31 | + // } |
| 32 | + // }) |
| 33 | + } |
| 34 | + } |
| 35 | + }) |
| 36 | + } |
| 37 | + }) |
| 38 | + } else { |
| 39 | + // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示 |
| 40 | + wx.showModal({ |
| 41 | + title: '提示', |
| 42 | + content: '当前微信版本过低,无法使用此小程序功能,请升级到最新微信版本后重试。' |
| 43 | + }) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +export function downLoadAndUpdate(updateManager) { |
| 48 | + /** |
| 49 | + * @description 下载小程序新版本并重启应用 |
| 50 | + * @param {Object} updateManager |
| 51 | + */ |
| 52 | + wx.showLoading() |
| 53 | + updateManager.onUpdateReady(() => { // 静默下载更新小程序新版本 |
| 54 | + wx.hideLoading() |
| 55 | + // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 |
| 56 | + updateManager.applyUpdate() |
| 57 | + }) |
| 58 | + updateManager.onUpdateFailed(() => { |
| 59 | + wx.hideLoading() |
| 60 | + // 新的版本下载失败 |
| 61 | + wx.showModal({ |
| 62 | + title: '已经有新版本了哟~', |
| 63 | + content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~', |
| 64 | + }) |
| 65 | + }) |
| 66 | +} |
0 commit comments