11

I'm using pushStates in my ajax-app to navigate from one "page" to another. Now, I'd like to see from what page I was coming from. But document.referrer always returns "". Or, when I open my app from another page (where it is linked), I got the URL from that other page.

Shouldn't these lines...

history.pushState({}, "Some title", "/some/valid/url/1");

history.pushState({}, "Some title", "/some/valid/url/2");

...produce a referrer like this:

http://somedomain.com/some/valid/url/1

?

Or in other words: Is there any way to set the document.referrer accordingly, or at least reset it to ""?

Note: I'm looking for solutions without caching the previous URL in some variable. I need something that really changes the document.referrer, because I cannot change the scripts that rely on it.

kraftwer1
  • 5,253
  • 10
  • 36
  • 54

1 Answers1

3

Short Answer: use window.location instead of history.pushState

Longer Answer:

document.referrer according to MDN: "The value is an empty string if the user navigated to the page directly (not through a link, but, for example, via a bookmark)"

Directly manipulating the history state will not be treated as following a link. You can simulate a link click by update window.location (MDN) which will also update the history automatically.

For example, load a tab with https://github.com/kanaka/mal/. Then type the following one line at a time (otherwise they are all run in a single javascript execution context and only the last location update applies)

console.log(history.length)     // 2
console.log(document.referrer)  // ""
window.location = "/kanaka/mal/tree/master/ada"
console.log(history.length)     // 3
console.log(document.referrer)  // "https://github.com/kanaka/mal"
window.location = "/kanaka/mal/tree/master/python"
console.log(history.length)     // 4
console.log(document.referrer)  // "https://github.com/kanaka/mal/tree/master/ada"
kanaka
  • 70,845
  • 23
  • 144
  • 140