Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 319
Banana Code Avatar asked May 17 '16 08:05

Banana Code


People also ask

Does history back trigger Popstate?

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history.

Which event is fired when the history of the browser window?

The popstate event of the Window interface is fired when the active history entry changes. If the history entry being activated was created by a call to history. pushState() or was affected by a call to history. replaceState() , the popstate event's state property contains a copy of the history entry's state object.

What is pushState and replaceState?

replaceState() will change the URL in the browser (ie. pressing the back button won't take you back) pushState() will change the URL, and keep the old one in the browser history (ie. pressing the back button will take you back)


1 Answers

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>
like image 109
anusreemn Avatar answered Sep 20 '22 06:09

anusreemn