Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created August 13, 2021 09:57
Show Gist options
  • Save JamieMason/0d1a04cad8d4bec68bc3d31d05c1167c to your computer and use it in GitHub Desktop.
Save JamieMason/0d1a04cad8d4bec68bc3d31d05c1167c to your computer and use it in GitHub Desktop.

Refactor this

Spec

when on the server
  return ''
when on the client
  when gclid=12345 GET param is present in the URL
    store it in sessionStorage
    return '12345'
  when gclid GET param is not present in the URL
    when sessionStorage is not supported
      return ''
    when sessionStorage is supported
      when gclid=12345 is set in sessionStorage
        return '12345'
      when gclid is not set in sessionStorage
        return ''

Current Implementation πŸ‘Ž

I bet something nice can be done with arrays of functions and find, filter, and forEach πŸ€·β€β™‚οΈ

function getGoogleClickId() {
  if (typeof document === 'undefined') {
    return ''
  }
  const fromUrl = new URLSearchParams(document.location.search).get('gclid')
  if (fromUrl) {
    if (typeof sessionStorage !== 'undefined') {
      sessionStorage.setItem('gclid', fromUrl)
    }
    return fromUrl
  }
  if (typeof sessionStorage !== 'undefined') {
    return sessionStorage.getItem('gclid') || ''
  }
  return ''
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment