I am using React. I want to warn the user when the user clicks on the back button.
What I had done was
handleWindowClose = (ev) => {
ev.preventD
EDIT
Looks like onbeforeunload
is what you want: check this related question, which contains a useful demo.
Also the MDN docs contain a useful example.
Assuming you've got some good reason for not wanting to use react-router
, I'll sketch the javascript way of doing this
It looks like you're capturing the wrong event. You want to grab any change of the url hash, so you should use onhashchange.
Example from the docs:
if ("onhashchange" in window) {
alert("The browser supports the hashchange event!");
}
function locationHashChanged() {
if (location.hash === "#somecoolfeature") {
somecoolfeature();
}
}
window.onhashchange = locationHashChanged;
However, I'd give react-router
a go, given that you're developing in React. In which case, browserHistory
would be your friend.
I had a similar issue and fixed that this way:
componentDidUpdate(){
window.onpopstate = (e) => {
// Tour code...
}
}
I having below problems when handling the back button in reactjs
to Solve problem 1 I did the following code
componentDidMount() {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', this.onBackButtonEvent);
}
to solve problem 2 I did below code,
onBackButtonEvent = (e) => {
e.preventDefault();
if (!this.isBackButtonClicked) {
if (window.confirm("Do you want to save your changes")) {
this.isBackButtonClicked = true;
// your custom logic to page transition,like react-router-dom history.push()
} else {
window.history.pushState(null, null, window.location.pathname);
this.isBackButtonClicked = false;
}
}
}
don't forget to add this.isBackButtonClicked = false; in constructor and unscubscribe the events.
componentWillUnmount = () => {
window.removeEventListener('popstate', this.onBackButtonEvent);
}
Try this code:
componentDidMount() {
window.addEventListener("popstate", this.onBackButtonEvent)
}
componentWillUnmount() {
window.removeEventListener("popstate", this.onBackButtonEvent)
}
onBackButtonEvent = () => {
window.history.forward()
}