Managing Browser Back/Forward when you use JqueryMobile


I am using JQueryMobile for building website that works on Mobile, tablet, and desktop computers.

As my application is an Ajax application. I wanted to control the browser URL in order to enable browser back/forward button in my Ajax single-page application.

The solution is really easy, whenever you want to change the location call

location.hash = “456”;

This will update browser URL as following:

       http://mysite.com/myfolder/index.html#456

Of course passing your own application specific hash

Whenever the user click back or forward, you need to handle the following event:

window.onhashchange = function () {


        //Use location.hash and update your application display as you need


};

Until now everything is perfect. But if you are using JQM (JqueryMobile) you will face trouble.
JQM uses hash to manage the transition between multiple pages and dialogues. While doing so, it update the localtion.hash.

The best workaround for this is to let JQM leave location.history alone. This can be easily done by:

$.mobile.changePage(“#my-page”, {changeHash: false});

As you see, the second parameter is an object with many option, what we need here is:

      changeHash: false

And viola, now you have full control of your location hash.

What is a downside is that it will impose burden on you to control all page/dialogue changes yourself. you can not simply use:

        href=”#my_other_page”

Because JQM will simply change it but will update browser hash.

Links:
https://api.jquerymobile.com/jQuery.mobile.changePage/

From ahm507.blogspot.com