简体   繁体   English

如何从windows.form删除Cookies?

[英]How to delete Cookies from windows.form?

I am working with the Webbrowser control on a windows.form application written in C#. 我正在用C#编写的windows.form应用程序上使用Webbrowser控件。 I would like to write a method for deleting the cookies from the Webbrowers control after it visits a certain site. 我想编写一种在Webbrowers控件访问某个站点后从cookie中删除cookie的方法。 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? 任何人都可以对整个cookie事情有所了解吗?

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. 如果启用了JavaScript,则可以使用此代码段清除以清除Web浏览器当前所在站点的cookie。

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. 它源自此小书签,用于清除cookie。

I modified the solution from here: http://mdb-blog.blogspot.ru/2013/02/c-winforms-webbrowser-clear-all-cookies.html 我从此处修改了解决方案: 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 您可以在流程开始时的某个地方调用SupressCookiePersist,并在关闭浏览器时调用EndBrowserSession清除Cookie,如下所述: Facebook多帐户

I found a solution, for deleting all cookies. 我找到了删除所有cookie的解决方案。 the example found on the url, deletes the cookies on application (process) startup. 在url上找到的示例,将在应用程序(进程)启动时删除cookie。

http://mdb-blog.blogspot.com/2013/02/c-winforms-webbrowser-clear-all-cookies.html 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. 该解决方案使用InternetSetOption函数来宣布WEBBROWSER清除其所有内容。

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 : 请注意,这仅按照MSDN INTERNET_OPTION_SUPPRESS_BEHAVIOR上的说明清除特定过程的cookie:

A general purpose option that is used to suppress behaviors on a process-wide basis. 通用选项,用于在整个流程范围内禁止行为。

尝试使用此:

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

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

web browser control based on Internet Explorer , so when we delete IE cookies,web browser cookies deleted too. 基于Internet Explorer的Web浏览器控件,因此当我们删除IE cookie时,web浏览器cookie也被删除。 so by this answer you can try this: 因此,通过答案,您可以尝试以下操作:

System.Diagnostics.Process.Start("CMD.exe","/C RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");

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? Web浏览器控件是否显示页面构成了您作为开发人员无法控制的多个站点,或者您只是使用Web浏览器控件来查看在应用程序中创建的自定义HTML页面?

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. 如果是前者,则cookie直接与设置它们的域绑定,因此要删除这些cookie,您需要监视用户的cookie目录并删除创建的任何新cookie,以跟踪对现有cookie的更改。

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. 如果是更高版本,则始终可以将webbrowser控件发送到自定义页面,该页面使用服务器端脚本(如果在应用程序中可用)或JavaScript删除cookie。

I'm using this code and it works without JavaScript. 我正在使用此代码,并且没有JavaScript就可以工作。 It's doing the same things as the JavaScript, but in VB.NET. 它的功能与JavaScript相同,只是在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= . 与JavaScript唯一的真正区别在于,我专门搜索=并使cookie=过期,而不是仅使cookie=value过期。 This is important for expiring cookies that have no value. 这对于使没有价值的Cookie过期非常重要。

Pitfalls: 陷阱:

  • You can only delete the cookies of the website to which you have navigated. 您只能删除您浏览过的网站的cookie。
  • If the page is redirected to a different domain, the cookies you remove might be from the redirected domain. 如果页面被重定向到其他域,则您删除的Cookie可能来自重定向的域。 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. ReadyState = WebBrowserReadyState.Complete ,不要访问Document ,否则Document将为Nothing并且取消引用将引发异常。
  • 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. 带有View Cookies加载项的 Firefox在调试特定网页方面大有帮助。

After a great time finding how destroy sessions in webbrowser C# I'm have sucessfull using a code: 经过一段很长的时间,发现如何在Webbrowser C#中销毁会话,我使用代码成功完成了:

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"); 在我的应用程序中,我需要使用webbrowser1.navigate(“ xxx”);

here don't work if you use the C# properties. 如果您使用C#属性,则在这里不起作用。

i hope you find it useful this information. 我希望您能从中获得有用的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM