History API: Javascript Pushstate, get previous URL

安稳与你 提交于 2019-11-28 04:34:30

问题


$(window).bind('statechange',function(){
     var State = History.getState(),
     url = State.url;
});

In the following function, url returns the current URL. What I'm looking for is, within that function, to get the previous URL, so for example, if I'm on /cars/ferrari and go to /cars/ford, url would return cars/ford, but I want to get /cars/ferrari.

How do I get the previous URL within a statechange event?


回答1:


$(window).bind('statechange',function(){
    // Prepare Variables
    var State = History.getState(),
        url = State.url,
        states = History.savedStates,
        prevUrlIndex = states.length - 2,
        prevUrl = states[prevUrlIndex].hash;
});

That seems to do the trick! prevUrl gives me the desired URL.




回答2:


All I would do is push the URL on to the state object so you can get it back again.

So this when you use pushState :

history.pushState(
  {'previous_url': document.location.href}, 
  document.title,
  "?some_query_string"
);

Then when you get the state it will have previous_url on it :)




回答3:


Try this:

alert(document.referrer);

Note:

The value is an empty string if the user navigated to the page directly (not through a link, but, for example, via a bookmark). Since this property returns only a string, it does not give you DOM access to the referring page.

See more here: https://developer.mozilla.org/en-US/docs/DOM/document.referrer?redirectlocale=en-US&redirectslug=document.referrer



来源:https://stackoverflow.com/questions/13298743/history-api-javascript-pushstate-get-previous-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!