4

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?

MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89
FairyQueen
  • 2,283
  • 7
  • 37
  • 57
  • possible duplicate of [Creating a new Location object in javascript](http://stackoverflow.com/questions/3213531/creating-a-new-location-object-in-javascript) – Explosion Pills Mar 07 '13 at 22:29
  • `window.location` is an object, with handy dandy methods for grabbing the different bits. `document.referrer` on the other hand is a string, and so that'll need to be parsed manually. – ultranaut Mar 07 '13 at 22:33

3 Answers3

13

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='';
kennebec
  • 102,654
  • 32
  • 106
  • 127
6

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('/');
Aaron Powell
  • 24,927
  • 18
  • 98
  • 150
  • 1
    `http://example.com/://foobar` is a valid URI accoriding to RFC 3986. Your `parts` could be missing something... – rodneyrehm Mar 07 '13 at 22:39
1

If you want the convenience and can afford the weight, have a look at URI.js or one of the suggested URL parsers. If you don't need anything fancy, <a>s href decomposition will do the job just fine.

Community
  • 1
  • 1
rodneyrehm
  • 13,442
  • 1
  • 40
  • 56