Skip to content

Instantly share code, notes, and snippets.

@fblundun
Created January 7, 2016 12:07
Show Gist options
  • Save fblundun/59119a987bf4e8c934f2 to your computer and use it in GitHub Desktop.
Save fblundun/59119a987bf4e8c934f2 to your computer and use it in GitHub Desktop.
How to get the root domain on which cookies can be written
function getRootDomain() {
var split = window.location.hostname.split('.');
var position = split.length - 1;
while (position >= 0) {
var currentDomain = split.slice(position, split.length).join('.');
document.cookie = 'unique=unique;domain=' + currentDomain + ';';
if (document.cookie.indexOf('unique') > -1) {
return currentDomain;
}
position -= 1;
}
// Cookies cannot be read
return window.location.hostname;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment