Skip to content

Instantly share code, notes, and snippets.

@eduardocereto
Created July 3, 2012 21:18
Show Gist options
  • Save eduardocereto/3043239 to your computer and use it in GitHub Desktop.
Save eduardocereto/3043239 to your computer and use it in GitHub Desktop.
Always return top level domain
/**
* First domain where cookies can be set by the browser.
*/
function get_top_domain(){
var i,h,
weird_cookie='__top_level=cookie',
hostname = document.location.hostname.split('.');
for(i=hostname.length-1; i>=0; i--) {
h = hostname.slice(i).join('.');
document.cookie = weird_cookie + ';domain=.' + h + ';';
if(document.cookie.indexOf(weird_cookie)>-1){
document.cookie = weird_cookie.split('=')[0] + '=;domain=.' + h + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
return h;
}
}
return '';
}
@eduardocereto
Copy link
Author

Fails for localhost. In this case you can still set cookies but you need to omit the domain= part.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment