2

I try to set a cookies via js using jQuery.cookie for all the current subdomains like this

$.cookie('account', 'myvalue', { path: '/', domain: '.domain.com' });

The thing is that window.location.hostname will return www.domain.com or domain.com depending on its context.

Is there any method available to simply replace the subdomain if present to a "." and if no subdomain present still show the . at the beginning?

putvande
  • 15,068
  • 3
  • 34
  • 50
Martin
  • 11,216
  • 23
  • 83
  • 140
  • 2
    `"." + window.location.hostname.split('.').slice(-2).join('.')` - but that won't work well with an IP address for a host. – dc5 Aug 10 '13 at 20:42

2 Answers2

1

The question asked "what is the quickest way", so this is the quickest way because it uses the least lines of code and does not add the overhead of the context switch that JavaScript has for functions, or a for loop:

var domain = window.location.hostname;
var parts = domain.split('.');
var isIpAddress;

// Decide whether host is IP address
isIpAddress = /[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}/.test(domain);

// If it's an IP, then use full host name,
// otherwise just use last two values of the dot-delimited host name array
if(isIpAddress)
    domain = window.location.hostname;
else
{
    if(parts.length <= 3)
       domain = '.'+window.location.hostname;
    else
       domain = '.'+window.location.hostname.split('.').slice(1).join('.');
}
Alex W
  • 37,233
  • 13
  • 109
  • 109
1

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

Community
  • 1
  • 1
dc5
  • 12,341
  • 2
  • 35
  • 47