Skip to content

Instantly share code, notes, and snippets.

@fewlme
Last active May 11, 2022 08:30
Show Gist options
  • Select an option

  • Save fewlme/7957b31cb4a4d103807101570569ac62 to your computer and use it in GitHub Desktop.

Select an option

Save fewlme/7957b31cb4a4d103807101570569ac62 to your computer and use it in GitHub Desktop.
Grabs the UTMs from the URL and transform them into a unique CID store in a cookie and injected in Hatch widget
/* ***************************************************
-- CID to data-gh-cid --
- To be placed before the HATCH WIDGET LIBRARY script
*************************************************** */
const HATCH_CID_COOKIE = "h_cid";
function createHatchCid() {
var url = window.location.href;
var regexp = /(?!&)utm_[^=]*=[^&]*(?=&)?/g;
var utms = url.match(regexp);
if(!utms) return null;
var n_cid = '';
var values = utms.reduce(function(obj, param) {
var keyVal = param.split('=');
n_cid += keyVal[1]+'_';
return n_cid;
}, {});
n_cid = n_cid.slice(0, -1);
return decodeURIComponent(n_cid.replace(/\+/g, " "));
}
var cid = createHatchCid();
if (cid != undefined) {
var now = new Date();
var expireDate = new Date(now.getTime() + 86400000);
document.cookie = HATCH_CID_COOKIE + "=" + cid + "; expires=" + expireDate.toUTCString() + ";";
}
var hatchStoredCid = document.cookie.split(';').filter((item) => item.trim().startsWith(HATCH_CID_COOKIE + "="));
if(hatchStoredCid.length > 0){
var hatchStoredCidValue = hatchStoredCid[0].split(HATCH_CID_COOKIE + "=")[1]
var hatchWidgets = document.querySelectorAll("[data-gh-buy-now-button]");
for(i = 0;i < hatchWidgets.length; i++) hatchWidgets[i].setAttribute("data-gh-cid", hatchStoredCidValue);
for(u = 0;u < hatchWidgets.length; u++) hatchWidgets[u].setAttribute("data-extra-request-parameters", "{'aid':'"+hatchStoredCidValue.toLowerCase()+"_'}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment