Show alert on Browser Back Button event on react js
Finally, I solved by myself. I have given the explanation with the code below:
First, add the below code in either componentDidUpdate
or componentWillMount
hook:
window.history.pushState({name: "browserBack"}, "on browser back click", window.location.href);
window.history.pushState({name: "browserBack"}, "on browser back click", window.location.href);
The reason why I'm pushing it twice is that the state will be updated only if it's pushed twice. Here's the Ref. The above code will push the current page's URL in the history on the page load.
So when the back browser button is clicked the same page will be reloaded again since the history has been manipulated by the pushState
method.
Then add the following code above the pushState
method:
window.addEventListener('popstate', (event) => {
if (event.state) {
//do your code here
}
}, false);
Now, when the Browser back button is clicked the above even listener will be called and since we updated the state
which pushState
method, the if
will be true and you can do whatever you wanted to do in it.
You can try this,
window.addEventListener('popstate', (event) => {
alert("You message");
});
You can place it in componentWillMount()
or componentDidMount()
as per your need.
Ref
check out this link How to Detect Browser Back Button event - Cross Browser
The key points there:
document.onmouseover = function() {
//User's mouse is inside the page.
window.innerDocClick = true;
}
document.onmouseleave = function() {
//User's mouse has left the page.
window.innerDocClick = false;
}
window.onhashchange = function() {
if (window.innerDocClick) {
//Your own in-page mechanism triggered the hash change
} else {
//Browser back button was clicked
}
}
This prevents back space from being used to navigate back
$(function(){
/*
* this swallows backspace keys on any non-input element.
* stops backspace -> back
*/
var rx = /INPUT|SELECT|TEXTAREA/i;
$(document).bind("keydown keypress", function(e){
if( e.which == 8 ){ // 8 == backspace
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
}
});
});
if you use react hooks you can use useEffect hooks to do it in following step
import React, { useState, useEffect } from "react";
const [finishStatus, setfinishStatus] = useState(false);
const onBackButtonEvent = (e) => {
e.preventDefault();
if (!finishStatus) {
if (window.confirm("Do you want to go back ?")) {
setfinishStatus(true)
// your logic
props.history.push("/");
} else {
window.history.pushState(null, null, window.location.pathname);
setfinishStatus(false)
}
}
}
useEffect(() => {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', onBackButtonEvent);
return () => {
window.removeEventListener('popstate', onBackButtonEvent);
};
}, []);