在JavaScript中获取.domain.com的最快方法

时间:2013-08-10 20:35:37

标签: javascript

我尝试使用jQuery.cookie通过js为所有当前子域设置Cookie,如下所示

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

问题是window.location.hostname将返回www.domain.comdomain.com,具体取决于其背景。

是否有任何方法可以简单地将子域替换为“。”。如果没有子域存在仍然显示。一开始?

2 个答案:

答案 0 :(得分:1)

问题是“什么是最快的方式”,所以这是最快捷的方式,因为它使用最少的代码行,并且不会增加JavaScript对函数或for循环的上下文切换的开销:< / p>

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('.');
}

答案 1 :(得分:1)

对于以下任何值:

  • any.number.of.host.names.here.foo.domain.com
  • foo.domain.com
  • domain.com

以下内容将起作用:

"." + window.location.hostname.split('.').slice(-2).join('.');

在这种情况下,localhost的主机会返回.localhost。我不完全确定这方面的最佳行为。请参阅:Cookies on localhost with explicit domain

如果您需要查找IP地址作为主机名,您需要添加更多逻辑来确定它是否是IP地址。

更好的方法可能是:

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;
}

重要

正如@Hiroto在其中一条评论中指出的那样,请确保您知道将使用此逻辑的域。为.co.uk设置Cookie不是一个好主意。有关此问题的有趣读物,请参阅:Mozilla Bug 252342: fix cookie domain checks to not allow .co.uk