How do I enable cookies in a webview?
I tried to use
CookieManager.getInstance().setAcceptCookie(true);
just before calling WebView.loadUrl() and it doesn't work as I get an HTML page error from a website saying cookies need to be enabled.
How does cookieManager know which webview to enable cookies?
Say if I had an activity with two webviews in the screen and I only wanted one of those webviews to enable cookies, how is that possible using a CookieManager?
I feel like I am missing something. I could not find a method like webView.setCookieManager or Cookiemanager.setWebView(webview).
You should consider that
CookieManager.getInstance().setAcceptCookie(true);
doesn't work from lollipop(API21) and above. You should check and use appropriate function for that case:
if (android.os.Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
} else {
CookieManager.getInstance().setAcceptCookie(true);
}
CookieManager.getInstance() is the CookieManager instance for your entire application.
Hence, you enable or disable cookies for all the webviews in your application.
Normally it should work if your webview is already initialized:
http://developer.android.com/reference/android/webkit/CookieManager.html#getInstance()
Maybe you call CookieManager.getInstance().setAcceptCookie(true); before you initialize your webview and this is the problem?
Related
I need to save user login credentials for WebView in Android.
I have tried this, but with no luck.
WebView mWebview = (WebView) v.findViewById(R.id.wv_spielplan);
if(BuildConfig.VERSION_CODE < 21){
CookieManager.getInstance().setAcceptCookie(true);
} else {
CookieManager.getInstance().setAcceptThirdPartyCookies(mWebview, true);
}
CookieSyncManager.createInstance(getActivity());
CookieSyncManager.getInstance().startSync();
If the webview displays internet content, you may want to deal with the data from server side. Online or if you are showing "off line" assets content, i.e., content packaged with your app, allow javascript and DOM to work and you will be able to set a cookie inside webview. Edit: have a look at this: https://stackoverflow.com/a/5409155/5885018 and Set a cookie to a webView in Android
first of all, can someone please explain how does CookieManager.getInstance() work? I don't really get how I can get the session from webview? Lets say if I have this
CookieSyncManager.createInstance(WebviewPage.this);
CookieManager cookieManager = CookieManager.getInstance();
Do I get the session from the class named WebviewPage? but what if I named my actual WebView to webview, how can cookieManager get the session of webview? not even talk about if I had two WebView, webview1 and webview2. How do I know which session that was stored in cookieManager??
My main question is...I have two activities and one webview in each activity. How can I get the session from Activity A and pass it to the webview in Activity B?
Thanks!!!
As far as I know, you don't need to set cookie for webview2.
webview2 will automatically use the cookies from webview1.
CookieManager seems to be a singleton, so when you call getInstance() you always get the same instance. So if webview 1 set some cookies on the CookieManager, or if you set it your self using set Cookie, all other webviews should get the same cookies as well.
I have an application on appspot that works fine through regular browser, however when used through Android WebView, it cannot set and read cookies. I am not trying to get cookies "outside" this web application BTW, once the URL is visited by WebView, all processing, ids, etc. can stay there, all I need is session management inside that application. First screen also loads fine, so I know WebView + server interactivity is not broken.
I looked at WebSettings class, there was no call like setEnableCookies.
I load url like this:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
webview.loadUrl([MY URL]);
}
..
}
Any ideas?
If you are using Android Lollipop i.e. SDK 21, then:
CookieManager.getInstance().setAcceptCookie(true);
won't work. You need to use:
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
I ran into same issue and the above line worked as a charm.
From the Android documentation:
The CookieSyncManager is used to synchronize the browser cookie
store between RAM and permanent storage. To get the best performance,
browser cookies are saved in RAM. A separate thread saves the cookies
between, driven by a timer.
To use the CookieSyncManager, the host application has to call the
following when the application starts:
CookieSyncManager.createInstance(context)
To set up for sync, the host application has to call
CookieSyncManager.getInstance().startSync()
in Activity.onResume(), and call
CookieSyncManager.getInstance().stopSync()
in Activity.onPause().
To get instant sync instead of waiting for the timer to trigger, the
host can call
CookieSyncManager.getInstance().sync()
The sync interval is 5 minutes, so you will want to force syncs
manually anyway, for instance in onPageFinished(WebView, String). Note
that even sync() happens asynchronously, so don't do it just as your
activity is shutting down.
Finally something like this should work:
// use cookies to remember a logged in status
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);
webview.loadUrl([MY URL]);
I figured out what's going on.
When I load a page through a server side action (a url visit), and view the html returned from that action inside a Webview, that first action/page runs inside that Webview. However, when you click on any link that are action commands in your web app, these actions start a new browser. That is why cookie info gets lost because the first cookie information you set for Webview is gone, we have a seperate program here.
You have to intercept clicks on Webview so that browsing never leaves the app, everything stays inside the same Webview.
WebView webview = new WebView(this);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url); //this is controversial - see comments and other answers
return true;
}
});
setContentView(webview);
webview.loadUrl([MY URL]);
This fixes the problem.
My problem is cookies are not working "within" the same session. –
Burak: I had the same problem. Enabling cookies fixed the issue.
CookieManager.getInstance().setAcceptCookie(true);
CookieManager.getInstance().setAcceptCookie(true); Normally it should work if your webview is already initialized
or try this:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
I'm trying to set some cookies on my WebView to open a browser with the same session that I have on my app.
I read a lot of answers but they don't work for me. The only solution I've found is in the loadUrl, hardcode the cookie data in extraHeaders, but as expected this only works for this requests, and doesn't maintain the session.
The code that I have is:
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.xxx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();
String cookie = cookieManager.getCookie("http://xx.xxx.example.com");
Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.xx.example.com");
getCookie() returns the correct data, but when I read the cookies from the server, those are empty. What is wrong? Please advise.
Thank you!!!
Solved!!!! the problem is with the webView, I dont know what happend, but If I create the
WebView webView = new WebView(Activity.this);
it works. If I read the webview from activity with findViewById() it doesn't work.
Also if you need to set a list of cookies that you received previously from a website.
All you have to do is use a for-loop to go through and set all of them . It helped me to solve the situation
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
...
cookieSyncManager.sync();
is the cause of problem. You should do like this:
CookieSyncManager.createInstance(mWebView.getContext());
...
CookieSyncManager.getInstance().sync();
And there will be no need to manually create WebView...
I have a native Android 2.1 application that hosts a web view. I load up a site that contains javascript that uses the LocalStorage feature. When the application is running localStorage works fine. When some users exit the application and restart it, all the values are gone. I'm not seeing this problem in my Motrola Droid or Sprint EVO, but there is a report of users in the field with this issue.
Does anyone know what I am missing? I'm setting the following flag to true.
settings.setDomStorageEnabled(true);
To make the local storage work for your own WebView in Android, you need to make sure the WebView is using the correct file, and the local storage is enabled like this:
String packageName = "com.dongshengcn.android";
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);
settings.setDatabasePath("/data/data/"+packageName+"/databases");
settings.setDomStorageEnabled(true);
Where "com.dongshengcn.android" should be replaced with your own android app pacakge name.
Just for complete the previous responses which did not allow to resolve the issue in my case.
I'm working with Android 4.1.1. My app is using local storage within a Webview and I was getting the same issue as in the original question: the local storage works fine until I kill the app. In this case, the data was lost.
By inspiring me from previous responses, and especially from #diyism, I was able to solve my issue with this:
String databasePath = this.getApplicationContext().getDir("databases", Context.MODE_PRIVATE).getPath();
settingsMenu.setDatabasePath(databasePath);
In fact, as written in the setDatabasePath() documentation: to function correctly, this method must be called with a path to which the application can write.
setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}
only need these two lines:
this.getSettings().setDomStorageEnabled(true); //enable to use "window.localStorage['my']='hello1'", in webview js on >= android 2.0
this.getSettings().setDatabasePath("/data/data/"+this.context.getPackageName()+"/databases/"); //if no set or wrong path, variables disappear on killed
// Confimed on android 2.1 emulator
// enable javascript localStorage
WebSettings webSettings = myWebView.getSettings();
webSettings.setDomStorageEnabled(true); // localStorage
// eg if your package
// package www.myapp.whatever;
// eg webSettings.setDatabasePath("/data/data/www.myapp.whatever/databases/");
webSettings.setDatabasePath("/data/data/packagename/databases/");
this works