How can I get the URL of the previous page when the popstate event fires?

Here is a simple example of a pushState and popstate :

 <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 the popstate event is popstate , the URL of the current page is displayed.

My question is:

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

PS I tried document.referrer but didn't show anything.

+5
source share
2 answers

Please try to save the previous Url in a variable and listen 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> 
0
source

with PopStateEvent. I use

 window.history.pushState( {} , {} , url ); 

other ways I'm not sure.

Below I tested his work. Hope helpful.

 window.addEventListener('popstate', function(e){ console.log(e.srcElement.location); /* You get other location types( 'http://....' or '/index.html' */ var previusUrl = e.srcElement.location.href; console.log( previusUrl ); // with http://............ }); 
0
source

All Articles