all files / src/ index.js

17.14% Statements 6/35
0% Branches 0/26
12.5% Functions 1/8
14.71% Lines 5/34
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61  1×                   1×     1×     1×                     1×                                                                
// Event Register Function
const addEvent = (element, eventName, fn) => {
  if (element.addEventListener) {
    element.addEventListener(eventName, fn, false)
  } else if (element.attachEvent) {
    element.attachEvent('on' + eventName, fn)
  } else {
    element['on' + eventName] = fn
  }
}
 
export default class DeepLink {
  // constructor
  constructor (options) {
    this.options = options
 
    // binding function.
    this.register = (el, options) => {
      if (typeof options.appScheme === 'undefined') {
        throw Error('appScheme is a required param value.')
      }
      addEvent(el, 'click', (e) => {
        e && e.preventDefault()
        this.openApp(options)
      })
    }
 
    // open the app.
    this.openApp = (options) => {
      if (typeof options.appScheme === 'undefined') {
        throw Error('appScheme is a required param value.')
      }
 
      const ua = navigator.userAgent.toLowerCase()
      const isIPhone = /iphone|ipad|ipod/.test(ua)
      const isAndroid = ~ua.indexOf('android')
      if (isIPhone || isAndroid) {
        let interval
        let timer
        const clearTimers = () => {
          clearInterval(interval)
          clearTimeout(timer)
        }
        const checkAppInterval = () => {
          if (document.webkitHidden || document.hidden) {
            clearTimers()
          }
        }
        interval = setInterval(checkAppInterval, 200)
        timer = setTimeout(() => {
          const appStoreLink = isIPhone ? this.options.appStore : this.options.playStore
          appStoreLink && (document.location.href = appStoreLink)
        }, 1000)
        options.appScheme && (document.location.href = options.appScheme)
      } else {
        options.webUrl && (document.location.href = options.webUrl)
      }
    }
  }
}