如何使用 JavaScript 获取引用者的域名/主机名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3420031/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the referrer's domain/host name using JavaScript?
提问by Keltex
I know I can get the host name of the current page, by simply doing:
我知道我可以通过简单地获取当前页面的主机名:
var myhostname = location.hostname;
But how do I get the host name of the referrer? I can get the referrer by
但是我如何获得引用者的主机名?我可以通过以下方式获得推荐人
var referrer = document.referrer;
but unfortunately there's no document.referrer.hostnameavailable in JavaScript. How can I get this value?
但不幸的是,document.referrer.hostname在 JavaScript 中没有可用的。我怎样才能得到这个值?
An example of where this is useful is if somebody clicks a link on google.com. I want to be able to retrieve google.com from the referrer (not the page and the query string).
这很有用的一个例子是,如果有人点击了 google.com 上的链接。我希望能够从引荐来源网址(而不是页面和查询字符串)检索 google.com。
采纳答案by Lou Franco
By parsing it.  document.referrer.split( '/' );will get you close.  Or take a look at this
通过解析它。  document.referrer.split( '/' );会让你靠近。或者看看这个
http://blog.stevenlevithan.com/archives/parseuri
http://blog.stevenlevithan.com/archives/parseuri
If referrer is coming from a browser, it will be sane -- but just in case you want more robust parsing.
如果referrer 来自浏览器,它会是理智的——但以防万一你想要更健壮的解析。
回答by adnan korkmaz
function parseURL(url) {
    var a=document.createElement('a');
    a.href=url;
    return a.hostname;
}
This is a relatively old question, nevertheless this may help any followers.
这是一个相对古老的问题,不过这可能对任何追随者有所帮助。
回答by chipit24
You can use var referrer = new URL(document.referrer).hostname.
您可以使用var referrer = new URL(document.referrer).hostname.
See https://developer.mozilla.org/en-US/docs/Web/API/URL.URL.
请参阅https://developer.mozilla.org/en-US/docs/Web/API/URL.URL。
回答by baquiax
You can use regexp to extract this data.
您可以使用正则表达式来提取此数据。
string.match(/^http([s]?)://([a-zA-Z0-9-_\.]+)(:[0-9]+)?/);
string.match(/^http([s]?)://([a-zA-Z0-9-_\.]+)(:[0-9]+)?/);
回答by Java4you
Hi use this function to get domain name.
嗨,使用此功能获取域名。
function getDomain(url) {
    if (url) {
        var match = /(?:https?:\/\/)?(?:\w+:\/)?[^:?#\/\s]*?([^.\s]+\.(?:[a-z]{2,}|co\.uk|org\.uk|ac\.uk|org\.au|com\.au))(?:[:?#\/]|$)/gi
                .exec(url);
        return match ? match[1] : null;
    } else
        return null;
}
回答by elkelk
It includes the protocol, but document.originwill work. It works via the Origin header, which has no path information included with it.
它包括协议,但document.origin会起作用。它通过 Origin 标头工作,其中不包含路径信息。

