B4A Library [lib] CookieManager

Here's a small library that enables you to manage any cookies used by a WebView in your application.

CookieManager
Version: 1.16
  • CookieManager
    Methods:
    • GetAcceptCookies As Boolean
      Returns True if cookies will be accepted by your application.
    • GetAllowFileSchemeCookies As Boolean
      Gets whether the application's WebView instances send and accept cookies for file scheme URLs.
    • GetCookie (Url As String) As String
      Returns the cookie for the given Url in the format: NAME=VALUE [; NAME=VALUE]
      If no cookie exists for the Url then a null value will be returned.
    • HasCookies As Boolean
      Returns True if any cookies are stored for your application.
    • RemoveAllCookies
      Removes all cookies stored for your application.
    • RemoveExpiredCookies
      Removes all expired cookies stored for your application.
    • RemoveSessionCookies
      Removes all session cookies stored for your application.
    • SetAcceptCookies (Accept As Boolean)
      Set whether cookies will be accepted for your application.
    • SetAcceptFileSchemeCookies (Accept As Boolean)
      Sets whether the application's WebView instances should send and accept cookies for file scheme URLs.
    • SetCookie (Url As String, Value As String)
      Sets the cookie for the Url to the Value.
  • CookieSyncManager
    Methods:
    • CreateInstance
      Creates an instance of the CookieSyncManager.
      The CookieSyncManager is used to synchronise 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 with a 5 minute interval.
    • ResetSync
      Resets the CookieSyncManager timer.
    • StartSync
      Requests the CookieSyncManager to start synchronisation.
      Typically called in Activity_Resume.
    • StopSync
      Requests the CookieSyncManager to stop synchronisation.
      Typically called in Activity_Pause.
    • Sync
      Forces the CookieSyncManager to synchronise now.
      This method is asynchronous, there is no guarantee it will synchronise immediately.

For an example of usage take a look here: http://www.b4x.com/forum/basic4andr...-load-url-username-password-2.html#post131419, and here: http://www.b4x.com/forum/basic4andr...-load-url-username-password-2.html#post134391.

Martin.
 

Attachments

  • CookieManager_v_1.16.zip
    17.4 KB · Views: 1,315
Last edited:

barx

Well-Known Member
Licensed User
Longtime User
A nice addition, Good job WarWound
 

cstangor

Member
Licensed User
Longtime User
My App creates an Application has stopped unexpectedly error on cm.Removeallcookies. Any idea why?

Thanks
 

cstangor

Member
Licensed User
Longtime User
OK, right. here's the error:

java.lang.IllegalStateException: CookieSyncManager::createInstance() needs to be called before CookieSyncManager::getInstance()

my code is simply:

<code>
Dim cm As CookieManager
cm.RemoveAllCookies
</code>

Thanks
 

warwound

Expert
Licensed User
Longtime User
Hi.

Can you let me know what version of Android you're gettiing this exception with?
I'll then do some tests and hopefully update the library as required.

Martin.
 

warwound

Expert
Licensed User
Longtime User
CookieManager updated to version 1.15

Hmmmm i'm not sure what's going on here.
The RemoveAlCookies method does not use CookieSyncManager, it simple executes:

B4X:
CookieManager.getInstance().removeAllCookie();

Anyway i did update the library last November, testing something for another forum member, you can find the related post here: http://www.b4x.com/forum/basic4andr...-load-url-username-password-2.html#post134391.

We found no use for the update so i just left it unpublished, however i'll now make that update available. I have changed that CookieSyncManager Initialize method to CreateInstance as that is the name of the method it wraps.
The CookieSyncManager methods are:

CookieSyncManager
Methods:
  • CreateInstance
    Creates an instance of the CookieSyncManager.
    The CookieSyncManager is used to synchronise 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 with a 5 minute interval.
  • ResetSync
    Resets the CookieSyncManager timer.
  • StartSync
    Requests the CookieSyncManager to start synchronisation.
    Typically called in Activity_Resume.
  • StopSync
    Requests the CookieSyncManager to stop synchronisation.
    Typically called in Activity_Pause.
  • Sync
    Forces the CookieSyncManager to synchronise now.
    This method is asynchronous, there is no guarantee it will synchronise immediately.

And some demo code:

B4X:
Sub Process_Globals
   
End Sub

Sub Globals
   Dim CookieManager1 As CookieManager
   Dim CookieSyncManager1 As CookieSyncManager
   Dim WebView1 As WebView
End Sub

Sub Activity_Create(FirstTime As Boolean)
   CookieSyncManager1.CreateInstance
   
   WebView1.Initialize("WebView1")
   Activity.AddView(WebView1, 0, 0, 100%x, 100%y)
   '   call SetAcceptCookie after WebView has been initialized
   CookieManager1.SetAcceptCookies(True)
   
   '   load a webpage that requires a login
   Dim Url As String
   Url="http://www.geograph.org.uk/profile/6526"   '   change this to your login page
   WebView1.LoadUrl(Url)
   
