Multi-Domain Cookie & First-Party Context Preserver Script
Lightweight JavaScript snippet to preserve client identifiers across subdomains and mitigate Safari ITP cookie expiration.
Mitigating Safari ITP Tracking Loss
Safari Intelligent Tracking Prevention caps client-set cookies to 7 days or 24 hours when link decoration is detected. This script pairs root domain cookies with persistent localStorage keys so users returning after 7 days retain their original attribution parameters.
Implementation Code & Script
Writes first-party cookies to the root domain and syncs values with localStorage to prevent tracking resets.
(function() {
function getRootDomain() {
var parts = window.location.hostname.split('.');
if (parts.length <= 2) return window.location.hostname;
return '.' + parts.slice(-2).join('.');
}
function setRootCookie(name, value, days) {
var expires = '';
if (days) {
var d = new Date();
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + d.toUTCString();
}
var domain = getRootDomain();
document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/; domain=' + domain + '; SameSite=Lax; Secure';
}
function syncContext(key) {
var match = document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)'));
var cookieVal = match ? decodeURIComponent(match[2]) : null;
var storageVal = null;
try { storageVal = localStorage.getItem('gg_' + key); } catch(e) {}
if (cookieVal && !storageVal) {
try { localStorage.setItem('gg_' + key, cookieVal); } catch(e) {}
} else if (!cookieVal && storageVal) {
setRootCookie(key, storageVal, 90);
}
}
// Preserve critical advertising and analytics identifiers
['_fbp', '_fbc', '_ga', 'user_id'].forEach(syncContext);
})();How to cite and attribute this tool
MIT LicenceThis resource is free, open and un-gated under the MIT Open Source Licence. You are encouraged to use, integrate and cite it with attribution:
Geraghty, G. (2026). Multi-Domain Cookie & First-Party Context Preserver Script. Gordon Geraghty Resources Hub. https://gordongeraghty.com/resources/gtm-analytics/multi-domain-cookie-preserver
BibTeX Format
@misc{geraghty_multi_domain_cookie_preserver,
author = {Geraghty, Gordon},
title = {Multi-Domain Cookie & First-Party Context Preserver Script},
year = {2026},
url = {https://gordongeraghty.com/resources/gtm-analytics/multi-domain-cookie-preserver},
note = {Head of Performance, Empire Amplify}
}Changelog & Version History
v1.0.0Initial release of multi-domain cookie preserver with localStorage backup.