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 ''
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 ''
}