简体   繁体   中英

Send cookie to web application using system.windows.forms.browser

I have windows forms application. I have to create and send new cookie to web application via browser control(create and send new cookie from windows forms application through its browser control).

This winforms application displays only one web application that is waiting for information in wanted cookie. This web application then should do some decisions depending on value from this cookie.

I have found this: Use cookies from CookieContainer in WebBrowser

but I would like to avoid using:

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]

Any ideas?

I did not extensively tested this solution, but it should work. I tried it with a static page and the cookie is correctly added.

What I do is basically injecting into the document a Javascript function that adds the cookie, then immediately calling it.

        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
        }

        void Form1_Load(object sender, EventArgs e)
        {
            webBrowserControl.Navigate("file:///C:/Temp/span.html");
            webBrowserControl.Navigated += webBrowserControl_Navigated;
        }

        void webBrowserControl_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            InjectCookieSetterScript();
        }

        private void InjectCookieSetterScript()
        {
            String script =
@"function setCookie()
{
    document.cookie = ""myCookie=value;path=/"";
}";
            InjectScript(script);
            webBrowserControl.Document.InvokeScript("setCookie");
        }

        public void InjectScript(String scriptText)
        {    
            var headElements = webBrowserControl.Document.GetElementsByTagName("head");
            if (headElements.Count == 0)
            {
                throw new IndexOutOfRangeException("No element with tag 'head' has been found in the document");
            }
            var headElement = headElements[0];

            var script = webBrowserControl.Document.CreateElement("script");
            script.InnerHtml = scriptText; // "<script>" + scriptText + "</script>";
            headElement.AppendChild(script);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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