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.
In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.
The history. pushState() method can be used to push a new entry into the browser's history—and as a result, update the displayed URL—without refreshing the page. It accepts three arguments: state , an object with some details about the URL or entry in the browser's history.
The big difference is, that while pushState will create a new entry in the browser's history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With