Reputation: 6707
I have two customized functions that handle back and forward page. I need to call them when user clicks on the browser back/forward buttons too.
window.onpopstate = function() {
if ( /* back button clicked */ ){
showPreviousPage():
} else {
showNextPage();
}
})
How can I implement that condition? In other word, how can I detect browser back button is clicked?
Upvotes: 5
Views: 5977
Reputation: 1
//react js detect browser pop forward or back
window.addEventListener("popstate", (e) => {
var loc = document.location;
if (event && event.state && event.state.usr && event.state.usr.pop) {
var stateloc = event.state.usr.pop;
} else {
var stateloc = "forward";
}
if (event && event.state && event.state.usr && event.state.usr.pop) {
var stateloc = event.state.usr.pop;
} else {
var stateloc = "forward";
}
// window.history.pushState(null, null, null);
if (stateloc == "forward") {
history.forward();
} else if (stateloc == "back") {
history.back();
console.log(
// "location: " +
// document.location +
// ", state: " +
// JSON.stringify(event.state)
// );
Upvotes: -1