How to enable local storage on Android WebView in Xamarin.Forms

I would like to enable HTML5 localstorage in my Xamarin.Forms app. When I deploy to an Android device I can see that the web page is erroring because localstorage is not enabled.

Natively, localstorage can be enabled as follows:

    webview = (WebView) findViewById(R.id.webview); 
    WebSettings settings = webview.getSettings(); 
    settings.setDomStorageEnabled(true);

How/where can I access these platform specific settings for the Android web view (Android.WebKit.Webview) when I only have access to the Xamarin.Forms webview (Xamarin.Forms.WebView).

More generally, is it at all possible to write platform specific code in Xamarin.Forms or is Xamarin.Forms too limited for all but the most very basic applications?

Answers


Yes it's possible to write platform specific code when using Xamarin.Forms, that's exactly the function of the renderers extensability like Paul said.

Create your custom WebView on Forms PCL

public class CustomWebView : WebView { }

Create your custom WebCiewRenderer on your Android Project

public class CustomWebViewRenderer : global::Xamarin.Forms.Platform.Android.WebViewRenderer
{
    protected override void OnElementChanged (Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Xamarin.Forms.WebView> e)
    {
        base.OnElementChanged (e);

        if (Control != null) {
            Control.Settings.DomStorageEnabled = true;
        }
    }
}

Don't forget to export your renderer

[assembly: ExportRenderer (typeof (CustomWebView), typeof(CustomWebViewRenderer))]

You can write platform-specific code when needed by using custom renderers. By following that link you will see different examples of how to customize the controls for each platform. In your case, you would be subclassing the WebViewRenderer in order to provide Android-specific behavior.


Need Your Help

Eclipse for android on Debian Lenny

android eclipse debian

I have installed Eclipse on Debian Lenny after having installed java (apt-get install sun-java6-jre sun-java6-plugin sun-java6-jdk).