在WebBrowser和IE之间共享cookie

时间:2018-03-02 00:17:22

标签: webbrowser-control internet-explorer-11

我打开Internet Explorer 11.登录网站。然后我创建WebBrowser控件。导航到同一站点。但错过了cookie,我没有登录。可以在IE和WebBrowser之间共享cookie吗?

1 个答案:

答案 0 :(得分:1)

WebBrowser默认情况下使用IE浏览器,但旧版本。为了使用更新,您需要调整注册表。为了检索cookie:


    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
    const int INTERNET_COOKIE_HTTPONLY = 0x00002000;

    public static string GetGlobalCookies(string uri)
    {
        uint datasize = 1024;
        StringBuilder cookieData = new StringBuilder((int)datasize);
        if (InternetGetCookieEx(uri, null, cookieData, ref datasize, 
        INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)
            && cookieData.Length > 0)
        {
            return cookieData.ToString().Replace(';', ',');
        }
        else
        {
            return null;
        }
    }

Source

然后你可以将它们传递给网页浏览器控件:

WebBrowser web = new WebBrowser();
web.Document.Cookie = GetGlobalCookies(uri);