How do I get the referrer's domain/host name using JavaScript?

Javascript

Javascript Problem Overview


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.hostname available in JavaScript. How can I get this value?

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).

Javascript Solutions


Solution 1 - Javascript

This would do:

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

Example.

Solution 2 - Javascript

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.

Solution 3 - Javascript

By parsing it. document.referrer.split( '/' ); will get you close. Or take a look at this

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.

Solution 4 - Javascript

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

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

Solution 5 - Javascript

You can use regexp to extract this data.

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

Solution 6 - Javascript

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

Solution 7 - Javascript

It includes the protocol, but document.origin will work. It works via the Origin header, which has no path information included with it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeltexView Question on Stackoverflow
Solution 1 - JavascriptGert GrenanderView Answer on Stackoverflow
Solution 2 - Javascriptadnan korkmazView Answer on Stackoverflow
Solution 3 - JavascriptLou FrancoView Answer on Stackoverflow
Solution 4 - Javascriptchipit24View Answer on Stackoverflow
Solution 5 - JavascriptbaquiaxView Answer on Stackoverflow
Solution 6 - JavascriptJava4youView Answer on Stackoverflow
Solution 7 - JavascriptelkelkView Answer on Stackoverflow