Skip to content
目录

全局监听网络状态

app.js

javascript
//app.js
App({
  globalData: {
    offline: false,
  },
  onLaunch() {
    wx.getNetworkType({
      success: res => {
        console.log(res);
        if (res.networkType === "none") {
          wx.setStorageSync("offline", true);
          this.globalData.offline = true;
        } else {
          wx.setStorageSync("offline", false);
          this.globalData.offline = false;
        }
      },
    });
    wx.onNetworkStatusChange(res => {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      console.log(currentPage);
      const isHome = currentPage?.route === "pages/home/index";
      console.log(res);
      if (res.networkType === "none" || res.networkType === 'offline') {
        wx.setStorageSync("offline", true);
        this.globalData.offline = true;
        wx.showToast({
          title: '网络异常',
          icon: 'error',
          duration: 2000
        })
        if (isHome) {
          wx.showToast({
            title: '网络异常',
            icon: 'error',
            duration: 2000
          })
        } else {
          //依情况而定是否需要返回首页
          // setTimeout(() => {
          //   wx.switchTab({
          //     url: "/pages/home/index",
          //   });
          // }, 1500);
        }
      } else {
        if (wx.getStorageSync("offline")) {
          wx.setStorageSync("offline", false);
          this.globalData.offline = false;
          wx.showToast({
            title: '网络异常',
            icon: 'error',
            duration: 2000
          })
          if (isHome) {
          } else {
            setTimeout(() => {
              wx.switchTab({
                url: "/pages/home/index",
              });
            }, 1000);
          }
        }
      }
    });
  },
});