Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the parts of a url using document.referrer?

Tags:

javascript

I need to use document.referrer to get the previous URL I also need to be able to get the parts of the URL like:

window.location.protocol
window.location.host
window.location.pathname

but I can't figure out how to do it with document.referrer. Anyone got any ideas?

like image 897
FairyQueen Avatar asked Nov 30 '22 04:11

FairyQueen


2 Answers

You can create an a element with the referrer as its url.

a elements (with hrefs) can act like location objects

var a=document.createElement('a');
a.href=document.referrer;
alert([a.protocol,a.host,a.pathname].join('\n'));
a='';
like image 191
kennebec Avatar answered Dec 10 '22 01:12

kennebec


There's no equivalent to window.location with regards to document.referrer so your only option will be to break down the string itself. You could write a regex to do that or rely on a series of string splits:

var parts = document.referrer.split('://')[1].split('/');
var protocol = document.referrer.split('://')[0];
var host = parts[0];
var pathName = parts.slice(1).join('/');
like image 30
Aaron Powell Avatar answered Dec 10 '22 03:12

Aaron Powell