Search code examples
javascriptjavaandroidwebviewsavestate

How to save Login Information on WebView Application?


I am Working on an Android application that uses webView to load a web page. The webpage which I am using has a Login form I can log in using that form and do my stuff. The problem is when I close the app (exit it) and open the application I've to do Login again. How can I save the Login information such that when I open my app I don't have to do Login?

Is there any way to save all information before closing the Application?


Solution

  • You have to first register the JavaScriptInterface on your webview. JavaScriptInterFace can be a inner class as shown below. This class will have a function that you can call from html page( via javaScript ) and inside this function you can write code to change activity.

    Here is the working solution for you:

    public class JavascriptInterfaceActivity extends Activity {
        /** Called when the activity is first created. */
    
    
        WebView wv;
    
        JavaScriptInterface JSInterface;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            wv = (WebView)findViewById(R.id.webView1);
    
            wv.getSettings().setJavaScriptEnabled(true);
            // register class containing methods to be exposed to JavaScript
    
            JSInterface = new JavaScriptInterface(this);
            wv.addJavascriptInterface(JSInterface, "JSInterface"); 
    
           if(not_logged_in){
             wv.loadUrl("file:///android_asset/myPage.html");
           }
    
    
        }
    
    
        public class JavaScriptInterface {
            Context mContext;
    
            /** Instantiate the interface and set the context */
            JavaScriptInterface(Context c) {
                mContext = c;
            }
    
            @android.webkit.JavascriptInterface
            public void login_success()
            {
                // save login success.
            }
        }
    }
    

    Here is the html page

    <html>
    <head>
    <script type="text/javascript">
    function displaymessage()
    {
    JSInterface.login_success();
    }
    </script>
    </head>
    
    <body>
    <form>
    <input type="button" value="Click me!" onclick="displaymessage()" />
    </form>
    </body>
    </html>