Windows Phone WebBrowser set cookies

点点圈 提交于 2020-01-10 05:43:06

问题


I am using HttpWebRequest for REST services which uses some basic authentication that relies on JSESSIONID cookie. I need to pass that cookie to WebBrowser control to reuse that session, but didn't find any usable solution that would allow me to pass that cookie in the Browser's cookie store.

Is there any way? The only way that I can think of now is to use Naviagate(url, null, MANUALLY_CONSTRUCTED_HEADER) which is kind of brute-force.

Yes, and really have to use WebBrowser for this kind of action.

Any suggestions?


回答1:


Another thought is that you might be able to add cookies via JavaScript. You should be able to do this (provided IsScriptEnabled is true on your browser control):

private void setCookie(string name, string value, string path = "", string domain = "", bool isSecure=false, string expires = "")
{
        var sb = new StringBuilder();
        sb.AppendFormat("document.cookie = '{0}=\" + escape(\"{1}\")", name, value);
        if (!String.IsNullOrEmpty(expires))
            sb.AppendFormat(";expires=\"{0}\"", expires); // should be a GMTString
        if (!String.IsNullOrEmpty(path))
            sb.AppendFormat(";path=\"{0}\"", path); 
        if (!String.IsNullOrEmpty(domain))
            sb.AppendFormat(";domain=\"{0}\"", domain);
        if (isSecure)
            sb.Append(";secure'");
        var cookieJs = sb.ToString();
        Debug.WriteLine(cookieJs);
        webBrowser.InvokeScript(cookieJs);
}



回答2:


I solved my problem by sending JSESSIONID in URL for the first time, which then obtained the valid JSESSIONID cookie. But this is not an universal approach.

I think that there is solution which will navigate to simple webpage, that's nested within the application resource. The browser can then invoke javascript function, which will set the cookies passed by parameters. If Microsoft does not interfere with such approach (by disablink document.cookie), this can be a solution (I haven't tested it yet).




回答3:


For those who are getting exception on invoking script even on LoadCompleted event, try this out:

webBrowser.InvokeScript("eval", "document.cookie = \"COOKIE_NAME=" + COOKIE_VALUE + "; Path=/; Domain=" + WEB_URL.DnsSafeHost + " ;\";");

This one worked for me on LoadCompleted event. Keep in mind you have to load twice to get cookie functional. On LoadCompleted, cookie will be injected but not shown, on second load though, it would work fine.



来源:https://stackoverflow.com/questions/13287409/windows-phone-webbrowser-set-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!