localhorst27
localhorst27

Reputation: 143

Put cookie on a WebView in Xamarin

I have the following plan in my Xamarin Project:

The existing API (not public) delivers a System.Net.CookieCollection.

How can I realise my idea, using a POST-Request with those cookies? Here's my base:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class WebPage : ContentPage
{
    public WebPage(string url, CookieCollection cookies)
    {
        InitializeComponent();
        BindingContext = new MainPageViewModel();
        MyWebView.Source = "https://" + url;

    }
}

Kind regards, localhorst27

Upvotes: 5

Views: 6106

Answers (1)

Timo Salomäki
Timo Salomäki

Reputation: 7189

You will have to create a custom renderer for the WebView on both Android and iOS. That way you'll be able to inject the cookies into the Android WebView and iOS UIWebView. If you are not familiar with them, start here: Introduction to Custom Renderers

When you're familiar with how renderers work, follow this post by Christine Blanda on Xamarin forums: Setting Cookies in a WebView

I'll also post the code here to make sure it's preserved in case the original post goes down.

Android OnElementChanged

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

iOS OnElementChanged

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

Upvotes: 6

Related Questions