如何获取子域并使用greasemonkey将其加载到url?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (58)

我的网址是http://somesubdomain.domain.com(子域可能有所不同,域总是相同的)。需要采用子域名,并使用greasemonkey(或者打开一个URL为domain.com/some/path/here/somesubdomain的新窗口)使用类似domain.com/some/path/here/somesubdomain的东西重新加载页面。

提问于
用户回答回答于
var full = window.location.host
//window.location.host is subdomain.domain.com
var parts = full.split('.')
var sub = parts[0]
var domain = parts[1]
var type = parts[2]
//sub is 'subdomain', 'domain', type is 'com'
var newUrl = 'http://' + domain + '.' + type + '/your/other/path/' + subDomain
window.open(newUrl);
用户回答回答于

此方法将主机名拆分为{domain: "", type: "", subdomain: ""}

function splitHostname() {
        var result = {};
        var regexParse = new RegExp('([a-z\-0-9]{2,63})\.([a-z\.]{2,5})$');
        var urlParts = regexParse.exec(window.location.hostname);
        result.domain = urlParts[1];
        result.type = urlParts[2];
        result.subdomain = window.location.hostname.replace(result.domain + '.' + result.type, '').slice(0, -1);;
        return result;
}

console.log(splitHostname());

此方法仅将子域作为字符串返回:

function getSubdomain(hostname) {
        var regexParse = new RegExp('[a-z\-0-9]{2,63}\.[a-z\.]{2,5}$');
        var urlParts = regexParse.exec(hostname);
        return hostname.replace(urlParts[0],'').slice(0, -1);
}

console.log(getSubdomain(window.location.hostname));
// for use in node with express:  getSubdomain(req.hostname)

扫码关注云+社区

领取腾讯云代金券