How to set and delete cookies from WebBrowser Control for arbitrary domains

后端 未结 6 2194
你的背包
你的背包 2020-12-05 21:03

How can I set and delete cookies for a domain in webbrowser control without using Javascript (which doesn\'t allow to set / delete cookies without navigating to the webs

6条回答
  •  清歌不尽
    2020-12-05 21:32

    Hope this helps

    using System.Runtime.InteropServices;
    
    namespace Storm8
    {
        class Program
        {
    
            [DllImport("wininet.dll", SetLastError = true)]
            private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
    
            [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern bool InternetGetCookie(
                string lpszUrlName,
                string lpszCookieName,
                StringBuilder lpszCookieData,
                [MarshalAs(UnmanagedType.U4)]
                ref int lpdwSize
            );
    
            [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern bool InternetSetCookie(
                string lpszUrlName,
                string lpszCookieName,
                string lpszCookieData
            );
    
            [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern bool InternetSetOption(
                int hInternet,
                int dwOption,
                string lpBuffer,
                int dwBufferLength
            );
    
    
    
            [STAThread]
            static void Main(string[] args)
            {
                InternetSetOption(0, 42, null, 0);
                InternetSetCookie("http://domain.name.com", "cookiename", "cookievalue");
    
                WebBrowser wb = new WebBrowser();
                string testUrl = "http://domain.name.com/fight.php?showAttackBg=true";
                string additionalHeaders = "User-Agent: Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit /528.18 (KHTML, like Gecko) Mobile/7A341" + Environment.NewLine +
                    "Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" + Environment.NewLine +
                    "Accept-Language: en-gb";
    
                if (wb.Document == null)
                    wb.Navigate(testUrl, null, null, additionalHeaders);
    
                while (wb.Document == null)
                    Application.DoEvents();
    
                Console.WriteLine("\nPress any key to continue...");
                Console.ReadKey(true);
            }
        }
    }
    

    Reference

提交回复
热议问题