Skip to content

Web Tip: Blocking the Back Button

If you are developing web apps, you’ve likely run into this before. You are navigating your Xojo web app and you use the browser’s back button to return to the previous page of the app. But rather than taking you to the previous page, you get a message that the app lost connection to the sever.  This is even more common on a mobile device where we tend to use the back gesture to return to the previous page.

In order to avoid this you can use the following code snippet to block the back button and keep the current webpage displayed. It will reload the current webpage, so you probably will want to combine this technique with the use of cookies to keep track of the data you save and retrieve for the user.

The first step to implement this is adding a value to the HashTag property for the Session object in the Opening Event Handler of the webpage. For example:

Session.HashTag = "#"

Next, select the App object and type the following snippet of code under the HTML Header section in the associated Inspector Panel:

<script>
window.addEventListener('popstate', function(event) {
	history.pushState(null, null, window.location.pathname);
	history.pushState(null, null, window.location.pathname);
	}, false);
</script>

That’s all! You can also watch this simple “how to” in a 2 minute video (in English)  (video in Spanish). Questions? Ask me on Twitter @XojoES or on the Xojo Forum.