Robotium Test to Extract Cookies from WebView - android

My Sign Up Process produces cookies in a WebView, not in native code. All my tests depend on the cookies retrieved from the Webview so I need a way to extract data from a webview inside a Robotium test. How can this be done? Here is my WebView fragment:
public class MyWebViewFragment extends Fragment {
private CookieManager cookieManager;
#ViewById
WebView myWebView;
#AfterViews
void theAfterViews() {
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
CookieSyncManager.createInstance(getActivity());
cookieManager = CookieManager.getInstance();
myWebView.loadUrl(theURL);
myWebView.setWebViewClient(new WebViewClient()
{
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if ((url != null) && (url.equals(theURL)))
{
String theCookies = cookieManager.getCookie(url);
// ######## I need to pull these Cookies out here in the Robotium test. How do I use Solo etc to do this?
}
}
}
}
I need to know how to write a Robotium test that will at the right point pull out the values of the Cookies and save it for the rest of the tests to use. I need to get thiw working or none of my other tests will run. Thanks

The simple answer as i think you may know having seen your other questions is to get hold of the fragment and then ask the fragment for the value. Potentially you might consider mocking this functionality out for your tests or allow your tests a method to be able to set the cookies for itself etc (not sure if this is feasible for your case or not.)

Related

android WebView cookies expires when exit app

As the CookieSyncManager.getInstance().sync(); is deprecated Itried to maintain cookies forever in my application using new command
flush() :
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
CookieManager.getInstance().setAcceptCookie(true);
CookieManager.getInstance().acceptCookie();
CookieManager.getInstance().acceptThirdPartyCookies(webview);
CookieManager.getInstance().flush();
}
// and more settings for webview
}
But every time I open the app it seems that previous cookies were expired. Do those options help preserving cookies? And Should I put them in onPageFinished?
Besides I have to say that the cookies are working fine on the target website and are set to live for 100 days. Also minSdkVersion is 21 and targetSdkVersion is 29.
Using PersistentCookieJar — persistent and good for encapsulating the Cookies within the App itself. please checkthis
every time APP plan to launch Webview, the cookies will need to be copied from the PersistentCookieJar to the CookieManager.

Webview doesn't clear history, cache etc

I have an android application that has native framework and content itself is presented in web format and in webview. The meaning of the application is to allow users to use the device using predefined
services that may require autentication.
How ever when I try to clean up the webview caches after user has completed his/her tasks the webview will remember everything and all e.g. login credentials are in place, history remains etc.
I have tried the following to do the clean up without any success, what I am missing in this ?
(wvfo if the overlay fragment in which the webview is that each service is using)
wvfo.getWebView().clearCache(true);
wvfo.getWebView().clearFormData();
wvfo.getWebView().clearHistory();
wvfo.getWebView().clearMatches();
// wvfo.getWebView().setWebViewClient(new WebViewClient());
// wvfo.loadUrl("javascript:document.open();document.close();");
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
wvfo.destroyWebview();
Any ideas what is wrong with this and why the history doesn't get cleared ?
Thanks in advance
Yes, You have to delete webview default DB also. Check the below code.
static void clearWebViewAllCache(Context context, WebView webView) {
try {
AgentWebConfig.removeAllCookies(null);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
context.deleteDatabase("webviewCache.db");
context.deleteDatabase("webview.db");
webView.clearCache(true);
webView.clearHistory();
webView.clearFormData();
clearCacheFolder(new File(AgentWebConfig.getCachePath(context)), 0);
} catch (Exception ignore) {
//ignore.printStackTrace();
if (AgentWebConfig.DEBUG) {
ignore.printStackTrace();
}
}
}
I hope, this will help you.
Happy codding...

Android Persistent Cookie Store with HTTPUrlConnection

I searched a lot now for the persistence of Cookies but cant find a good solution.
I use HTTPUrlConnection to authenticate against a server and I get Cookies back. I retrieve them in CookieManager and can load them into a new connection. Now I want to persistent that Cookies, perhaps the whole Cookiemanager Object. I found a solution, that you can persist the Cookies with specifying a CookieStore by creating the CookieManager.
I found only old solutions (2-3 years) that say you have to build your own persistent CookieStore, since a persistent CookieStore is not implemented in the SDK? Is this up to date? Is there already a persistent CookieStore implemented in the SDK or does I have to persist the Cookies by myself with SharedPreferences? Or does anybody has a better solution to persist Cookies nowadays?
Best Regards,
This seems to be answered in some other palces, I didn't try it but you can get a detailed explain in this link:
http://blog.winfieldpeterson.com/2013/01/17/cookies-in-hybrid-android-apps/
public class YourApplication extends Application {
public void onCreate() {
super.onCreate();
//Setup Cookie Manager and Persistence to disk
CookieSyncManager.createInstance(this);
CookieManager.getInstance().setAcceptCookie(true);
}
}
public class MainActivity extends BaseActivity {
public void onResume() {
CookieSyncManager.getInstance().stopSync();
}
public void onPause() {
CookieSyncManager.getInstance().sync();
}
}
API21 deprecates CookieSyncManager, now to ensure that cookies are written to disk use:
CookieManager.flush()

Is default behavior of Android's WebView changed to open internally all links?

I noticed that with the last update of Google System WebView, all the links in my WebViews are opened in the view itself. But according to the documentation from google:
public boolean shouldOverrideUrlLoading (WebView view, String url)
Added in API level 1
Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url. This method is not called for requests using the POST "method".
I did not provide custom WebViewClient.
NOTE: The device that I noticed the problem was HTC One with the latest Google System WebView from June 8, 2015
I can reproduce the findings. Android System WebView 43.0.2357.121 exhibits the behavior that you describe, while the version I had on before upgrading to it did not.
I have filed a bug report on this and now need to do more testing and warn the world.
Thanks for pointing this out!
UPDATE
Here is a blog post that I wrote on this subject. Quoting myself from it:
My recommendation at the moment is:
Always attach a WebViewClient to your WebView
Always implement shouldOverrideUrlLoading() on the WebViewClient
Always return true to indicate that you are handling the event
Always do what your app needs to have done, whether that is loading
the URL into the WebView or launching a browser on the URL (rather
than returning false and relying on stock behavior)
Something like this static inner class appears to do the trick —
create an instance and pass it to setWebViewClient() on your
WebView:
private static class URLHandler extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (shouldKeepInWebView(url)) {
view.loadUrl(url);
}
else {
Intent i=new Intent(Intent.ACTION_VIEW, Uri.parse(url))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(i);
}
return(true);
}
private boolean shouldKeepInWebView(String url) {
return(true); // or false, or use regex, or whatever
}
}
(where you would put your business logic in shouldKeepInWebView() to
determine whether or not a given URL should stay in the WebView
or launch a browser)
Seems to me this issue was resolved in 44.0.240.54.

How to handle a binary data response in WebView

My activity has an intent filter to pick up a specific url and open it in a WebView control, which brings user to an auth page (user name/password). After authentication is done user will get a binary stream response (file). Is there a way to handle that response and read data from the stream?
I tried to setup a custom WebViewClient with the overridden shouldOverrideUrlLoading method, but app doesn't get there.
#Override
mMyWebView.setWebViewClient(new CustomWebClient());
mMyWebView.loadUrl("http://xxx.xx.x.xx:xxxx/getCert");
...
private class CustomWebClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading (WebView view, String urlConection)
{
// break point here doesn't stop debugger
return true;
}
}
neither works
mMyWebView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading (WebView view, String urlConection)
....
});
Server reacts on requests in the same way from both My app and build-in browser. Build-in browser starts to download file received in response, but my app doesn't do anything and doesn't hit breakpoint inside CustomWebClient.
This is a separate app just to test this piece nothing else interferes with it. INTERNET & WRITE_EXTERNAL_STORAGE permissions added.
EDIT: Mar 8
Gave up. Will go with httpClient.
Did you implement this method of WebView?
void setDownloadListener(DownloadListener listener)
Register the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead.

Categories

Resources