I am trying to prevent browser back button for a specific page only in react redux project. Lets say I have four pages.
http://localhost:3000/abc/#/page1
,
http://localhost:3000/abc/#/page2
,
http://localhost:3000/abc/#/page3
and http://localhost:3000/abc/#/page4
etc
For all the pages user can go back and forth except page4
. Once user has visited page3
and clicked the next button he can not go back.
I have tried multiple options but none of them is working as expected. Below code is working as per my expectation but its blocking browser back for all the pages.
componentDidMount() {
window.history.pushState(null, document.title, window.location.href);
window.addEventListener('popstate', function (event){
window.history.pushState(null, document.title, window.location.href);
});
}
The back button in a browser can be disabled in a variety of ways. In this tutorial, we’ll show you how to use JavaScript to disable the back button. You may place the code on the first or previous page so that the browser will redirect to the same page if a user attempts to go back to the prior page.
This is one JavaScript trick out of many, which is not advisable to use in websites, though very useful in terms of security and integrity of online data. Restricting or Disabling the Browser back button can be very annoying for users who might wish to go back to the previous page from the existing page.
In our example, we will use two simple HTML pages. The first page will call the second page using a link and in the process using JavaScript, we will restrict the user from getting back to the first page (from the second page) using the Browser back button.
The above JavaScript function in the first page uses the history of the browser and forces it to navigate forward instead of going to the previous page. Therefore, every time the user clicks the back button or hits the backspace key, it will result in the Browser navigating or pushing the user forward and showing the same page (the page 2).
If you are using react-router
or react-router-dom
then you can conditionally disable back button for browser based on current route path.
You can use withRouter
Higher order component from react-router
or react-router-dom
, if your component is not a direct route component.
componentDidMount() {
const { match } = this.props;
if(match.url === "/abc/#/page4"){
window.history.pushState(null, document.title, window.location.href);
window.addEventListener('popstate', function (event){
window.history.pushState(null, document.title, window.location.href);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With