28

I am working with the Webbrowser control on a windows.form application written in C#. I would like to write a method for deleting the cookies from the Webbrowers control after it visits a certain site. Unfortunately, I don't know how to do that exactly and haven't found a lot of help on the internet.

If anyone has experience actually doing this, not just hypothetical because it might be trickier than it seems, I don't know.

int count = webBrowser2.Document.Cookie.Length;
webBrowser2.Document.Cookie.Remove(0,count);

I would just assume something like the above code would work but I guess it won't. Can anyone shed some light on this whole cookie thing?

Sam
  • 7,252
  • 16
  • 46
  • 65
Proximo
  • 6,235
  • 11
  • 49
  • 67
  • I'm curious. Would setting the object "webBrowser2" to a new instance of the WebBrowser control reset the cookies? – gehsekky May 26 '09 at 21:13
  • No, you physically have to delete them. It's just a matter of knowing the correct directory to look and catching access denied exceptions for files in use – Proximo Jun 26 '09 at 00:29
  • 1
    I know what a cookie is. I need to delete a specific cookie. – user Oct 23 '09 at 07:29
  • The HtmlDocument.Cookie documentation says that you can only set a single cookie at a time. – Jason Harrison Apr 13 '16 at 18:49

10 Answers10

25

If you have JavaScript enabled you can just use this code snippet to clear to clear the cookies for the site the webbrowser is currently on.

webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")

It's derived from this bookmarklet for clearing cookies.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jordan Milne
  • 448
  • 1
  • 6
  • 10
  • 2
    Just as a side note, if you need to be able to clear cookies for all sites, you're probably better off using something like the axWebBrowser COM object. .NET's built in WebBrowser control is pretty locked down. I only used this when switching to axWebBrowser wasn't an option and the browser only needed to be able to browse one site. – Jordan Milne Aug 10 '09 at 18:39
  • thank you sir .. i was looking for a code like this for ages .. thank thank – Saeed A Suleiman Jun 19 '15 at 14:31
  • 5
    Note: HttpOnly cookies are not available to javascript. – Jason Harrison Apr 13 '16 at 18:49
18

I modified the solution from here: http://mdb-blog.blogspot.ru/2013/02/c-winforms-webbrowser-clear-all-cookies.html

Actually, you don't need an unsafe code. Here is the helper class that works for me:

public static class WinInetHelper
{
    public static bool SupressCookiePersist()
    {
        // 3 = INTERNET_SUPPRESS_COOKIE_PERSIST 
        // 81 = INTERNET_OPTION_SUPPRESS_BEHAVIOR
        return SetOption(81, 3);
    }

    public static bool EndBrowserSession()
    {
        // 42 = INTERNET_OPTION_END_BROWSER_SESSION 
        return SetOption(42, null);
    }

    static bool SetOption(int settingCode, int? option)
    {
        IntPtr optionPtr = IntPtr.Zero;
        int size = 0;
        if (option.HasValue)
        {
            size = sizeof (int);
            optionPtr = Marshal.AllocCoTaskMem(size);
            Marshal.WriteInt32(optionPtr, option.Value);
        }

        bool success = InternetSetOption(0, settingCode, optionPtr, size);

        if (optionPtr != IntPtr.Zero) Marshal.Release(optionPtr);
        return success;
    }

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool InternetSetOption(
        int hInternet,
        int dwOption,
        IntPtr lpBuffer,
        int dwBufferLength
    );
}

You call SupressCookiePersist somewhere at the start of the process and EndBrowserSession to clear cookies when browser is closed as described here: Facebook multi account

Community
  • 1
  • 1
