Browser Back Button and Single Page Apps

These are just my notes. When it comes to this issue, I am a complete noob. Reader beware.

I was working on webpage that displayed all sorts of view of a calendar (FullCalendar). I wanted to add a form for creating an event. Sending the user to a new page made it difficult to get the user back the calendar view after the form was completed. Using a pop-up made the form difficult to use on mobile. The best solution involved hiding and displaying parts of the DOM.

This worked great, with the exception of the non-intuitive behavior of the back button. From the user’s perspective, loading the form looks like a new page. Thus user might think that hitting the back button would take them back to the calendar. Instead the back button takes them back to the page before the calendar page.

It turns out this problem has been known for years, dating back to when single page applications started to become popular. In fact HTML5 has functionality that specifically addresses this issue. There is an old javascript app that addresses this.

But what I wanted was a simple solution that works on HTML5 and pre-HTML5. Here it is (mostly from http://blog.falafel.com/fixing-back-button-simple-spa-behavior-using-location-hash/):

    window.onhashchange = function (e) {
        if (window.location.hash === "#" || window.location.hash === "") {
            calendar_view.show();
            event_form_view.hide();
        } else if (window.location.hash === "#form") {
            calendar_view.hide();
            event_form_view.show();
        }
    };

I should also mention that I bound this function to the cancel button on my form.

<pre>var cancel_button_click = function(){
    window.location.replace("");
    return false;
};</pre>

I am sure there are some cases where this code does not work. But for me, it works on the latest versions of Chrome, Firefox, Safari both on Linux and IOS. It works on Chrome on my Android tablet.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s