Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Setting Cookies in a WebView

$
0
0

I received a request this morning to share how I set cookies in a webview so here it is, hope it's helpful. It's worked for me so far but feel free to comment on it if it can be improved.
First, you have to create a custom render for your webview in iOS and Android, there are many examples of how to do that so I won't go into that here.
In my shared code I have a UserInfo object that contains a CookieContainer:

    public class UserInfo
    {
        public static CookieContainer CookieContainer = new CookieContainer();
    }

In my (native) login page I have an event called OnLoginClickAsync which validates the login information. I create a HTTPClientHandler:

                var handler =  new HttpClientHandler {CookieContainer = UserInfo.CookieContainer};
                var httpClient = new HttpClient(handler);

Then save the resulting CookieContainer if the validation is successful:

                UserInfo.CookieContainer = handler.CookieContainer;

On the Android side in the OnElementChanged event for my web view renderer I use:

            var cookieManager = CookieManager.Instance;
            cookieManager.SetAcceptCookie(true);
            cookieManager.RemoveAllCookie();
            var cookies = UserInfo.CookieContainer.GetCookies(new System.Uri(AppInfo.URL_BASE));
            for (var i = 0; i < cookies.Count; i++)
            {
                string cookieValue = cookies[i].Value;
                string cookieDomain = cookies[i].Domain;
                string cookieName = cookies[i].Name;
                cookieManager.SetCookie(cookieDomain, cookieName + "=" + cookieValue);
            }

On the iOS side in the OnElementChanged event for my web view renderer I use:

            // Set cookies here
            var cookieUrl = new Uri(AppInfo.URL_BASE);
            var cookieJar = NSHttpCookieStorage.SharedStorage;
            cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
            foreach (var aCookie in cookieJar.Cookies)
            {
                cookieJar.DeleteCookie(aCookie);
            }

            var jCookies = UserInfo.CookieContainer.GetCookies(cookieUrl);
            IList<NSHttpCookie> eCookies = 
                (from object jCookie in jCookies 
                 where jCookie != null 
                 select (Cookie) jCookie 
                 into netCookie select new NSHttpCookie(netCookie)).ToList();
            cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);

Also, if you want to use the cookie container in a straight call - not in a webview - just set it in the handler:

            var handler = new HttpClientHandler { CookieContainer = cookieContainer };
            var httpClient = new HttpClient(handler);

Viewing all articles
Browse latest Browse all 77050

Trending Articles