Introduction
While implementing a business application in a certain case the other day, it was implemented because it was implemented with the requirement that “Do not allow browser to return” Leave it to I checked a couple of ways to deal with this problem and I found about 2 patterns … was not implement the business applications in the projects that the other day, you leave on record since the implementation have gotten the requirement that “I want that you do not go back in the browser”.
I checked out a couple of patterns to find out how to handle this problem.
One way is to go back to the original page immediately when you go back to the history by pressing the back button.
But this is not good. Make sure the user’s requirements can not be returned by the browser in the first place.
The second way to achieve this is realistic.
It is a method of deleting the current history when transitioning the page.
We will introduce this method this time.
Let’s conclude by disabling the browser’s “Back” button. We just
history.pushState(null, null, null); $(window).on("popstate", function (event) { if (!event.originalEvent.state) { history.pushState(null, null, null); return; } });
paste this code into the JS we use on all pages.
Then I will explain what I am doing.
First of all, the history object in the window object below provides methods for manipulating the browser history.
This time, this method is used to clear the previous history immediately after page transition,
and the history object has a pushState method, which can be used to delete the history.
Pass the state object as the first argument of the pushState method, the title as the second argument, and the URL as the third argument.
This time, we do not want to leave the current history at the transition timing, so pass null for all the arguments and change it to an empty history.
history.pushState(null, null, null);
In the above, only the process at the time of the first access can be supported.
When the back button is pressed, the browser tries to keep history, so you have to delete it immediately.
Let’s define the popstate event using the on method to cope with this.
The popstate event is an event that fires when trying to manipulate the browser history. Fires when the browser’s Back or Forward button is pressed.
The passed event event object contains a property called originalEvent.
$(window).on("popstate", function (event) { if (!event.originalEvent.state) { history.pushState(null, null, null); return; } });
This has also prevented the process of leaving a history when you press the back button.
Summary
What did you think?
This can easily disable browser back and prevent it from returning.
Isn’t it particularly useful for sites that frequently change data in form submissions?
Discussion about this post