How can I get the url of the previous page when triggering the popstate event?
Asked Answered
O

2

21

Here's a simple example of pushState and popstate event:

<button id="example_btn">Click me</button>

<script>
$("#example_btn").click(function(){
            history.pushState( 
                {
                    'url' : "example.htm"
                }, null, "example.htm");
});
$(window).bind('popstate', function (event) {
    if (event.originalEvent.state) {
        console.log(event.originalEvent.state.url);
    }
});
</script>

When triggering the popstate event, it shows the url of the current page.

My question is:

How can I get the url of the previous page when triggering the popstate event in this case?


P.S. I have tried document.referrer but it didn't show anything.

Oscitant answered 17/5, 2016 at 8:13 Comment(0)
I
4

Please try keeping the previousUrl in a variable and listening to it.

<button id="example_btn">Click me</button>

<script>
var previousUrl = null;
$("#example_btn").on('click', function(){
           previousUrl = location.href;
             history.pushState( 
                {
                    'url' : "example.htm"
                }, null, "example.htm");
});
window.onpopstate = function (event) {
   console.log('Previous url was : ', previousUrl); 
};
</script>
Intestine answered 20/4, 2017 at 14:32 Comment(1)
And what if the user navigates multiple states back in the hierarchy?Beatup
S
0

UPDATED & TESTED & WORKING


Extended History Object

This is my source you can see full resource from https://gist.github.com/HasanDelibas/12050fc59d675181ea973d21f882081a


This library contains:

  • history.states -> get state list
  • history.stateIndex -> current state index
  • "historyChange" event -> detect history change (from,to,side="back"|"forward")
  • Important! state must be object at history.pushState( **state**, ...)
(function(){
  let stateSymbol = "__state__index__";
  history.stateIndex =-1;
  history.states=[];
  let pushState = history.pushState;
  function add(data,title,url){
    if(data==null) data={};
    if(typeof data!="object") data={data:data};
    data[stateSymbol] = (history.stateIndex+1);
    history.states.splice(history.stateIndex+1,0,[data,title,url])
    history.states.splice(history.stateIndex+2)
    history.stateIndex++;
  }
  history.pushState =function(data,title,url=null){
    add(data,title,url);
    pushState.bind(history)(data,title,url);
  }
  addEventListener("popstate",function(e){
    var eventObject= {};
    var newStateIndex =  e.state!=null ? e.state[stateSymbol] : -1;
    eventObject.from = history.states[history.stateIndex];
    eventObject.to   = newStateIndex>-1 ? history.states[newStateIndex] : null;
    eventObject.side = history.stateIndex>newStateIndex ? "back" : "forward"; 
    if( newStateIndex > -1 && !(newStateIndex in history.states) ){
      add(history.state,"",window.location.href);
    }
    window.dispatchEvent(new CustomEvent("historyChange", {detail: eventObject} ))
    history.stateIndex = e.state!=null ? e.state[stateSymbol] : -1;
  });
})();

Now you can get all states with history.states object, and detect history change with addEventListener("popstate",function(e))

Using

/**
  * @param e.detail.from [data,title,url]
  * @param e.detail.to   [data,title,url]
  * @param e.detail.side "back" | "forward"
  */
addEventListener("historyChange",function(e){
  var from = e.detail.from; // [ data , title , url ]
  var to   = e.detail.to;   // [ data , title , url ]
  var side = e.detail.side; // "back" | "forward"
  console.log( `You changed history. Side is ${e.detail.side}.\nFrom:${e.detail.from[2]}\nTo:${e.detail.to[2]}`)
})


history.pushState("1", "DENEME-TEST" ,"?1");
history.pushState("2", "DENEME-TEST" ,"?2");
// list of history states
console.log( history.states )
/*
[
  [ {...} ,  "DENEME-TEST" ,"?1" ]
  [ {...} ,  "DENEME-TEST" ,"?2" ]
]
*/
// get history current state index
console.log( history.stateIndex )
/*
1
*/

Stibine answered 9/2, 2018 at 23:22 Comment(2)
This shows the current URL, but not the URL before the popstate.Quadrinomial
The good idea here is to extend the history object to be able to explore all back and forward states. The old URL is simply the URL of the previous state.Research

© 2022 - 2024 — McMap. All rights reserved.