Search code examples
javascriptjqueryhtmlcordovabrowser-history

Back button (history) for Dynamic Document Object Model (DOM)


I'm making a little web app for be used with Cordova/Phonegap, so I need solutions that can be implemented in any WebView mostly Android and iOS but also some BlackBerry OS 10...

I change dynamically the DOM with JavaScript, the problem arises when I try to return to the "previous page", I have used several things, such as:

if (typeof (navigator.app) !== "undefined")
{
    navigator.app.backHistory();
}
else
{
    window.history.back();
}

This solution works for the first "pages" they are changed with the hash, but at some point I will not change over the hash, but only I change the DOM, then by clicking on the BackButton it is returning far behind.

Another thing is that I tried cloning the "previous page" with jquery clone (); but with this, I can only one step back once, I need something to keep everything (the history) in memory.

what do you suggest I do? Is there a plugin that do not use strictly HTML5? (as the older WebVies Android and iOS do not support certain functions).

Thanks for reading and please forgive my bad english.


Solution

  • Using jQuery's clone() and pushing the result into an array maybe a solution you can use. As the user 'navigates' your app, you capture the specific DOM node which is the parent to your "page", and remains static throughout the app.

     <html>
      <head>
      <title>Your App</title> 
      <script></script>
      </head>
      <body>
        <header>Your header here</header>
        <div id='container'>
              <-- the content you want to save in history here  -->
        </div>
        <footer>Your footer here</footer>
    

    The using a simple script like this:

      var navHistory = []
    
      function appHistory(){
         var cloned = $('#container').clone();
         navHistory.push(cloned);
     }
    

    Whenever a user 'navigates' in your app, you can invoke the appHistory function, copying and pushing the relevant DOM elements into the navHistory array.

    To retrieve the "page" contents, simple access the relevant array entry and remove/replace the current children of the parent container:

     function navBackOne(){
         //assuming you write the contents of the last page only when you
         //navigate away from it...
         var i = navHistory.length - 1;
         $('#container').children().remove()
         $(navHistory[i]).appendTo('#container')
         navHistory.pop();  
     }