【问题标题】:Send cookie to web application using system.windows.forms.browser使用 system.windows.forms.browser 将 cookie 发送到 Web 应用程序
【发布时间】:2015-08-05 15:05:14
【问题描述】:

我有 Windows 窗体应用程序。 我必须通过浏览器控件创建新 cookie 并将其发送到 Web 应用程序(通过其浏览器控件从 Windows 窗体应用程序创建和发送新 cookie)。

此 winforms 应用程序仅显示一个正在等待所需 cookie 中的信息的 Web 应用程序。然后,此 Web 应用程序应根据此 cookie 的值做出一些决定。

我发现了这个: Use cookies from CookieContainer in WebBrowser

但我想避免使用:

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

有什么想法吗?

【问题讨论】:

    标签: c# winforms webbrowser-control


    【解决方案1】:

    我没有对这个解决方案进行广泛的测试,但它应该可以工作。我用静态页面试了一下,正确添加了cookie。

    我所做的基本上是向文档中注入一个添加 cookie 的 Javascript 函数,然后立即调用它。

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

    【讨论】:

    • 谢谢!它按我想要的方式工作。这是一个优雅的 hack - 我喜欢它。
    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    相关资源
    最近更新 更多