I'm trying to simply set and retrieve a cookie inside a webview in android. I have tried numerous cookie manager scripts to try and get this to work. I have JavaScript enabled.
When running the application on a Samsung S3 and a Samsung Galaxy Tab 10.1 cookies don't appear to set at all (android 4.1). However, when running the software on a Samsung Galaxy ace, HTC Desire Z and in the android emulators, the cookies are set and read perfectly fine.
When working, the webview returns the string as expected, when not working, the output is simply "null"; the cookie has not value/is not set.
My specific case also uses sliding Navigation class, which is an extension of Actionbar Sherlock.
I'd really appreciate any help, I've been struggling with this for several weeks now.
Thank you.
HTML:
<html>
<head>
<title>
</title>
<script>
function createCookie(name, value)
{
var day = (1 * 24 * 60 * 60 * 1000);
var date = new Date();
date.setTime(date.getTime() + (20 * 365 * day));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
</script>
</head>
<body>
<h1 class="">
<script type="text/javascript">
createCookie("test", "If this is working, it returns this string. If this is not working, it returns null.");
document.write("test: " + readCookie("test"));
</script>
</body>
</html>
Java Code:
public class MainActivity extends SherlockActivity implements ISideNavigationCallback {
public static final String EXTRA_TITLE = "com.devspark.sidenavigation.sample.extra.MTGOBJECT";
public static final String EXTRA_RESOURCE_ID = "com.devspark.sidenavigation.sample.extra.RESOURCE_ID";
public static final String EXTRA_MODE = "com.devspark.sidenavigation.sample.extra.MODE";
public static String WebLoaded = "0";
public static String page = "signup.php";
private ImageView icon;
private SideNavigationView sideNavigationView;
private WebView engine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
icon = (ImageView) findViewById(android.R.id.icon);
sideNavigationView = (SideNavigationView) findViewById(R.id.side_navigation_view);
sideNavigationView.setMenuItems(R.menu.side_navigation_menu);
sideNavigationView.setMenuClickCallback(this);
if (getIntent().hasExtra(EXTRA_TITLE)) {
String title = getIntent().getStringExtra(EXTRA_TITLE);
int resId = getIntent().getIntExtra(EXTRA_RESOURCE_ID, 0);
setTitle(title);
icon.setImageResource(resId);
sideNavigationView.setMode(getIntent().getIntExtra(EXTRA_MODE, 0) == 0 ? Mode.LEFT : Mode.RIGHT);
}
//test
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String domain = "localhost";
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(domain, "name=value");
cookieManager.setCookie(domain, "path=/");
cookieManager.setCookie(domain, "HttpOnly");
//enable cookies
CookieManager.getInstance().setAcceptCookie(true);
//navigates web engine, including on nav click
engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl("file:///android_asset/" + page);
//enable JavaScript support - disabled by default for some weird reason
engine.getSettings().setJavaScriptEnabled(true);
engine.setWebViewClient(new WebViewClient());
//disables text selection
engine.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
return true;
}
});
}
#Override
public void onPause()
{
super.onPause();
engine.getSettings().setJavaScriptEnabled(false);
}
#Override
public void onResume()
{
super.onResume();
engine.getSettings().setJavaScriptEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
sideNavigationView.toggleMenu();
break;
case R.id.mode_left:
item.setChecked(true);
sideNavigationView.setMode(Mode.LEFT);
break;
case R.id.mode_right:
item.setChecked(true);
sideNavigationView.setMode(Mode.RIGHT);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onSideNavigationItemClick(int itemId) {
switch (itemId) {
case R.id.side_navigation_menu_item1:
invokeActivity(getString(R.string.title1), R.drawable.ic_android1);
page = "index.html";
break;
case R.id.side_navigation_menu_item2:
invokeActivity(getString(R.string.title2), R.drawable.ic_android2);
page = "test.html";
break;
case R.id.side_navigation_menu_item3:
invokeActivity(getString(R.string.title3), R.drawable.ic_android3);
break;
case R.id.side_navigation_menu_item4:
invokeActivity(getString(R.string.title4), R.drawable.ic_android4);
break;
case R.id.side_navigation_menu_item5:
invokeActivity(getString(R.string.title5), R.drawable.ic_android5);
break;
default:
return;
}
finish();
}
After over a month of research I've concluded that setting a cookie in android versions greater than 2.3 is not possible in a webview where the file is on the localhost (read directly from the assets folder).
I went through many alternatives to to using cookie storage, including using HTML's localstorage. The whole issue here, I am led to believe, is security. If I were to create a cookie or localstorage on the localhost, then other apps could access that storage, thus is a major security threat.
My ultimate problem was trying to bridge the webview with two-way communication with java and also having a place to store data during the process. My solution was to take advantage of the JavascriptInterface
The idea is as follows:
Parse data to function in javascript
Javascript calls a special javascript function e.g. "setData(myDataName, myData)"
Java has a function which listens to this, and will take arguments set by javscript, and can also return values to javascript.
Once data is parsed to Java, java stores this in a series of files in assets.
When javascript function "getData(myDataName)" is called, the data is returned by the same kind of method by Java.
I found this very useful: Android JavascriptInterface Documentation, Handling JavascriptInterface in Android 2.3
The only major 'hang-ups' come with a what I found was a fairly serious bug in Android 2.3 (fixed in 3.0) which effectively broke the JavascriptInterface. The second link above describes the best workaround I have found.
Here is an example of how to get the two-way communication working (it's very messy, but it works):
Custom webinterface class:
public class webViewInterface {
//#JavascriptInterface //for SDK 12+
public String showToast(String myText) {
Toast.makeText(context, myText, Toast.LENGTH_LONG).show();
return myText;
}
}
Main class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
engine = (WebView) findViewById(R.id.web_engine);
context = this;
WebSettings webSettings = engine.getSettings();
webSettings.setJavaScriptEnabled(true);
engine.setWebViewClient(new WebViewClient());
engine.loadUrl("file:///android_asset/" + page);
boolean javascriptInterfaceBroken = false;
try {
if (Build.VERSION.RELEASE.startsWith("2.3")) {
javascriptInterfaceBroken = true;
}
} catch (Exception e) {
// Ignore, and assume user javascript interface is working correctly.
}
// Add javascript interface only if it's not broken
// #TODO: write the workaround for < 2.3 devices
if (!javascriptInterfaceBroken) {
engine.addJavascriptInterface(new webViewInterface(), "MainActivityInterface");
}
//disables text selection
engine.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
return true;
}
});
}
HTML:
<html>
<head>
</head>
<body>
<input type="button" value="Say hello" onClick="showAndroidToast();" />
<script type="text/javascript">
function showAndroidToast() {
document.write(MainActivityInterface.showToast("eureka!"));
}
</script>
</body>
</html>
I encountered the same limitations. I am loading local html files from the assets fodler. On a 2.2 emulator, cookies are stored and can be retrieved via JavaScript. However, testing on my 4.1 device, cookies set by a local page won't persist.
Based on #kirgy's and #user3220983's suggestions, I made it using the Javascript interface.
webview.addJavascriptInterface(new JavaScriptInterface(this), "Android");
public class JavaScriptInterface {
...
#JavascriptInterface
public void setCookie(String name, String value) {
Editor editor = activity.settings.edit();
editor.putString(name, value);
editor.commit();
}
#JavascriptInterface
public String getCookie(String name) {
return activity.settings.getString(name, "");
}
#JavascriptInterface
public void deleteCookie(String name) {
Editor editor = activity.settings.edit();
editor.remove(name);
editor.commit();
}
Note: these functions does not provide full cookie functionality (expiration, path), I am posting this as an idea of a good starting point.
You need to set the cookie's expiration date or else the cookie won't be be accepted.
Something like this:
document.setCookie = function(sName,sValue)
{
var oDate = new Date();
oDate.setYear(oDate.getFullYear()+1);
var sCookie = sName.escape() + '=' + escape(sValue) + ';expires=' + oDate.toGMTString() + ';path=/';
document.cookie= sCookie;
}
Good luck, hope it works!
I encountered the same issue as kirgy. I was trying to use cookies (with javascript) in a Droid webview that displayed local content. It would not store the data. The same code worked perfectly if run from a remote url in the same webview though. Enabling cookies in java (with the Android CookieManger) had no effect.
Fortunately, I used custom javascript functions to encapsulate all my cookie needs in the local web app. Using the webview javascript interface, when running on the droid I just managed my cookies in a virtual manner by handling it up in the java.
For my needs, I only required session storage, so just put the cookies data in a java HashMap. I didn't worry about expiration dates or long term storage. If you need your "virtual cookies" to implement those details, it shouldn't be too difficult to figure out once the data is going to and from java via the js interface.
Related
I am attempting to load another site's iframe into my android app via webview. I am able to properly load other websites but when I load a stream from sportsbay.org which provides you with an iframe embed code snippet, the stream goes black and it prints "Sandboxing is not allowed". I have gone through several other questions to find an answer to this. My android project is as follows.
The specific url that I am passing in as video_url is https://sportsbay.org/embed/45629/1/btn-big-ten-network-live.html. The iframe snippet that sportsbay provides is <iframe allow='encrypted-media' width='640' height='360' marginwidth='0' marginheight='0' scrolling='no' frameborder='0' allowfullscreen='yes' src='//sportsbay.org/embed/45629/1/btn-big-ten-network-live.html'></iframe>. This url loads two urls 1) https://lowend.xyz/stream/45629.html which is the actual stream and moments later loads 2) https://sportsbay.org/live-streams to redirect you to the home page of sportsbay. I have code in MyWebViewClient that prevents the main sportsbay page from loading which would interrupt the stream I want to play (THIS is where I get the sandboxing message). I have tried replacing loadUrl with loadData and other variations that pass in the iframe html string along with the mimeType but what I have currently is the closest I have come to loading the stream (others don't get far enough to post the sandboxing message).
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Bring Linear layout into view.
setContentView(R.layout.webview);
// Grab current intent & pull out video url.
Intent i = getIntent();
String video_url = i.getStringExtra("video_url");
// Removes app name banner at top. Allows for orientation changes without reload.
getSupportActionBar().hide();
// Creates webview object.
WebView web = findViewById(R.id.webView);
// Configure settings for webview.
WebSettings webSettings = web.getSettings();
// Allows use of the phones file storage.
webSettings.setDomStorageEnabled(true);
// Sets encoding standard for urls.
webSettings.setDefaultTextEncodingName("utf-8");
// Able to zoom.
webSettings.setSupportZoom(true);
// Needed for websites to load javascript enabled content (most videos/streams).
webSettings.setJavaScriptEnabled(true);
// Attached webview to java class MyWebViewClient that vets the incoming urls before loading.
// Blocks Ads / viruses / popups.
// Also keeps url from launch in a browser.
web.setWebViewClient(new MyWebViewClient());
// Checks if channel is sourced from sportsbay.org.
if(video_url.contains("sportsbay.org"))
{
// Changes the browser user agent since chrome user agent returns 403 Forbidden message.
webSettings.setUserAgentString("Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion");
}
web.loadUrl(video_url);
}
public class MyWebViewClient extends WebViewClient {
public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
return true;
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final Uri uri = Uri.parse(url);
return handleUri(uri);
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return handleUri(uri);
}
private boolean handleUri(final Uri uri) {
Log.i(TAG, "Uri =" + uri);
final String host = uri.getHost();
final String scheme = uri.getScheme();
// Check requested URL to known good
if (host.equals("s1-tv.blogspot.com") ||
host.equals("reddit-tv-streams.blogspot.com") ||
host.equals("newdmn.icu") ||
host.equals("lowend.xyz"))
{
// Returning false means that you are going to load this url in the webView itself
return false;
} else {
// Do not load the requested URL
return true;
}
}
}
Great news! I figured it out. The sandboxing message was not because of the server incorrectly interacting with my app, it was because my app did not have permission to use the file storage outside of the android application (the app sandbox). This was fixed with:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
which needs to be placed in the Android Manifest.xml in the permissions area (under the top package).
I have implemented Paytm payment system and everything is working fine with a web intent on top of my intent, money is deducted from customer's acc and its getting added on my account but after the transaction gets complete it gets stuck on a white page saying 'Redirect to app' which i believe i should write the code to redirect back to my app but i don't know how to do that because i couldn't find a onTransactionSucess() event or anything similar to that i also tried onTransactionResponse but still no response. I checked all the paytm documentation and tried contacting paytm support but couldn't find a way.
Hope you have added 'CALLBACK_URL' which is requied to verify the checksum.
As mentioned in paytm documentation
CALLBACK_URL - Security parameter to avoid tampering. Generated using
server side checksum utility provided by Paytm. Merchant has to ensure
that this always gets generated on server. Utilities to generate
checksumhash is available here .
Hope this should do the magic.
I hope you have added this variable to your code -
PaytmPGService service;
If you are using it than you can get all the payment related methods like this :
service.startPaymentTransaction(this, true,
true, new PaytmPaymentTransactionCallback() {
#Override
public void onTransactionResponse(Bundle inResponse) {
System.out.println("===== onTransactionResponse " + inResponse.toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Objects.equals(inResponse.getString("STATUS"), "TXN_SUCCESS")) {
// Payment Success
} else if (!inResponse.getBoolean("STATUS")) {
// Payment Failed
}
}
}
#Override
public void networkNotAvailable() {
// network error
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
// AuthenticationFailed
}
#Override
public void someUIErrorOccurred(String inErrorMessage) {
// UI Error
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) {
// Web page loading error
}
#Override
public void onBackPressedCancelTransaction() {
// on cancelling transaction
}
#Override
public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
// maybe same as onBackPressedCancelTransaction()
}
});
I hope this will help you.
Change default callbackurl to suppose, 'http://yourdomain (ip address if checking on localhost)/pgResponse.php';.
Add following code to pgResponse.php
<?php
session_start();
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");
$paytmChecksum = "";
$paramList = array();
$isValidChecksum = "FALSE";
$paramList = $_POST;
$return_array= $_POST;
$checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);//generate new checksum
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : ""; //Sent by Paytm pg
//Verify all parameters received from Paytm pg to your application. Like MID received from paytm pg is same as your applicationís MID, TXN_AMOUNT and ORDER_ID are same as what was sent by you to Paytm PG for initiating transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.
$return_array["IS_CHECKSUM_VALID"] = $isValidChecksum ? "Y" : "N";
unset($return_array["CHECKSUMHASH"]);
$mid = $_POST['MID'];
$orderid = $_POST['ORDERID'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://securegw-stage.paytm.in/order/status?JsonData={"MID":"'.$mid.'","ORDERID":"'.$orderid.'","CHECKSUMHASH":"'.$checkSum.'"}',
CURLOPT_USERAGENT => 'Make Request'
));
$resp = curl_exec($curl);
$status= json_decode($resp)->STATUS;
//do something in your database
$encoded_json = htmlentities(json_encode($return_array));
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-I">
<title>Paytm</title>
<script type="text/javascript">
function response(){
return document.getElementById('response').value;
}
</script>
</head>
<body>
Redirecting back to the app.....</br>
<form name="frm" method="post">
<input type="hidden" id="response" name="responseField" value='<?php echo $encoded_json?>'>
</form>
</body>
</html>
In android studio:
public void onTransactionResponse(Bundle inResponse) {
Log.d("Create Response", inResponse.toString());
String response = inResponse.getString("RESPMSG");
if (response.equals("Txn Successful.")) {
Toast.makeText(Bag.this,"Payment done",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Bag.this,response,Toast.LENGTH_LONG).show();
}
}
I have created an app that will load links from my server into the webview. However, I have also written an intent to open the link in the user's browser so they can download the file. I want the link to change a bit while it loads in the browser.
I.e:
This is the link : https://www.example/v/file
My app should change "v" to "f" and load in the user's browser.
Like this: https://www.example/f/file
My code:
private void initWebDowload(String s){
webView.loadUrl(s);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(s));
startActivity(i);
}
Kinda complicated but you need to attach a custom WebViewClient to your WebView so you can change the URL loading behaviour.
Just to give an example:
webView.setWebViewClient(new CustomWebViewClient());
private class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// right here you are given the chance to change the [url] ^
view.loadUrl(url.replace("/v/file", "/f/file")); // replace v with f
return true;
}
}
}
I'm trying to get the favicon of the loaded page after using
WebView webView = new WebView(getActivity());
webView.loadUrl("http://" + url);
I'm attaching the asynchronous WebViewClient to the WebView to get the favicon after it loads
webView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
String linkTitle = view.getTitle();
Bitmap favicon = view.getFavicon();
onLinkUrlFinished(url, linkTitle);
}
});
The favicon getting back is always null, even for websites such as google/facebook that has favicons for sure.
Another thread says to use WebIconDatabase but it's deprecated:
Display the Android WebView's favicon
The API on android site refers to WebViewClient.onReceivedIcon which doesnt even exist.http://developer.android.com/reference/android/webkit/WebView.html#getFavicon%28%29
What's going on here?
In order to use onReceiveIcon(), you should use setWebChromeClient.
This is what I do and it's working for me.
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
webImage.setImageBitmap(icon);
}
});
WebIconDatabase is deprecated as of API 19. According to the comments in the code:
#deprecated This class is only required when running on devices up to
{#link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}
So unless you don't want to support API 18 and below, you should still be using WebIconDatabase:
WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());
And then, regardless what API you want to support, you need to specify in a custom WebChromeClient:
public class MyCustomWebChromeClient extends WebChromeClient {
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
// do whatever with the arguments passed in
}
}
Remember to register your custom WebChromeClient with your WebView:
mWebView.setWebChromeClient(new MyCustomWebChromeClient());
The key is to open the WebIconDatabase so WebView has somewhere to put the icons, and override WebChromeClient.onReceivedIcon. For additional information, see this StackOverflow article.
I know its an old thread but, for those facing problems getting favicon using webview client.
Kotlin:
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
tabTitle.text = view?.title // read website title
loadImg(view) // method to load the favicon
}
private fun loadImg (view: WebView?){
// u can directly use tabImage.setBitmap instead of assigning tabImg as val
val tabImg: ImageView = findViewById(R.id.tabImage)
// creating handler object to delay the associated thread a little bit after onPageFinished is called.
val handler = Handler()
val runnable = Runnable {
if(view?.favicon != null) {
tabImg.setImageResource(0) //remove the default image
tabImg.setImageBitmap(view?.favicon) // set the favicon
}
}
handler.postDelayed(runnable, 200) // delay time 200 ms
}
It worked for me, hope it helps new readers, plz up vote if it helps u, so that u can help others!
Best regards
So in the end I didn't end up using the deprecated API, instead I found out that if you put /favicon.ico after the domain, it'll give you the ico file, which I used in the end to fetch the image. The Uri API will have a getHost() method that will give you the host without having to manually parse it
String faviconUrl = Uri.parse(url).getHost() + "/favicon.ico";
For google for example the icon url will be www.google.com/favicon.ico
I am working on an Android Application that opens an HTML page in a webview within the app. The HTML page is stored in the assets folder and I call it by means of
loadUrl("file:///android_asset/a.html");
Now, the page is such that it accepts parameters from the URL (javascript). I need to know how do we pass URL parameters to this html file that is stored inside the assets folder. Writing them like this:
loadUrl("file:///android_asset/a.html?q=2&w=3");
doesn't work.
Is there any other way?
Riya
If your HTML page handles the parameters via javascript (and i can't think of any other way it can handle them), you can call a javascript function in your code with the parameters after the page is loaded, and pass parameters to it.
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() { setParameters(2,3)})()");
}
});
webview.loadUrl("file:///android_asset/a.html");
I tried the method suggested by shaish and many others for passing url parameters to an 'asset folder' url. It seems that this is a well known bug for android 3 and 4 (http://code.google.com/p/android/issues/detail?id=17535). Simply calling webview.loadUrl("file:///android_asset/a.html?q=2&w=3") works on a blackberry 10 simulator.
A similar explanation like shaish but adapted to my own case:
My problem was that anytime I switched to another app, when coming to the webapp, the webview kept reloading. I guess that's because of the following line in my onCreate() method: myWebView.loadUrl(url); I had the idea to pass these state variables in the url, but as you know it is not possible yet.
What I did was to save the state of some variables using onSaveInstanceState(Bundle outState) {...} and restore them with onRestoreInstanceState(Bundle savedInstanceState){...}.
In 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 it happens is that first I load the page and then I pass the variables when the page finished to load.
In javascript loadVariables function 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
}
}