Last active
June 11, 2021 09:11
-
-
Save fewlme/d5285ee4769dba9df10eb9cd047f3214 to your computer and use it in GitHub Desktop.
Store UTMs from URL into a cookie and inject them into Hatch widget
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* *************************************************** | |
| -- UTMs to data-extra-parameter-requests -- | |
| - To be placed before the HATCH WIDGET LIBRARY script | |
| *************************************************** */ | |
| const HATCH_UTMS_COOKIE = 'h_utms', utmParams = ['utm_source','utm_medium','utm_campaign','utm_content','utm_term']; | |
| let h_utms = {}, h_utms_v = ''; | |
| let utmQuery = decodeURIComponent(window.location.search.substring(1)), | |
| utmVariables = utmQuery.split('&'), | |
| ParameterName, | |
| i; | |
| const getUTMValue = (inputParameter) => { | |
| for (i = 0; i < utmVariables.length; i++) { | |
| ParameterName = utmVariables[i].split('='); | |
| if (ParameterName[0] === inputParameter) { | |
| return ParameterName[1] === null ? null : ParameterName[1]; | |
| } | |
| } | |
| } | |
| utmParams.forEach(param => { | |
| var pValue = getUTMValue(param); | |
| if(pValue === undefined) return; | |
| h_utms[param] = pValue; | |
| }); | |
| h_utms_v = JSON.stringify(h_utms).replace(/[\/\(\)\"]/g, "'"); | |
| if (h_utms_v != '{}') { | |
| var d = new Date(); | |
| d.setTime(d.getTime() + (30*24*60*60*1000)); | |
| var expires = "expires="+ d.toUTCString(); | |
| document.cookie = HATCH_UTMS_COOKIE + "=" + h_utms_v + ";" + expires + ";"; | |
| }; | |
| let hatchStoredUtm = document.cookie.split(';').filter((item) => item.trim().startsWith(HATCH_UTMS_COOKIE + "=")); | |
| if(hatchStoredUtm.length > 0){ | |
| var hatchStoredUtmValue = hatchStoredUtm[0].split(HATCH_UTMS_COOKIE + "=")[1]; | |
| var hatchWidgets = document.querySelectorAll("[data-gh-buy-now-button]"); | |
| for(u = 0;u < hatchWidgets.length; u++) hatchWidgets[u].setAttribute("data-extra-request-parameters", hatchStoredUtmValue); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment