Close active panel on navigating backwards

Close active panel on navigating backwards

The code below is used to close active panel when navigating backwards in history (browser's back button, data-rel="back", $.mobile.back(), etc.) and cancels navigation. The code works as it should except for one issue that it clears "forward" history.

  1. var newUrl;
  2. $(window).on("hashchange", function (e) {
  3.     newUrl = e.originalEvent.newURL;
  4. }).on("popstate", function (e) {
  5.     var direction = e.historyState.direction == "back" ? true : false,
  6.         activePanel = $(".ui-panel-open").length > 0 ? true : false,
  7.         url = newUrl,
  8.         title = document.title;
  9.     if (direction && activePanel) {
  10.         $(".ui-panel-open").panel("close");
  11.         $(".ui-header .ui-btn-active").removeClass("ui-btn-active");
  12.         $.mobile.pageContainer.pagecontainer("change", url, {
  13.             allowSamePageTransition: true
  14.         });
  15.         window.history.replaceState({}, title, url);
  16.         return false;
  17.     }
  18. });

  19. $(document).on("pagebeforechange", function (e, data) {
  20.     if (data.options && data.options.allowSamePageTransition) {
  21.         data.options.transition = "none";
  22.     } else {
  23.         data.options.transition = $.mobile.defaultPageTransition;
  24.     }
  25. });


To reproduce the problem:

  1. Navigate to "Page 2"
  2. Navigate to "Page 3"
  3. Navigate back to "Page 2"
  4. Notice browser's "forward" button
  5. On "Page2", open "panel" and then hit browser's back button or "Back" button in header

You will notice that browser's "forward" button is disabled.

How to maintain "forward" in browser's history?

Update:

Here is another version where I update history.state through .replaceState(). It has no effect whatsoever except for maintaining browser's history.