Skip to content

Instantly share code, notes, and snippets.

@Kevinlearynet
Last active March 10, 2026 14:43
Show Gist options
  • Select an option

  • Save Kevinlearynet/af4b6f075dbbb73dc7cda0afba246e5f to your computer and use it in GitHub Desktop.

Select an option

Save Kevinlearynet/af4b6f075dbbb73dc7cda0afba246e5f to your computer and use it in GitHub Desktop.
/**
* Attribution Tracking
*
* Captures UTM parameters and click IDs from the URL and
* forward them to onboarding flows for app signup attribution.
*
* https://www.twindo.com/?gclid=google&wbraid=google&gbraid=google&fbclid=facebook&ttclid=tiktok&sclid=snapchat&twclid=twitter&rdt_cid=reddit&msclkid=bing
* https://www.twindo.com/?utm_source=test&utm_medium=cpc&utm_campaign=brand&utm_term=keyword&utm_content=adcopy
* https://www.twindo.com/?utm_source=test&utm_medium=cpc&utm_campaign=brand&utm_term=keyword&utm_content=adcopy&gclid=google&wbraid=google&gbraid=google&fbclid=facebook&ttclid=tiktok&sclid=snapchat&twclid=twitter&rdt_cid=reddit&msclkid=bing
*/
class WP_Attribution {
constructor() {
this.cookieName = "attribution";
this.cookieDomain = location.hostname === "twindo.test" ? "twindo.test" : ".twindo.com";
this.utmKeys = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
this.clickIds = ["gclid", "wbraid", "gbraid", "fbclid", "ttclid", "sclid", "twclid", "rdt_cid", "msclkid"];
this.init();
}
/**
* Get Root Domain
*
* Extracts the root domain from a hostname, stripping subdomains.
*/
domainRoot(hostname) {
const parts = hostname.split(".");
return parts.slice(-2).join(".");
}
/**
* Init
*
* Fetches country via Cloudflare trace, then captures attribution if allowed.
*/
async init() {
const res = await fetch("https://www.twindo.com/cdn-cgi/trace");
const text = await res.text();
const country = text.match(/loc=(\w+)/)?.[1] ?? null;
if (country !== "US") {
this.colorLog("Tracking Disabled for GDPR", {
country: country,
});
return;
}
this.capture();
this.test();
}
/**
* Testing Helper
*/
test() {
this.colorLog("Attribution", JSON.stringify(this.attribution, null, 2));
}
/**
* Color Log
*
* Logs a labeled message to the console with a gradient background.
*/
colorLog(label, data) {
console.log("%c" + label, "background:linear-gradient(90deg,#8b2a9b 0%,#e63946 50%,#e63946 100%);color:#fff;padding:2px 8px;border-radius:3px");
if (data !== undefined) console.log(data);
}
/**
* Get UTMs
*
* Retrieves and validates stored tracking data from cookie as parsed JSON
*/
get attribution() {
const match = document.cookie.match(new RegExp(`(?:^|; )${this.cookieName}=([^;]*)`));
if (!match) return null;
try {
const decoded = JSON.parse(decodeURIComponent(match[1]));
const hasUtms = Object.keys(decoded.utms || {}).some((k) => this.utmKeys.includes(k));
const hasClickIds = Object.keys(decoded.click_ids || {}).length > 0;
const hasReferrer = !!decoded.referrer;
return hasUtms || hasClickIds || hasReferrer ? decoded : null;
} catch {
return null;
}
}
/**
* Set UTMs
*
* Encodes and writes tracking JSON to first-party cookie with 30-day expiry
*/
set attribution(value) {
const expires = new Date();
expires.setDate(expires.getDate() + 30);
document.cookie = `${this.cookieName}=${encodeURIComponent(JSON.stringify(value))};domain=${this.cookieDomain};path=/;expires=${expires.toUTCString()};SameSite=Lax;Secure`;
}
/**
* Capture UTMs
*
* Reads UTM params, click IDs, and document referrer from current URL and stores as JSON.
* UTMs overwrite the entire utms object, click IDs merge individually into existing values,
* referrer preserves the first captured value.
*/
capture() {
const params = new URLSearchParams(window.location.search);
const data = { click_ids: {}, utms: {} };
let hasUtms = false;
let hasClickIds = false;
for (const [key, value] of params.entries()) {
if (this.utmKeys.includes(key)) {
data.utms[key] = value;
hasUtms = true;
} else if (this.clickIds.includes(key)) {
data.click_ids[key] = value;
hasClickIds = true;
}
}
const referrerHostname = document.referrer ? new URL(document.referrer).hostname : null;
const isSameDomain = referrerHostname && this.domainRoot(referrerHostname) === this.domainRoot(location.hostname);
const referrer = document.referrer && !isSameDomain ? document.referrer : null;
if (!hasUtms && !hasClickIds && !referrer) return;
const existing = this.attribution || { click_ids: {}, utms: {} };
const sourceUrl = existing.source_url || (window.location.href ?? null);
this.attribution = {
source_url: sourceUrl,
referrer: referrer || existing.referrer || null,
click_ids: hasClickIds ? { ...existing.click_ids, ...data.click_ids } : existing.click_ids,
utms: hasUtms ? data.utms : existing.utms,
};
}
}
new WP_Attribution();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment