didimoo / AndroidLocalStorage

How to implement correctly a LocalStorage feature in Android Webview
Apache License 2.0
85 stars 28 forks source link

AndroidLocalStorage

LocalStorage is partially broken in Android webviews : Local storage is supposed to be a persistent storage available accros all tabs (or windows) of a browser. On Android, LocalStorage works well but only in the current webview. Multiple webviews of the same app can't share the same data with LocalStorage. That is sad !

JavaScriptInterface to the rescue !

This sample Android app shows you how you can fix the webview LocalStorage with a JavaScriptInterface.

What we do here is :

How to use it in your own project ?

This last step is as simple as this :

<script type="text/javascript">
        try{
            //we replace default localStorage with our Android Database one
            window.localStorage=LocalStorage;    
        }catch(e){
            //LocalStorage class was not found. be sure to add it to the webview
                    alert("LocalStorage ERROR : can't find android class LocalStorage. switching to raw localStorage")              
              }
    //then use your localStorage as usual
    localStorage.setItem('foo','it works')
    alert(localStorage.getItem('foo'))

</script>

Play with this example project to see how it works.