index.js 2.38 KB
/**
 * @file 微信隐私授权弹窗(自 glsk-applet-component/GlsxPrivacy 内联,仅主包引用)
 * 监听 wx.onNeedPrivacyAuthorization,在当前页展示用户隐私保护指引同意/拒绝 UI。
 */
import { getSystemInfo } from '~/utils/systemInfo'

let privacyHandler
const privacyResolves = new Set()
const closeOtherPagePopUpHooks = new Set()

if (wx.onNeedPrivacyAuthorization) {
  wx.onNeedPrivacyAuthorization(resolve => {
    if (typeof privacyHandler === 'function') {
      privacyHandler(resolve)
    }
  })
}

/** 关闭其它页面上的隐私弹窗,保证单例展示 */
function closeOtherPagePopUp(closePopUp) {
  closeOtherPagePopUpHooks.forEach(hook => {
    if (closePopUp !== hook) {
      hook()
    }
  })
}

Component({
  properties: {
    appletName: {
      type: String,
      value: ''
    },
    text: {
      type: String,
      value: ''
    }
  },

  data: {
    showPrivacy: false,
    isIPad: false
  },

  pageLifetimes: {
    show() {
      const closePopUp = () => {
        this.disPopUp()
      }
      privacyHandler = resolve => {
        privacyResolves.add(resolve)
        this.popUp()
        closeOtherPagePopUp(closePopUp)
      }
      closeOtherPagePopUpHooks.add(closePopUp)
      this.closePopUp = closePopUp
      getSystemInfo({
        success: res => {
          this.setData({
            isIPad: res.screenWidth > 700
          })
        }
      })
    },
    hide() {
      closeOtherPagePopUpHooks.delete(this.closePopUp)
    }
  },

  methods: {
    handleAgree() {
      this.disPopUp()
      privacyResolves.forEach(resolve => {
        resolve({
          event: 'agree',
          buttonId: 'agree-btn'
        })
      })
      privacyResolves.clear()
      this.triggerEvent('agreeClick')
    },
    handleDisagree() {
      this.disPopUp()
      privacyResolves.forEach(resolve => {
        resolve({
          event: 'disagree'
        })
      })
      privacyResolves.clear()
      this.triggerEvent('disagreeClick')
    },
    popUp() {
      if (this.data.showPrivacy === false) {
        this.setData({
          showPrivacy: true
        })
      }
    },
    disPopUp() {
      if (this.data.showPrivacy === true) {
        this.setData({
          showPrivacy: false
        })
      }
    },
    handleOpenPrivacyContract() {
      wx.openPrivacyContract({
        success() {},
        fail() {},
        complete() {}
      })
    }
  }
})