7

How can do the same function in javascript that is document.location.pathname - except with the referrer? so something like document.referrer.pathname?

Thanks.

Matt
  • 5,005
  • 10
  • 32
  • 39

3 Answers3

6

No, you can only extract needed part manually:

document.referrer.replace(/^[^:]+:\/\/[^/]+/, '').replace(/#.*/, '')
RReverser
  • 1,940
  • 14
  • 15
  • This is not exactly correct as the `document.location.pathname` will strip the parameters of the URL as well. You need to use: `document.referrer.replace(/^[^:]+:\/\/[^/]+/, '').replace(/#.*/, '').replace(/\?.*/, '')` to also remove the parameters of the referrer. – clement g Mar 20 '15 at 10:05
5

You can extract the pathname from the document.referrer and parse it with new URL() with the following code

const url = new URL(document.referrer)
url.pathname

Be sure to polyfill URL for IE 10 and below, easily done with https://polyfill.io/v3/polyfill.js?features=URL

kylewelsby
  • 4,031
  • 2
  • 29
  • 35
  • `/* Disable minification (remove '.min' from URL path) for more info */` is the error when clicking your link and `/* No polyfills found for current settings */` is the error when removing `min`. Perhaps you meant to post something else? – Abandoned Cart Jul 13 '19 at 11:16
  • Thanks @AbandonedCart for letting me know, I have changed the Polyfill.io link – kylewelsby Jul 13 '19 at 15:15
  • Note that the URL constructor will throw when not given a valid URL (like the empty string when no referrer is set). Depending on the use-case, providing a base URL might be a good way to prevent this: `new URL(document.referrer, "http://example.com/")` – Wilco Verhoef Jan 08 '22 at 01:04
0

you can use document.referrer to obtain the URL of the referring document. Is that what you mean??

Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86