Home > other >  Opening target="_blank" links with Xamarin.Forms WebView
Opening target="_blank" links with Xamarin.Forms WebView

Time:03-18

I have recently encountered an issue with links having the target attribute set to _blank. Tapping on them has no effect. The WebView does not load the linked page.

Searching around I found this solution: https://github.com/xamarin/Xamarin.Forms/issues/12917 which is setting SetSupportMultipleWindows(false). More specifically the suggestion is to insert the following line of code: webView.Settings.SetSupportMultipleWindows(true);.

Trying that I get the following error: Error CS1061 'WebView' does not contain a definition for 'Settings' and no accessible extension method 'Settings' accepting a first argument of type 'WebView' could be found (are you missing a using directive or an assembly reference?)

Is there a way to overcome the error?

CodePudding user response:

You could add support for multiple windows in OnElementChanged of Hybrid renderer with code:

Control.Settings.SetSupportMultipleWindows(true);

edit:

public class MyWebViewRenderer : WebViewRenderer
    {
        public MyWebViewRenderer(Context context) : base(context)
        {
        }

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

            if(Control!=null)
            {
                Control.Settings.SetSupportMultipleWindows(true);
                Control.Settings.JavaScriptEnabled = true;
                Control.SetWebChromeClient(new MyWebChromeClient());
            }

        }

    }

    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);
        }
    }

}

CodePudding user response:

After many tries towards the wrong direction I found the line of code that worked for me. In the override of the OnElementChanged method in the Custom Webview Renderer this is the code that makes the opening of links with target=_blank attribute possible:

Control.Settings.SetSupportMultipleWindows(false);

SetSupportMultipleWindows; should be set to false, not to true as it has been suggested.

  • Related