Sergey Belikov
  • 420
  • 3
  • 14
  • Worked perfectly for me too, ended hours of research why my ADFS server was always stuck on login to the same Claims Provider Trust, even after a logout. – zukanta Aug 01 '16 at 17:17
  • 1
    This somewhat works for me on Windows 10, in that subsequent usages of the browser do not have cookies, but when I restart the program and don't set INTERNET_SUPPRESS_COOKIE_PERSIST, old cookies show up again. So it doesn't seem to actually delete the cookies, as noted in mr.baby123's answer – dmi_ Aug 03 '18 at 19:08
  • According MSDN [Marshal.AllocCoTaskMem(size)](https://learn.microsoft.com/ru-ru/dotnet/api/system.runtime.interopservices.marshal.alloccotaskmem?view=net-5.0) should be released with [Marshal.FreeCoTaskMem(IntPtr)](https://learn.microsoft.com/ru-ru/dotnet/api/system.runtime.interopservices.marshal.freecotaskmem?view=net-5.0#System_Runtime_InteropServices_Marshal_FreeCoTaskMem_System_IntPtr_) . – no.Oby Sep 08 '21 at 18:58
10

I found a solution, for deleting all cookies. the example found on the url, deletes the cookies on application (process) startup.

http://mdb-blog.blogspot.com/2013/02/c-winforms-webbrowser-clear-all-cookies.html

The solution is using InternetSetOption Function to announce the WEBBROWSER to clear all its content.

int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;

bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
if (!success)
{
    MessageBox.Show("Something went wrong !>?");
}

Note, that clears the cookies for the specific PROCESS only as written on MSDN INTERNET_OPTION_SUPPRESS_BEHAVIOR:

A general purpose option that is used to suppress behaviors on a process-wide basis.

Sam
  • 7,252
  • 16
  • 46
  • 65
mr.baby123
  • 2,208
  • 23
  • 12
4

A variant of other proposed answers, which doesn't require unsafe code or manual marshalling:

    private static void SuppressCookiePersistence()
    {
        int flag = INTERNET_SUPPRESS_COOKIE_PERSIST;
        if (!InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, ref flag, sizeof(int)))
        {
            var ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            throw ex;
        }
    }

    const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 81;
    const int INTERNET_SUPPRESS_COOKIE_PERSIST = 3;

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, ref int flag, int dwBufferLength);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • And with the new (C# 7.2) `in` parameter modifier, you don't even need the extra `flag` variable , you can just specify inline: `InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, INTERNET_SUPPRESS_COOKIE_PERSIST, sizeof(int));` if you declare the p/invoke as `internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, in int lpBuffer, int dwBufferLength);` – Gábor Mar 24 '18 at 23:31
  • On a related note, no, this doesn't delete the cookies. This modifies the policy so that even cookies normally marked as persistent will not be persisted. Thread cautiously because using it might break some sites and login processes. If it works in your case then the cookies will be gone after you leave all right but it might just not work. – Gábor Apr 05 '18 at 10:39
4

web browser control based on Internet Explorer , so when we delete IE cookies,web browser cookies deleted too. so by this answer you can try this:

System.Diagnostics.Process.Start("CMD.exe","/C RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");
FarhadMohseni
  • 395
  • 5
  • 8
3

Try using this:

System.IO.File.Delete(Environment.SpecialFolder.Cookies.ToString() + "cookiename");
1
webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")
Josh M.
  • 26,437
  • 24
  • 119
  • 200
1

I'm using this code and it works without JavaScript. It's doing the same things as the JavaScript, but in VB.NET. Also, no navigation needed.

For Each cookie As String In Document.Cookie.Split(";"c)
    Dim domain As String = "." + url.Host
    While domain.Length > 0
        Dim path As String = url.LocalPath
        While path.Length > 0
            Document.Cookie = cookie.Split("="c)(0).Trim & "= ;expires=Thu, 30-Oct-1980 16:00:00 GMT;path=" & path & ";domain=" & domain
            path = path.Substring(0, path.Length - 1)
        End While
        Select Case domain.IndexOf(".")
            Case 0
                domain = domain.Substring(1)
            Case -1
                domain = ""
            Case Else
                domain = domain.Substring(domain.IndexOf("."))
        End Select
    End While
Next

The only real difference from the JavaScript is where, instead of just expiring cookie=value, I specifically search for the = and expire cookie=. This is important for expiring cookies that have no value.

Pitfalls:

  • You can only delete the cookies of the website to which you have navigated.
  • If the page is redirected to a different domain, the cookies you remove might be from the redirected domain. Or not, it's a race between the redirect and your code.
  • Don't access Document until ReadyState = WebBrowserReadyState.Complete, otherwise Document will be Nothing and the dereference will throw an exception.
  • Probably lots of others, but this code works great for me.

Firefox with the View Cookies Add-On helped a lot in debugging specific web pages.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eyal
  • 5,728
  • 7
  • 43
  • 70
1

Does the webbrowser control show pages form mutliple sites that you, as a developer, are not in control of, or are you just using the web browser control to view custom HTML pages created within your application?

If it is the former, cookies are directly tied to the domain that sets them, and as such to delete these cookies you would need to monitor the users's cookie directory and delete any new cookies created, a track changes to existing cookies.

If it is the later, you can always send the webbrowser control to a custom page that deletes the cookies with either server-side scripting (if available in your application) or JavaScript.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter Lange
  • 2,786
  • 2
  • 26
  • 40
  • I guess the WebBrowser control doesn't use something like a CookieContainer object that we can just reset to reset all cookies, eh? – gehsekky May 26 '09 at 21:24
  • Well, I read somewhere on google that webbrower control cookies are stored in some application cache seperate from IE. I don't mind deleting all the cookies from the cookies folder in windows but I'm just not sure if that will solve the problem. – Proximo May 26 '09 at 21:37
  • 1
    Hmmm, that could be the case currently. The last time I used a WebBrowser Control was with VB6 of all things, so they certainly may have refined that by now. I wouldnt delete all the users cookies though, in any case. Thats just mean. I stored my passwords to naughty sites in those cookies. =) – Peter Lange May 26 '09 at 21:50
  • Great, well let me test your suggestion out and see if it will work, if so I'll give you the check. – Proximo May 27 '09 at 00:29
0

After a great time finding how destroy sessions in webbrowser C# I'm have sucessfull using a code:

webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")

how says for Jordan Milne in this topic above.

In my application I need use webbrowser1.navigate("xxx");

here don't work if you use the C# properties.

i hope you find it useful this information.

Josh M.
  • 26,437
  • 24
  • 119
  • 200
diangelisj
  • 167
  • 1
  • 2
  • 4