Skip to content

uniapp 小程序强制用户使用最新版本

其实 uniapp 官网有这个例子。

https://uniapp.dcloud.net.cn/api/other/update.html#getupdatemanager

把下面这段代码放入 App.vue 文件里的 onLaunch 钩子里,以后用户打开小程序,都会检查最新版本。检查到就提醒用户更新。

js
    console.log('App Launch')
    const updateManager = uni.getUpdateManager();

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调。是否有最新版本。
      console.log(res.hasUpdate, 'hasUpdate');
    });

    updateManager.onUpdateReady(function (res) {
      uni.showModal({
        title: '更新提示',
        content: '新版本已经准备好,是否重启应用?',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        }
      });

    });

    updateManager.onUpdateFailed(function (res) {
      // 新的版本下载失败
    });

在小程序开发者工具里还可以设置编译模式,检查提醒用户更新是否生效了。如下:

image.png

Released under the MIT License.