小程序授权方法封装

我们在开发微信小程序时都会需要用到一些用户权限,如:录像头、录音、保存到相册等等权限

以下是我封装的js,提供给大家使用

checkAnth.js

export default class checkAnth {

  constructor() {

  }

  // 初始化授权获取(授权wxSetting,授权名称)

  initcheckAuth(authName, authtype) {

    var _that=this

    this.checkAuth().then(setRes => {

      if (!setRes[authName]) {

        wx.authorize({

          scope: authName,

          success(authRes) {

            console.log(authRes, authtype);

          },

          fail(authErr) {

            _that.checkAuth(true, authName, authtype)

          }

        })

      }

    })

  }

  // 检测授权和提示

  checkAuth(showModel = false, authName, authtype) {

    return new Promise((resolve, reject) => {

      wx.getSetting({

        success(res) {

          if (!res.authSetting[authName]) {

            if (showModel) {

              wx.showModal({

                title: '授权提示',

                content: `需要您的${authtype}`,

                confirmText: '去开启',

                confirmColor: '#FE5250',

                success(modelRes) {

                  if (modelRes.confirm) {

                    wx.openSetting() // 打开授权管理页面

                  } else {

                    wx.showToast({ title: `请前往开启手机${authtype}权限~`, icon: 'none', duration: 3000 })

                  }

                }

              })

            }

            resolve({ authName: false })

          } else {


            resolve({ authName: true })

          }

        },

        fail: err => {

          wx.showToast({ title: `请检测手机${authtype}是否开启,重新进入本页面~`, icon: 'none', duration: 3000 })

        }

      })

    })

  }

}



在页面中引入

import anthUtils from '../../../../utils/checkAnth.js';

const anth = new anthUtils();

 anth.initcheckAuth('scope.camera', '摄像头');//调用即可

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容