I am trying to implement this solution offered as an answer here: Opening target="_blank" links with Xamarin.Forms WebView
In the Android project I have created a custom renderer which has these code excerpts:
[assembly: ExportRenderer(typeof(HybridWebView), typeof(MyApp.controls.HybridWebViewRenderer))]
public class HybridWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
Control.Settings.SetSupportMultipleWindows(true);
}
}
In my shared project I have created a HybridWebView
which has among others these excerpts of code:
public class HybridWebView : WebView
{
public override bool OnCreateWindow(Android.Webkit.WebView view, bool isDialog, bool isUserGesture, Android.OS.Message resultMsg)
{
Android.Webkit.WebView newWebView = new Android.Webkit.WebView(_context);
view.AddView(newWebView);
Android.Webkit.WebView.WebViewTransport transport = (Android.Webkit.WebView.WebViewTransport)resultMsg.Obj;
transport.WebView = newWebView;
resultMsg.SendToTarget();
return true;
}
}
This gives as a result the following error:
CS0115 'HybridWebViewRenderer.OnCreateWindow(WebView, bool, bool, Message)': no suitable method found to override
Any idea how to overcome this issue?
As far as I'm concerned,we do not need to override the OnCreateWindow in custom renderer in Target project.Also, please take care of the OnElementChanged method in Custom Webview.We need set SetSupportMultipleWindows to true,enabled JS,set SetWebChromeClient, set WebViewClient,set AddJSInterface and last but not least, LoadUrl for the webview.
Below is the code snippet for your reference:
[assembly: ExportRenderer(typeof(HybridWebView),
typeof(HybridWebViewRenderer))]
namespace AppHybridWebView.Droid
{
public class HybridWebViewRenderer : WebViewRenderer
{
public HybridWebViewRenderer(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Settings.SetSupportMultipleWindows(false);
Control.Settings.JavaScriptEnabled = true;
Control.SetWebChromeClient(new MyWebChromeClient());
Control.SetWebViewClient(new JavascriptWebViewClient(this, $"javascript: {JavascriptFunction}"));
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
Control.LoadUrl($"file:///android_asset/Content/{((HybridWebView)Element).Uri}");//LoadUrl
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((HybridWebView)Element).Cleanup();
}
base.Dispose(disposing);
}
}
public class MyWebChromeClient : WebChromeClient
{
public override bool OnCreateWindow(Android.Webkit.WebView view, bool isDialog, bool isUserGesture, Message resultMsg)
{
if (!isDialog)
{
return true;
}
return base.OnCreateWindow(view, isDialog, isUserGesture, resultMsg);
}
}
}
Code in xaml:
<local:HybridWebView x:Name="hybridWebView" Uri="index.html" />