iosweb-applicationsiphone-web-app

How can I create an iOS webapp that returns to the previous state after being inactive?


When I create an iOS webapp in HTML, I use following code:

<meta name="apple-mobile-web-app-capable" content="yes" />

So, after adding it as a Safari bookmark to the home screen of the iPhone and starting it, I noticed that once I go back to the home screen and re-open the app, the web app doesn't keep its previous state.

It doesn't start where I left of and opens the start page instead. Native apps don't do that.

How can I create an iOS webapp that returns to the previous state after being inactive?


Solution

  • You'll need to locally store the current status of the page every time it changes (in a cookie, LocalStorage, or IndexedDB), and read that value back when the app is opened.

    Web app frameworks probably have this built-in, but here's a rough and basic standalone example, using LocalStorage:

    function pageChange(href) {
        // called when a new page is requested by the user
        // (could be set to run whenever an 'a' element is clicked)
        localStorage.setItem('last_href', href);
        window.location.href = href;
    }
    
    function startUp() {
        // runs when the web app starts up
        var last_href = localStorage.getItem('last_href');
        if (typeof last_href == "string" && last_href.length) {
            // check that last_href is actually stored
            // or it won't work the first time the web app is launched
            window.location.href = last_href;
        }
    }