For any of the following values:
- any.number.of.host.names.here.foo.domain.com
- foo.domain.com
- domain.com
the following will work:
"." + window.location.hostname.split('.').slice(-2).join('.');
A host of localhost
would return .localhost
in this case. I'm not entirely sure of the best behavior in that respect. See: Cookies on localhost with explicit domain
If you need to look out for IP addresses as a hostname, you''ll want to add a bit more logic to determine if it's an IP address.
A better approach might be:
function getDomain() {
var path = window.location.hostname.split('.');
// See above comment for best behavior...
if(path.length === 1) return window.location.hostname;
if(path.length === 4 && isIPAddress(path)) return window.location.hostname;
return "." + window.location.hostname.split('.').slice(-2).join('.');
}
// doesn't check for ip V6
function isIPAddress(path) {
for(var i = 0; i < path.length; ++i) {
if(path[i] < 0 || path[i] > 255) {
return false;
}
}
return true;
}
Important
As @Hiroto noted in one of the comments, make sure you know which domain(s) this logic will be used on. It wouldn't be a good idea to set cookies for .co.uk
. For an interesting read on this problem see: Mozilla Bug 252342: fix cookie domain checks to not allow .co.uk