Dan Cook
Dan Cook

Reputation: 2072

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?

Upvotes: 2

Views: 4423

Answers (2)

Rui Marinho
Rui Marinho

Reputation: 1712

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))]

Upvotes: 5

Paul
Paul

Reputation: 1175

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.

Upvotes: 0

Related Questions