I have only 2 routes
/
and
/about
when I am on URL
localhost:8080 -> it renders my home page
localhost:8080/about -> it renders about page
If user open home page and click on about button and go to about page , not if user will click back button of browser I want just alert "user click on browsers button"
I have tried many internet solution but none of that works
tried this but doest not worked .
$(window).on('popstate', function(event) {
alert("You are going to back page. Can work that?");
});
2
Answers
you can use the url comparison.
popstate
is designed for a SPA, IOW: your SPA on page routing will do apushstate
.. You won’t get apopstate
from a none SPA app.Link -> https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent
Note: A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document.
Notice the bit that says ->
same document
, IOW: if your navigating to about without using pushstate, then it’s not the same document.A SPA works like this ->
Back button pressed
So you can use jQuery to do this, often what users do is intercept the
a
tag, usepreventDefault
and do 1,2 above.Note: beforeunload could be used, but be aware its synchronous and very bad UX, especially using alert. So if you can get push/popstate working you will find you can create much better UX for the user. eg. like been able to use the new HTML Dialog element -> https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog