0

I need grab the path of a referring URL, which can be served from many different hostnames which can be under HTTP or HTTPS and even have port numbers.

Can someone give me an example of how to run some code only if the referring URL contains a specific string such as path and a file name or just a certain path without a file extension?

Zoolander
  • 2,293
  • 5
  • 27
  • 37
  • You'd use `document.referrer`. See also: http://stackoverflow.com/questions/1098877/javascript-redirect-based-on-referrer – David Wolever Oct 10 '11 at 19:28
  • Thanks for the tip, however I'm unsure of how to only grab the part after the hostname which could contain .com, .net, or even a port number. So I only want to compare against whatever is after the first "/" after the hostname. – Zoolander Oct 10 '11 at 19:29

1 Answers1

4

Well, you can start with something simple:

var parts = document.referrer.replace(/^https?:\/\//, '').split('/');
parts.shift();
var path = parts.join('/');
if (path.indexOf('filename') > -1) {
    // code here
}

And if you need more flexibility see this library: http://blog.stevenlevithan.com/archives/parseuri

deviousdodo
  • 9,177
  • 2
  • 29
  • 34
  • In addition to having multiple hostnames, the referring page can be under HTTP or HTTPS protocols. Can you please update your example to work under either protocol? Also, I only need to grrab the referrer in this one place, so using a library would be overkill. – Zoolander Oct 10 '11 at 19:38
  • I've updated my replace to use a regex to handle both http and https. – deviousdodo Oct 10 '11 at 19:45