How to delete Cookies from windows.form?

☆樱花仙子☆ 提交于 2019-12-17 02:46:26

问题


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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


Try using this:

System.IO.File.Delete(Environment.SpecialFolder.Cookies.ToString() + "cookiename");



回答5:


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);



回答6:


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.




回答7:


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());}}}})())")



回答8:


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");



回答9:


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.




回答10:


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.



来源:https://stackoverflow.com/questions/912741/how-to-delete-cookies-from-windows-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!