I need to prevent click of the browser back button. When user clicks on browser back button from desktop or mobile we need to stay on same page. I tried different solutions from internet (some of them are working for Firefox). One of the code that is working on Firefox only:
window.history.pushState(null, "", window.location.href);
window.onpopstate = function () {
window.history.pushState(null, "", window.location.href);
};
On chrome or safari or edge browser when we do external click on page then only above code will work and user will be prevented to click on the back button. Please help me for this issue
CodePudding user response:
It is generally not recommended to disable the browser's back button, as this can be confusing and frustrating for users. Instead, you should consider alternative ways of handling navigation within your application, such as using client-side routing or using the history.pushState() method to update the URL and change the page content without reloading the page.
That being said, if you still want to disable the back button, one option you can try is to use the window.onbeforeunload event to show a prompt whenever the user tries to leave the page. This will not completely prevent the user from navigating away from the page, but it will at least give them a warning and give them the option to stay on the page.
Here's an example of how you could use the window.onbeforeunload event to show a prompt when the user tries to leave the page:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page?";
};
Keep in mind that this approach may not work in all browsers, and it may not be effective at completely preventing the user from navigating away from the page.
CodePudding user response:
visit this link there you can find your solution... :) Happy Coding... :)