0

I want to accept cookies in WebView, but get error

Uncaught Error: SECURITY_ERR: DOM Exception 18

The problem occures just in local js file. As Android docs say, I must use setAcceptFileSchemeCookies

But it doesn't solve my problem. I don't know what I'm doing wrong.

whole list of code:

protected override void OnCreate(Bundle bundle) {
        try {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            _webView = FindViewById<WebView>(Resource.Id.webview);
            string html = string.Empty;
            Android.Webkit.CookieManager.SetAcceptFileSchemeCookies(true);               
            using (var stream = _webView.Context.Assets.Open("res/mobileLogin.html")) {
                using (TextReader reader = new StreamReader(stream)) {
                    html = reader.ReadToEnd();
                }
            }
            _webView.Settings.JavaScriptEnabled = true;
            _webView.Settings.AllowFileAccess = true;
            _webView.Settings.AllowUniversalAccessFromFileURLs = true;
            _webView.SetWebViewClient(new HybridWebViewClient());
            _webView.SetWebChromeClient(new WebChromeClient());
            _webView.LoadDataWithBaseURL("file:///android_asset/res/", html, "text/html", "UTF-8", null);
            Android.Webkit.CookieManager.Instance.SetAcceptCookie(true);

        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
CruorVult
  • 823
  • 1
  • 9
  • 17

1 Answers1

0

As far as I can read, setting the cookie host to localhost on Android triggers a security exception. If you try the same with a remote host it will probably work. That, of course does not solve your problem. Something like this: https://stackoverflow.com/a/24897724/368379 could provide a starting point to handle stuff yourself, but not exactly the same as Cookies.

If you go the JavascriptInterface route, you can implement that in Xamarin.Android like so:

public class MyJavascriptInterface : Java.Lang.Object
{
    [Export("DoStuff")]
    [JavascriptInterface]
    public void DoStuff(string stuff)
    {
        // do something here with the string
    }
}

var webView = new WebView(this);
webView.Settings.JavaScriptEnabled = true;
var interface = new MyJavascriptInterface();
webView.AddJavascriptInterface(interface, "MyJavascriptInterface");

Then you can call it in Javascript like so:

MyJavascriptInterface.DoStuff("My Awesome String");
Community
  • 1
  • 1
Cheesebaron
  • 24,131
  • 15
  • 66
  • 118