Show alert on Browser Back Button event on react js
Answer a question
I have to show an alert on the browser back event on React js. I have tried using the addEventListener
but I'm not sure where to place the code in the React page. Should I place in any life-cycle hooks or in the render? I'm not sure. Please help me out.
Answers
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.
更多推荐
所有评论(0)