How to get referrer domain name / domain using JavaScript?

I know that I can get the host name of the current page by simply doing:

var myhostname = location.hostname; 

But how to get the host name for the referrer? I can get a referrer

 var referrer = document.referrer; 

but unfortunately there is no document.referrer.hostname available in JavaScript. How can I get this value?

An example of where this is useful is if someone clicks a link to google.com. I want to be able to retrieve google.com from the referrer (not the pages and query strings).

+52
javascript
Aug 05 '10 at 23:47
source share
7 answers

We disassemble it. document.referrer.split( '/' ); will bring you closer. Or take a look at this

http://blog.stevenlevithan.com/archives/parseuri

If the referrer comes from the browser, it will be normal - but just in case, you need a stronger analysis.

+24
Aug 05 '10 at 23:50
source share

This would do:

 document.referrer.split('/')[2]; 

Example.

+43
Aug 05 '10 at 23:59
source share
 function parseURL(url) { var a=document.createElement('a'); a.href=url; return a.hostname; } 

This is a relatively old question, however it can help any followers.

+31
Aug 05 '13 at 1:00
source share

You can use var referrer = new URL(document.referrer).hostname .

See https://developer.mozilla.org/en-US/docs/Web/API/URL.URL .

+9
Oct 16 '14 at 19:26
source share

You can use regexp to extract this data.

string.match(/^http([s]?)://([a-zA-Z0-9-_\.]+)(:[0-9]+)?/);

+1
Sep 23 '13 at 21:20
source share

It includes a protocol, but document.origin will work. It works through the Origin header, which does not contain path information included in it.

+1
Jul 18 '16 at 17:36
source share

Hi, use this function to get the domain name.

 function getDomain(url) { if (url) { var match = /(?:https?:\/\/)?(?:\w+:\/)?[^:?#\/\s]*?([^.\s]+\.(?:[az]{2,}|co\.uk|org\.uk|ac\.uk|org\.au|com\.au))(?:[:?#\/]|$)/gi .exec(url); return match ? match[1] : null; } else return null; } 
0
Jul 03 '15 at 12:50
source share



All Articles