End Sub

Sub Activity_Resume
   CookieSyncManager1.StartSync   '   not really required for this test example
End Sub

Sub Activity_Pause (UserClosed As Boolean)
   CookieSyncManager1.StopSync   '   not really required for this test example
End Sub

Sub WebView1_PageFinished (Url As String)
   '   force the CookieSyncManager to synchronise
   CookieSyncManager1.Sync
   CookieSyncManager1.ResetSync
   
   Log("WebView1_PageFinished Url = "&Url)
   Log("Cookies: "&CookieManager1.GetCookie(Url))
   
   If CookieManager1.HasCookies Then
      Log("Cookies: "&CookieManager1.GetCookie(Url))
   Else
      Log("No cookies found")
   End If
End Sub

I'm not that sure what exactly all of this can do except give you a chance to maintain cookies between restarts of your application.

Can you try the new version - call the CookieSyncManager method CreateInstance before using any CookieManager methods - and report back if it works ok or not?

Thanks.

Martin.
 

cstangor

Member
Licensed User
Longtime User
No Cookies Found

So I am using the cookiemanager library example.

I enter my website: umd.instructure.com

I enter my credentials and respond "yes" to "do you want the browser to remember this information"

I'm logged on fine, and can log on again without having to reenter the credentials.

But I always get "no cookies found." in the page_finished event.

What am I missing?

Thanks
 

cstangor

Member
Licensed User
Longtime User
OK, sorry to be dense but I have a basic question (new to cookies)

Cookies seem to have a URL, a name, and a value.

How does setcookies allow all 3 to be specified?

Thanks
 

warwound

Expert
Licensed User
Longtime User
You use the SetCookie (Url As String, Value As String) method, the String passed as the Value parameter is formatted:

B4X:
name1=value1

' or if there are more than one name/values separate them with a semi-colon

name1=value1;name2=value;name3=value3

' example

SetCookie("http://mydomain.com", "username=martin;password=fubar")

Martin.
 

cstangor

Member
Licensed User
Longtime User
OK, so I'm doing:

1. Run the logon procedure
2. Use getCookies to get the cookie string
3. Uninstall the program
4. Rerun, using setCookies with the string returned at (2)

But that doesn't create the behavior that would have occurred if I had tried the logon procedure a second time after (2).

Does it matter where the setCookies is placed?

Thanks again so much.
 

warwound

Expert
Licensed User
Longtime User
First thing to check is how long the session cookie is valid for.
Different websites set different periods for which the logged in session cookie is valid - some have no period and the cookie lasts forever.

So if you uninstall and reinstall then try to logon using the old cookie there is a chance that the cookie will have expired.
If that's not the problem then i'm not sure what's going wrong.

Is the name of the cookie (exactly) correct?

Do you have access to the webserver you're trying to login to?
If so could you modify the login page to dump the cookie sent by your app to a file and then look at the file to see exactly what cookie is being sent?

Is the login page located on a normal HTTP url or a secure HTTPS url?

Martin.
 

warwound

Expert
Licensed User
Longtime User
Can you test the attached update and let me know if it works correctly?

  • GetAllowFileSchemeCookies As Boolean
    Gets whether the application's WebView instances send and accept cookies for file scheme URLs.
  • SetAcceptFileSchemeCookies (Accept As Boolean)
    Sets whether the application's WebView instances should send and accept cookies for file scheme URLs.

Martin.
 
Last edited:

Magneto

New Member
Licensed User
Longtime User
Hi warwound,
thanks for the very fast answer. The new version works wonderfull.
Thanks!
 

3fazeac

Member
Licensed User
Longtime User
I'm having trouble with FileScheme Cookies on an older Android platform:
Are FileScheme Cookies supported on Android 2.2?

I installed Version 1.16 of the library and ran the CookieManagerExample.b4a.
The target is a Android 2.2.1 physical phone and also an Android 2.2, platform 2.2, API level 8 virtual device (as seen in the Android Virtual Device Manager)

The out-of-the-box code works fine with no errors, however, if I adjust the code in the Activity_Create to read

B4X:
    Activity.AddView(WebView1, 0, 0, 100%x, 100%y)
    '    call SetAcceptCookie after WebView has been initialized

    Dim FSCookies As Boolean 
    FSCookies = CookieManager1.GetAllowFileSchemeCookies
  
    CookieManager1.SetAcceptCookies(True)

Then the example program fails with this error
java.lang.NoSuchMethodError: android.webkit.CookieManager.allowFileSchemeCookies at uk.co.martinpearman.b4a.httpcookiemanager.B4ACookieManager.GetAllowFileSchemeCookies(B4ACookieManager.java:23)

The error only occurs when the GetAllowFileSchemeCookies method is called: for example, if I call CookieManager1.GetAllowFileSchemeCookies in Activity_Pause then the error occurs only when I quit the activity.

The FileScheme Cookies work just fine on my Android 4.4.1 device.
 
Top