Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

History API: Javascript Pushstate, get previous URL

$(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?

like image 875
HandiworkNYC.com Avatar asked Nov 08 '12 22:11

HandiworkNYC.com


2 Answers

$(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.

like image 136
HandiworkNYC.com Avatar answered Sep 21 '22 03:09

HandiworkNYC.com


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 :)

like image 27
user3468034 Avatar answered Sep 23 '22 03:09

user3468034