0

In my jQuery Mobile multi-page application, is it possible to check if history.back() would be a page within the application?

I have a link on a subpage of the application that I would like to execute history.back() if that refers to a subpage within the application or just plainly link to the application main page otherwise.

I want to do something like

if(canGoBack) {$.mobile.back();} else {$.mobile.changePage('#main');}

Twilite
  • 873
  • 9
  • 22

1 Answers1

0

On the initial load of the app, store a flag in the history state object on document.ready:

$(function() {
    history.replaceState($.extend(history.state, {root:true}));
});

From then on, whenever we want to check if we can go back, just see if the flag we set is there in the current history state object. If it is, we are on the initial page and cannot go back:

function canGoBack() {
    return !(history.state && history.state.root);
}

HTML:

<a href="javascript:if(canGoBack) {$.mobile.back();} else $.mobile.changePage('#main');}">Back</a>
Twilite
  • 873
  • 9
  • 22