Update document.referrer via history.pushState ()

I use pushStates in my ajax application to navigate from one page to another. Now I would like to see which page I came from. But document.referrer always returns "" . Or, when I open the application from another page (where it is connected), I got the URL from this other page.

Shouldn't these lines ...

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

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

... create a referrer as follows:

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

?

Or, in other words: is there a way to set document.referrer accordingly, or at least reset to "" ?

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

+7
html5 pushstate
source share
1 answer

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 went directly to the page (not through a link, but, for example, through a bookmark)"

Direct state management of history will not be treated as a link. You can simulate a click link to update window.location ( MDN ), which will also automatically update the history.

For example, download a tab using https://github.com/kanaka/mal/ . Then enter the next line at a time (otherwise they all run in the same javascript execution context and only the latest location update is applied).

 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" 
+1
source share

All Articles