I managed to pass the variables differently.
My problem was that at any time, when I switched to another application, when I came to webapp, web browsing kept rebooting. I guess because of the following line in my onCreate()
method: myWebView.loadUrl(url);
I had the idea of ββpassing these state variables to a URL, but as you know, this is not yet possible. I did to save the state of some variables using onSaveInstanceState(Bundle outState) {...}
and restore them using onRestoreInstanceState(Bundle savedInstanceState){...}
.
In the onCreate method, after setting up myWebView, I did the following:
myWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String urlString) { Log.i("onPageFinished", "loadVariables("+newURL+")"); if(newURL!="") myWebView.loadUrl("javascript:loadVariables("+"\""+newURL+"\")"); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); jsInterface = new JSInterface(this,myWebView); myWebView.addJavascriptInterface(jsInterface, "Android"); if (savedInstanceState != null) { // retrieve saved variables and build a new URL newURL = "www.yoururl.com"; newURL +="?var1=" + savedInstanceState.getInt("key1"); newURL +="?var2=" + savedInstanceState.getInt("key2"); Log.i("myWebApp","NEW URL = " + newURL); } myWebView.loadUrl("www.yoururl.com");
So what happens is that first I load the page and then pass the variables when the page ends for loading. In the javascript function, loadVariables
looks like this:
function loadVariables(urlString){ // if it is not the default URL if(urlString!="www.yoururl.com") { console.log("loadVariables: " + urlString); // parse the URL using a javascript url parser (here I use purl.js) var source = $.url(urlString).attr('source'); var query = $.url(urlString).attr('query'); console.log("URL SOURCE = "+source + " URL QUERY = "+query); //do something with the variables } }
source share