Search code examples
xamarin.formswebviewcustom-renderer

Xamarin.Forms ERR_FILE_NOT_FOUND (file:///android_asset/Content/https://stackoverflow.com) using HybridWebViewSample


I followed the post to create a custon WebView to interact with client JavaScript: https://learn.microsoft.com/es-es/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview

But when I try to load a page, for example https://www.google.es, the wevView shows an "ERROR_FILE_NOT_FOUND" loading the page "file:///android_asset/Content/https://www.google.es"

This the OnElementChanged of the HybridWebViewRenderer:

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{           
    base.OnElementChanged(e);

    if (e.OldElement != null)
    {
        Control.RemoveJavascriptInterface("jsBridge");
        ((HybridWebView)Element).Cleanup();
    }
    if (e.NewElement != null)
    {
        Control.SetWebViewClient(new JavascriptWebViewClient($"javascript: {JavascriptFunction}"));
        Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
        Control.LoadUrl($"file:///android_asset/Content/{((HybridWebView)Element).Uri}");
    }
}        

Edited: It seems hybridWebView doesn't work with external pages!

Any suggestion?


Solution

  • Solved:

    Changing the LoadUrl method:

    Control.LoadUrl($"file:///android_asset/Content/{((HybridWebView)Element).Uri}");
    

    by:

    UrlWebViewSource source = Element.Source as UrlWebViewSource;
    Control.LoadUrl(source.Url);
    

    Works with external webs and can retrive JavaScript callBacks and send JavaScript code. This is the full code:

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
    {           
        base.OnElementChanged(e);
    
        if (e.OldElement != null)
        {
            Control.RemoveJavascriptInterface("jsBridge");
            ((HybridWebView)Element).Cleanup();
        }
        if (e.NewElement != null)
        {
            Control.SetWebViewClient(new JavascriptWebViewClient($"javascript: {JavascriptFunction}"));
            Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
            UrlWebViewSource source = Element.Source as UrlWebViewSource;
            Control.LoadUrl(source.Url);
        }
    }