cJS – Traffic Source
cJS – Traffic Source
GTM Custom JavaScript Variable Last updated: November 2026
Overview
This GTM Custom JavaScript variable detects and returns the traffic source for a website visitor as one flat string (google_ads, facebook_ads, google_organic, newsletter_email, referral, direct, …). It is designed to work for both lead generation (form submissions) and ecommerce (Purchase events) by populating a traffic_source or source custom parameter on conversion tags — most commonly the Meta Pixel Lead and Purchase events.
Its classification rules mirror the MTK Attribution engine: the same click IDs, the same utm_medium values, the same referrer domain lists, and the same fresh-cookie rescue — collapsed to a single string instead of a separate channel and source. If a site runs both, the two agree on where a visit came from.
The variable uses last-touch attribution within a session: each new entry to the site with a fresh click ID or UTM replaces the prior value, so the conversion is credited to the channel that most recently brought the user in. localStorage carries the resolved value across pages and browser tabs, so attribution is preserved through popup forms on internal pages, multi-step checkouts, and pages the visitor opens in a new tab.
How It Works
Detection Priority
The variable resolves an entry from that pageview's URL parameters, referrer, and platform cookies, walking the rules below in order. The first match wins. All comparisons are case-insensitive.
| Priority | Signal | Returns |
|---|---|---|
| 1 | Paid social (no gclid / gbraid / wbraid / msclkid in URL) — any of: utm_medium containing both "paid" and "social" (paid_social, paidsocial, social-paid); utm_medium=paid / cpc / ppc with a social signal (social utm_source, fbclid / ttclid in URL, or a social referrer); a social utm_medium (social, social-media, sm, social-network) with a utm_campaign | {source}_ads — the platform from the click ID or referrer, else facebook_ads, when utm_source is missing |
| 2 | gclid, gbraid, or wbraid in URL, or utm_medium=cpc / paid_search with a Google (or no) utm_source | google_ads |
| 3 | msclkid in URL, or utm_medium=cpc / paid_search with utm_source = bing / bingads / microsoft | microsoft_ads |
| 4 | utm_medium=cpc / paid_search with any other utm_source | {source}_ads |
| 5 | ttclid in URL | tiktok_ads |
| 6 | utm_medium=email | {source}_email, or email when utm_source is missing |
| 7 | A social utm_medium with no utm_campaign | {source}_organic (e.g. instagram_organic) |
| 8 | Any other utm_source | {source}_{medium} (e.g. partner_referral), or {source} when there is no medium |
| 9 | Referrer host is a search engine (google., bing., yahoo., duckduckgo., ecosia.) | {engine}_organic — a Google referrer with a fresh _gcl_aw cookie upgrades to google_ads |
| 10 | Referrer host is a social network (facebook., fb., instagram., linkedin., twitter., x.com, t.co, youtube., reddit., pinterest., tiktok.), or fbclid in URL with any external referrer | {network}_organic — a Facebook/Instagram referrer with a fresh _fbc cookie and no fbclid in the URL upgrades to facebook_ads |
| 11 | Any other external referrer | referral |
| 12 | fbclid in URL with no referrer at all | facebook_organic |
| 13 | No signals, but a fresh _gcl_aw cookie | google_ads |
| 14 | No signals, but a fresh _fbc cookie | facebook_ads |
| 15 | Nothing identifying | direct |
utm_source values typed as a hostname are first collapsed to their platform (facebook.com / m.facebook.com → facebook, google.com → google, t.co → twitter, youtu.be → youtube), so they classify and report exactly like the bare name; an unknown hostname keeps its host minus www. (www.partnersite.com → partnersite_com). Values are then normalized through a small alias table, so Meta's {{site_source_name}} values come out readable: fb → facebook, ig → instagram, msg → messenger, an → audience_network, x → twitter, googleads / adwords → google, bingads / bing → microsoft. Anything else is lower-cased and snake_cased (Facebook Ads → facebook_ads).
Referrer domains are matched against the referrer's hostname only, with label boundaries: google. matches google.com and news.google.de but not notgoogle.com; x.com matches x.com and www.x.com but not wix.com; bing. never matches plumbing.com. A referrer from the site's own hostname is internal navigation and never classifies.
Attribution Model
This variable uses last-touch attribution within a session. The value is resolved once, on the pageview that brought the visitor in, and stored. A later pageview only re-resolves when:
- the URL carries a fresh campaign signal — any
utm_source,utm_medium,utm_campaign, or any ofgclid,gbraid,wbraid,msclkid,fbclid,ttclid; or - the site has been idle for more than 30 minutes in every tab (GA-style session timeout); or
- nothing is stored yet (first pageview of the visit, or storage was blocked).
A session belongs to the browser, not the tab: every tab on the site shares one stored value and one idle clock, the way a GA4 session does.
Internal navigation never changes attribution — and neither does an external referrer on its own. A mid-checkout bounce through PayPal, Stripe, or an OAuth provider comes back with a foreign referrer and no campaign signal, and the stored paid source survives it.
This means:
- A user who clicks a Google Ad, leaves, and returns via a Facebook Ad will be attributed to Facebook on conversion — and vice versa. The newest signal always wins, whichever platform it came from.
- A user who clicks a Facebook Ad, browses to checkout over multiple pages, and converts is still attributed to Facebook because localStorage carries the resolved value through the funnel.
- A user who clicks a Google Ad and opens a page in a new tab is still attributed to Google Ads in that tab. (Before v2.3 the new tab started over and usually reported
direct.) - Tabs share one value: a user who arrives from a Google Ad in one tab and then a Facebook Ad in another is attributed to Facebook in both — whichever ad brought them in most recently.
- A user who leaves the site idle for more than 30 minutes and comes back via organic search is re-resolved as organic search, even if a tab stayed open or the browser was restarted in between.
To switch to first-touch attribution: skip the re-resolve when a value is already stored, and drop the 30-minute expiry. (Or use MTK Attribution, which reports first touch, last touch, and the full journey.)
Funnel and Tab Persistence via localStorage
Without persistence, multi-page funnels would lose attribution. By the second page of a checkout, document.referrer becomes your own domain, and click IDs disappear from the URL once the user navigates internally. A page opened in a new tab has the same problem.
The variable stores a single key, cjs_traffic_source, holding the resolved value and the time of the last pageview: {"v":"google_ads","t":1700000000000}. It lives in localStorage, which every tab on the site's origin shares. Every pageview in any tab reads the stored value and refreshes the timestamp, so a visitor who keeps navigating never times out.
If localStorage is blocked, the variable falls back to sessionStorage, which keeps attribution through the funnel in that one tab only. If both are blocked (some private-browsing modes), each pageview is resolved on its own. The variable also reads sessionStorage when localStorage holds nothing, so visits that were already in progress when you upgraded from v2.2 or earlier keep their source.
Why UTMs Are Required for Paid Social
Facebook (and Instagram) append fbclid to all outbound links — both paid ads and organic posts. Relying on fbclid or the _fbc cookie alone would incorrectly label organic Facebook traffic as paid.
To distinguish paid from organic, paid social ad URLs must include UTMs following this convention:
| Channel | utm_source | utm_medium |
|---|---|---|
| Meta Ads (all placements) | {{site_source_name}} (fb, ig, msg, an) | paid_social |
| LinkedIn Ads | paid_social | |
| TikTok Ads (paid) | tiktok | paid_social |
paid_social is the recommended value, but the variable also accepts the other common ways social ads get tagged:
- any
utm_mediumspelling both "paid" and "social" —paidsocial,social-paid,Paid Social; utm_medium=paid(Meta's own URL-builder default),cpc, orppcwith a social signal — a socialutm_source(facebook,fb,meta,instagram,ig,messenger,msg,an,tiktok,linkedin,twitter,x,reddit,pinterest,youtube,snapchat,threads,quora,nextdoor, or a hostname such asfacebook.com), anfbclid/ttclid, or a social referrer;- a social
utm_medium(social,social-media,sm,social-network) with autm_campaign. The campaign is what separates an ad from a post:utm_medium=socialwith no campaign returns{source}_organic.
A Google or Microsoft click ID in the URL still wins as paid search. Tag organic posts without a utm_campaign — an organic post tagged utm_medium=social&utm_campaign=… reads as paid.
Any click with fbclid and none of the paid signals above is treated as organic. Without consistent UTM tagging on ad URLs, paid and organic Facebook traffic will be misattributed.
The one exception is the _fbc cookie rescue: when a Facebook or Instagram referrer arrives with no fbclid in the URL but the Pixel's _fbc cookie was created within the last 30 minutes, the click's parameter was lost in transit (consent redirect, URL rewrite) and the visit is credited to facebook_ads. An _fbc sitting next to an fbclid proves nothing — the Pixel writes _fbc from whichever fbclid it sees, organic or paid — so that case stays organic.
For Google, Microsoft, and TikTok, the platform-specific click IDs (gclid / gbraid / wbraid, msclkid, ttclid) are unique to paid traffic and don't have this collision problem. UTMs are optional for those channels but recommended for GA4 reporting consistency; utm_medium=cpc on its own is also recognised as paid search.
Google Ads Attribution
Google Ads detection works in three layers:
gclid,gbraid, orwbraidin the URL — present on the landing page when a user clicks a Google Ad.gbraidandwbraidare the iOS privacy-preserving equivalents ofgclid; without them, iOS ad clicks fall through to organic or direct.utm_medium=cpc— catches manually tagged ads when auto-tagging is off or a redirect stripped the click ID.- Fresh
_gcl_awcookie — set automatically by gtag.js / the Conversion Linker when auto-tagging is enabled. The cookie embeds its creation time (GCL.{seconds}.{gclid}), and only a cookie created within the last 30 minutes counts: it either upgrades a Google organic referrer togoogle_adsor rescues a direct arrival. A stale cookie is ignored — those cookies live ~90 days, and honouring one would relabel every returning visitor asgoogle_adsfor months, over their real email, Microsoft Ads, or organic source.
For the _gcl_aw fallback to work, the Google Ads account must have auto-tagging enabled and gtag.js or the Conversion Linker must be firing on the site.
Lead Gen vs. Ecommerce Use
The same variable works for both conversion types because the underlying attribution problem is the same: a user enters with a source signal, navigates internally, and converts on a deeper page.
For lead gen (popup forms, contact forms):
- Used in Meta Pixel Lead event as
traffic_sourceparameter - Captures source even when the popup appears on a different page than the landing page
For ecommerce (multi-step checkout):
- Used in Meta Pixel Purchase event as
sourceparameter - Captures source through cart → checkout → confirmation flow
Both use cases benefit from the localStorage persistence layer — without it, attribution would collapse to direct on internal pages and in new tabs.
Cross-Tab Behavior
Since v2.3, every tab on the site shares one stored value. If a user opens a page in a new tab partway through a visit (say, a portfolio page from the menu, or checkout from a cart), the new tab reports the source that started the visit instead of re-detecting from its own internal referrer, which almost always came out direct.
Because the value is shared, the most recent campaign signal in any tab wins in every tab. That's the same last-touch rule applied across tabs, and it matches how a GA4 session treats a new campaign.
Before v2.3 the value lived in sessionStorage, which is scoped to a single tab, so a new tab started fresh. If you're still on v2.2 or earlier, expect direct to be over-reported on conversions that happen in a second tab.
Known Limitations
- No cross-session attribution. 30 minutes without a pageview in any tab ends the session. A user who visits via Facebook Ads on Monday and converts via direct on Wednesday will be attributed to direct on Wednesday. This is intentional last-touch behavior; use MTK Attribution for first-touch and journey reporting.
- iOS Safari ITP restricts cookie and storage lifetimes on Apple devices. The
_fbcand_gcl_awcookies may have shortened lifespans, which can affect the cookie rescues specifically. - Untagged Meta ads look organic. A paid Facebook click that arrives with
fbclidbut no paid-socialutm_medium(see above) returnsfacebook_organic. This is by design — see above. - Untagged landing pages with no referrer are direct. If a user lands with no UTMs, no click ID, no referrer, and no fresh platform cookie, the visit is
direct, and a later form submit on an internal page inherits that. UTM-tag your landing pages. - Referrer-based organic detection relies on
document.referreron the entry pageview. If the landing page is reached via a redirect that strips the referrer, the visit resolves asdirectunless a fresh platform cookie rescues it. - Unknown referrers are bucketed as
referral, not reported by hostname, to keep the value's cardinality low in Meta and GA4 reports.
Usage in GTM
Variable Setup
- Variable type: Custom JavaScript
- Variable name: cJS - Traffic Source
- Return type: String
Paste the contents of cjs-traffic-source.js as the variable body, or import the GTM Essentials container which includes it.
Tag Implementation — Lead Event
<script>
fbq('track', 'Lead', {
lead_type: 'Form Submit',
content_name: '{{Page Path}}',
traffic_source: '{{cJS - Traffic Source}}', // last-touch traffic source
ad_placement: '{{cJS - Ad Placement}}'
}, {
eventID: '{{cJS - Custom Event ID}}'
});
</script>
Tag Implementation — GA4 Event Parameter
| Parameter | Value |
|---|---|
cjs_traffic_source | {{cJS - Traffic Source}} |
Register cjs_traffic_source as a custom dimension in GA4 to report on it.
The code
/*!
* Marketing Toolkit — cJS – Traffic Source
* Version: v2.3.0
* Last updated: 2026-11-24
* https://github.com/whboggs/marketing-toolkit
*/
function() {
// cJS - Traffic Source
//
// Last-touch traffic source for lead gen and ecommerce conversion tags, returned as one
// flat snake_case string (google_ads, facebook_ads, google_organic, newsletter_email,
// referral, direct, ...).
//
// Classification mirrors the MTK Attribution engine (resolveTouch): the same click IDs,
// the same utm_medium values, the same referrer domain lists, and the same fresh-cookie
// rescue — collapsed to a single string instead of channel + source.
//
// An ENTRY is resolved once, from the pageview that brought the visitor in, and carried
// across every tab on the site in localStorage so popup forms, multi-step checkouts, and
// pages opened in a new tab still report the source that started the visit. Every tab
// shares one entry and one idle clock, like a GA4 session. A later pageview only replaces
// the stored entry when it carries a fresh campaign signal in the URL (a click ID or a
// UTM) or the tab has been idle for longer than the session window — internal navigation
// never changes attribution, and neither does a mid-funnel bounce through a payment
// gateway or an OAuth provider.
var STORE_KEY = 'cjs_traffic_source'; // localStorage key: {"v": "<source>", "t": <last activity ms>}
var SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes, GA-style — idle longer than this = new entry
var PAID_SOCIAL_MEDIUM = 'paid_social'; // the canonical paid-social utm_medium (always paid social)
// Paid Social, beyond paid_social — mirrors the MTK engine (v7.0):
// 1. a medium containing both "paid" and "social" (paidsocial, social-paid) — on its own;
// 2. a generic paid medium (PAID_GENERIC_MEDIUMS) with a social signal: a social utm_source,
// an fbclid / ttclid, or a social referrer;
// 3. a social medium (SOCIAL_MEDIUMS) WITH a utm_campaign. Without a campaign it's organic.
// A Google / Microsoft click ID still wins as paid search.
var PAID_GENERIC_MEDIUMS = ['paid', 'cpc', 'ppc'];
var SOCIAL_MEDIUMS = ['social', 'social-media', 'social_media', 'social media', 'sm', 'social-network', 'social_network', 'social network'];
// utm_source spellings that name a social platform (hostname styles like m.facebook.com match too).
var SOCIAL_SOURCES = ['facebook', 'fb', 'meta', 'instagram', 'ig', 'messenger', 'msg', 'an', 'audience_network',
'tiktok', 'linkedin', 'twitter', 'x', 'reddit', 'pinterest', 'youtube', 'snapchat', 'threads', 'quora', 'nextdoor'];
// Referrer domain lists — same fragments as the MTK engine defaults. A trailing dot means
// "this label anywhere in the host" (google.com, news.google.de); an inner dot means "this
// exact domain or a subdomain of it" (x.com, www.x.com — but never wix.com).
var SEARCH_DOMAINS = ['google.', 'bing.', 'yahoo.', 'duckduckgo.', 'ecosia.'];
var SOCIAL_DOMAINS = ['facebook.', 'fb.', 'instagram.', 'linkedin.', 'twitter.', 'x.com', 'youtube.', 'reddit.', 'pinterest.', 'tiktok.', 't.co'];
// utm_source aliases -> the platform name this variable reports. Covers Meta's
// site_source_name values (fb / ig / msg / an) recommended in the UTM docs, so a paid
// Facebook click tagged utm_source=fb returns facebook_ads, not fb_ads.
var SOURCE_ALIASES = {
fb: 'facebook', ig: 'instagram', msg: 'messenger', an: 'audience_network',
x: 'twitter', 'x.com': 'twitter',
googleads: 'google', adwords: 'google',
bingads: 'microsoft', bing: 'microsoft'
};
// ---------------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------------------
var params = new URLSearchParams(window.location.search);
function param(key) { return params.get(key) || ''; }
function lower(s) { return s ? String(s).toLowerCase() : ''; }
// Turn any typed value into a safe snake_case token ("Facebook Ads" -> "facebook_ads").
function slug(s) {
return lower(s).replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
}
// Hostname labels that name a known platform -> the bare utm_source key it normally arrives as.
var HOST_PLATFORMS = {
facebook: 'facebook', fb: 'facebook', instagram: 'instagram', messenger: 'messenger',
linkedin: 'linkedin', lnkd: 'linkedin', twitter: 'twitter', x: 'x', t: 'x',
youtube: 'youtube', youtu: 'youtube', reddit: 'reddit', pinterest: 'pinterest',
tiktok: 'tiktok', snapchat: 'snapchat', threads: 'threads', quora: 'quora',
nextdoor: 'nextdoor', google: 'google', bing: 'bing', yahoo: 'yahoo',
duckduckgo: 'duckduckgo', ecosia: 'ecosia'
};
// A utm_source typed as a hostname collapses to its platform key ("m.facebook.com" -> "facebook",
// "t.co" -> "x"); an unknown hostname keeps its host minus "www.". Bare values pass through.
function platformKey(key) {
if (!key || key.indexOf('.') === -1) return key;
var host = key.replace(/^www\./, '');
var labels = host.split('.');
for (var i = 0; i < labels.length - 1; i++) { // every label but the TLD
if (HOST_PLATFORMS.hasOwnProperty(labels[i]) && (labels[i] !== 't' || host === 't.co')) {
return HOST_PLATFORMS[labels[i]];
}
}
return host;
}
// Hostname clean-up, alias lookup, then slug — so utm_source=IG, Instagram, and
// l.instagram.com all give "instagram"; www.partnersite.com gives "partnersite_com".
function sourceName(raw) {
var key = platformKey(lower(raw));
if (!key) return '';
return SOURCE_ALIASES.hasOwnProperty(key) ? SOURCE_ALIASES[key] : slug(key);
}
// Is this value in the list? (ES5 stand-in for Array.prototype.includes.)
function inList(value, list) {
for (var i = 0; i < list.length; i++) { if (list[i] === value) return true; }
return false;
}
// Rule 1: the canonical paid-social medium, or any spelling carrying both "paid" and "social".
function isPaidSocialMedium(medium) {
if (!medium) return false;
if (medium === PAID_SOCIAL_MEDIUM) return true;
return medium.indexOf('paid') > -1 && medium.indexOf('social') > -1;
}
// Does utm_source name a social platform? Bare names (facebook) and hostnames (m.facebook.com).
function isSocialUtmSource(source) {
if (!source) return false;
if (inList(source, SOCIAL_SOURCES)) return true;
var parts = source.replace(/^www\./, '').split('.');
for (var i = 0; i < parts.length - 1; i++) { // every label but the TLD
if (inList(parts[i], SOCIAL_SOURCES)) return true;
}
return false;
}
// Entry storage. localStorage is shared by every tab on the site's origin, so a page opened
// in a new tab inherits the entry instead of starting over as "direct" (sessionStorage is
// per-tab, which is what lost it before v2.3). sessionStorage is the fallback where
// localStorage is blocked; reading it also carries an entry written by v2.2 or earlier
// through a visit that is mid-flight when the upgrade publishes. Both blocked (some private
// browsing modes) degrades to "no persistence": each pageview resolves on its own.
var STORE_AREAS = ['localStorage', 'sessionStorage'];
function readStore() {
for (var i = 0; i < STORE_AREAS.length; i++) {
try {
var raw = window[STORE_AREAS[i]].getItem(STORE_KEY);
if (raw) return JSON.parse(raw); // first area holding an entry wins
} catch (e) { /* area blocked or value unreadable: try the next one */ }
}
return null;
}
function writeStore(value) {
var entry = JSON.stringify({ v: value, t: Date.now() });
for (var i = 0; i < STORE_AREAS.length; i++) {
try { window[STORE_AREAS[i]].setItem(STORE_KEY, entry); return; } catch (e) { /* try the next area */ }
}
}
// Referrer HOST only — scheme, userinfo, port, and path stripped — so a path or query string
// containing "x.com" or "google." can never be mistaken for the referring domain.
var referrer = lower(document.referrer);
var refHost = referrer
.replace(/^[a-z][a-z0-9+.-]*:\/\//, '')
.split('/')[0]
.split('@').pop()
.split(':')[0];
var selfHost = lower(window.location.hostname);
// A referrer from the site's own hostname is internal navigation, not attribution.
var hasReferrer = referrer !== '' && refHost !== selfHost;
// Boundary-aware domain match against refHost (see SEARCH_DOMAINS comment for the styles).
function hostMatches(frag) {
if (!frag) return false;
if (frag.charAt(frag.length - 1) === '.') {
// "google." — label prefix anywhere in the host
return refHost.indexOf(frag) === 0 || refHost.indexOf('.' + frag) > -1;
}
if (frag.indexOf('.') > -1) {
// "x.com" — exact registrable domain or a subdomain of it
if (refHost === frag) return true;
var tail = '.' + frag;
return refHost.length > tail.length && refHost.indexOf(tail) === refHost.length - tail.length;
}
return refHost.indexOf(frag) > -1; // plain substring for loose custom entries
}
function matchesList(list) {
for (var i = 0; i < list.length; i++) { if (hostMatches(list[i])) return true; }
return false;
}
// The platform name behind a referrer, used for the "<name>_organic" buckets. Anything not
// listed reports its registrable-ish host label (e.g. "ecosia" for ecosia.org).
function referrerName() {
if (hostMatches('google.')) return 'google';
if (hostMatches('bing.')) return 'bing';
if (hostMatches('yahoo.')) return 'yahoo';
if (hostMatches('duckduckgo.')) return 'duckduckgo';
if (hostMatches('facebook.') || hostMatches('fb.')) return 'facebook';
if (hostMatches('instagram.')) return 'instagram';
if (hostMatches('linkedin.')) return 'linkedin';
if (hostMatches('twitter.') || hostMatches('x.com') || hostMatches('t.co')) return 'twitter';
if (hostMatches('youtube.')) return 'youtube';
if (hostMatches('reddit.')) return 'reddit';
if (hostMatches('pinterest.')) return 'pinterest';
if (hostMatches('tiktok.')) return 'tiktok';
var labels = refHost.replace(/^www\./, '').split('.');
return slug(labels.length > 1 ? labels[labels.length - 2] : labels[0]);
}
// Cookie reader — exact name match, so "_gcl_aw" can't be satisfied by "x_gcl_aw".
function readCookie(name) {
var parts = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0; i < parts.length; i++) {
var pair = parts[i].split('=');
if (pair[0] === name) {
try { return decodeURIComponent(pair.slice(1).join('=')); } catch (e) { return ''; }
}
}
return '';
}
// Platform cookies embed the click ID AND its creation time. Only a FRESH cookie — created
// within the session window — may classify an entry. A stale one just means "returning
// visitor" (these cookies live ~90 days); using it would erase Direct and double-credit ads
// for months. Returns the click ID, or null.
function freshClickCookie(name, tsIndex, tsUnit) {
var raw = readCookie(name);
if (!raw) return null;
var parts = raw.split('.');
var ts = parseInt(parts[tsIndex], 10);
if (!ts) return null;
if (tsUnit === 's') ts = ts * 1000;
var age = Date.now() - ts;
if (age < 0 || age > SESSION_TIMEOUT) return null;
return parts.slice(tsIndex + 1).join('.') || null;
}
function freshGclid() { return freshClickCookie('_gcl_aw', 1, 's'); } // "_gcl_aw" = GCL.{seconds}.{gclid}
function freshFbclid() { return freshClickCookie('_fbc', 2, 'ms'); } // "_fbc" = fb.1.{ms}.{fbclid}
// Does THIS pageview carry a campaign signal — any UTM or any ad-platform click ID? Read from
// the URL only: cookies outlive the click by weeks and must never look like a fresh arrival.
function hasCampaignSignal() {
if (param('utm_source') || param('utm_medium') || param('utm_campaign')) return true;
return !!(param('gclid') || param('gbraid') || param('wbraid') ||
param('msclkid') || param('fbclid') || param('ttclid'));
}
// ---------------------------------------------------------------------------------------
// Resolver — the MTK engine's rule order, flattened to one string. First match wins.
// ---------------------------------------------------------------------------------------
function resolve() {
var utmSourceRaw = param('utm_source');
var utmSource = platformKey(lower(utmSourceRaw)); // "google.com" compares as "google"
var utmMedium = lower(param('utm_medium'));
var gclid = param('gclid');
var gbraid = param('gbraid'); // iOS web-to-app Google Ads click ID
var wbraid = param('wbraid'); // iOS app-to-web Google Ads click ID
var msclkid = param('msclkid');
var fbclid = param('fbclid');
var ttclid = param('ttclid');
var hasPaidSearchClickId = gclid || gbraid || wbraid || msclkid;
var socialMedium = inList(utmMedium, SOCIAL_MEDIUMS);
// The social platform behind this visit: typed source first, then click ID, then referrer.
function socialName() {
if (utmSourceRaw) return sourceName(utmSourceRaw);
if (ttclid) return 'tiktok';
if (fbclid) return 'facebook';
if (hasReferrer && matchesList(SOCIAL_DOMAINS)) return referrerName();
return 'facebook';
}
// 1. Paid Social — see PAID_GENERIC_MEDIUMS / SOCIAL_MEDIUMS. Checked before paid search so
// utm_source=facebook&utm_medium=cpc is a social ad; a Google / Microsoft click ID still
// wins. fbclid alone never proves a paid click (Meta appends it to organic posts too).
var socialSignal = isSocialUtmSource(utmSource) || fbclid || ttclid ||
(hasReferrer && matchesList(SOCIAL_DOMAINS));
if (!hasPaidSearchClickId && (
isPaidSocialMedium(utmMedium) ||
(inList(utmMedium, PAID_GENERIC_MEDIUMS) && socialSignal) ||
(socialMedium && param('utm_campaign')))) {
return socialName() + '_ads';
}
// 2. Paid Search — any Google / Microsoft click ID, or utm_medium=cpc / paid_search
// (manual tagging with auto-tagging off, or a click ID stripped by a redirect).
if (gclid || gbraid || wbraid || msclkid || utmMedium === 'cpc' || utmMedium === 'paid_search') {
if (msclkid || utmSource === 'bing' || utmSource === 'bingads' || utmSource === 'microsoft') return 'microsoft_ads';
if (!utmSource || utmSource === 'google' || utmSource === 'googleads' || utmSource === 'adwords') return 'google_ads';
return sourceName(utmSourceRaw) + '_ads'; // some other paid-search network, tagged by hand
}
// 3. TikTok Ads — ttclid is paid-only (organic TikTok links don't carry it).
if (ttclid) return 'tiktok_ads';
// 4. Email — "<source>_email" (newsletter_email, klaviyo_email), or plain "email" when untagged.
if (utmMedium === 'email') {
return utmSource ? sourceName(utmSourceRaw) + '_email' : 'email';
}
// 5. Organic Social (tagged) — a social medium with no utm_campaign is a post, not an ad.
if (socialMedium) return socialName() + '_organic';
// 6. Any other tagged campaign — "<source>_<medium>" (partner_referral, podcast_sponsorship),
// or just "<source>" when there is no medium.
if (utmSource) {
return utmMedium ? sourceName(utmSourceRaw) + '_' + slug(utmMedium) : sourceName(utmSourceRaw);
}
// 7. Untagged arrival with an external referrer.
if (hasReferrer) {
if (matchesList(SEARCH_DOMAINS)) {
// Same-platform upgrade: an ad click FROM google.com whose gclid was lost in transit
// still set a fresh _gcl_aw — that's Google Ads, not organic.
if (hostMatches('google.') && freshGclid()) return 'google_ads';
return referrerName() + '_organic';
}
if (matchesList(SOCIAL_DOMAINS) || fbclid) {
// Same-platform upgrade — but ONLY when the URL carried no fbclid. The Pixel writes _fbc
// from whichever fbclid it sees, so a fresh _fbc next to an fbclid is just that (possibly
// organic) click echoed back. With no fbclid in the URL, a fresh _fbc is real evidence of
// a paid click whose parameter went missing.
if (!fbclid && (hostMatches('facebook.') || hostMatches('fb.') || hostMatches('instagram.')) && freshFbclid()) {
return 'facebook_ads';
}
// fbclid from a referrer outside the social list (e.g. a Messenger in-app browser) is still Meta.
return (matchesList(SOCIAL_DOMAINS) ? referrerName() : 'facebook') + '_organic';
}
return 'referral'; // some other site we don't bucket
}
// 8. fbclid with no referrer at all (some in-app browsers strip it) — still an organic Meta click.
if (fbclid) return 'facebook_organic';
// 9. Cookie rescue — last resort before Direct. A FRESH platform cookie means an ad click just
// happened but its URL signal never reached us (consent redirect, URL rewrite, tag first
// firing mid-session). Stale cookies never classify.
if (freshGclid()) return 'google_ads';
if (freshFbclid()) return 'facebook_ads';
// 10. Nothing identifying — typed URL, bookmark, app, dark social.
return 'direct';
}
// ---------------------------------------------------------------------------------------
// Entry handling — reuse the stored entry through internal navigation; re-resolve on a fresh
// campaign signal, after the idle window, or when nothing is stored yet.
// ---------------------------------------------------------------------------------------
var stored = readStore();
var expired = !stored || !stored.t || (Date.now() - stored.t) > SESSION_TIMEOUT;
if (stored && stored.v && !expired && !hasCampaignSignal()) {
writeStore(stored.v); // touch last-activity, keep the value
return stored.v;
}
var value = resolve();
writeStore(value);
return value;
}