0

I am building a single page application and I am looking to imitate the routing achieved by the Google Play Music page. When the user loads up my page I would like them to receive all of the HTML needed and then dynamically load data as they navigate the page.

To maintain a users navigation history I need the page to have a way to manage the back button functionality and URL routing. What can I use to handle new the URL entry when there is only one page served to the user?

If you are familiar with the Google Music page you will see that a combination of the URL and loading spinners are used. This tells the user that the page is loading but they never actually leave the original page.

David Price
  • 170
  • 1
  • 16

1 Answers1

0

According to this answer, you can accomplish this using the HTML5 history API. The things you need to pay attention to on that page are the pushState() method and the popstate event.

Using this answer as a template, some code that you may write to accomplish this might look as follows:

window.onload = function() {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function(event) {
            // you should deal with the back button in here
            history.pushState("state object or string", "Title", "/some-page");
        };
    }
    else {
        // for browsers that don't support history
        var ignoreHashChange = true;
        window.onhashchange = function() {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
            }
            else {
                ignoreHashChange = false;
            }
        };
    }
}

This will prevent the user from pressing the back button, instead sending them to domain/hello in modern browsers. For your use case you might want to use event.state to keep track of where you are and whether the previous page was from your app or not.

Community
  • 1
  • 1
cjm
  • 814
  • 1
  • 11
  • 26