繁体   English   中英

从应用程序强制在移动浏览器中打开新标签页

[英]Force open a new tab in mobile browser from an app

我有一个应用程序,它在 xamarin 中有一个 webview 并显示一个 web,其中包含以这种方式配置的链接:

<a target="_blank" href="http://www.web.com"> http://www.web.com </a>

但它们不起作用,我想这是因为从应用程序查看网络时,它无法在新窗口中打开链接。 我也试过 window.open 没有任何变化。 我如何配置链接以使用新链接窗口强制打开浏览器。

谢谢。

如您所料,Xamarin.Forms 不支持打开新选项卡/窗口。 但是 Webview 组件有一个名为“Navigating”的事件处理程序,每次 webview 尝试打开新页面时,您都可以订阅它以执行代码。

public void NavigatingEventHandler(object sender, WebNavigatingEventArgs args)
{
    if (args.Url.StartsWith("https://"))
    {
        //If you want to open the new window in the OS browser
        Device.OpenUri(new Uri(args.Url));

        //If you want to open the new window inside the webview
        webview.Source = args.Url;

        args.Cancel = true;
    }
}

XAML:

<WebView x:Name="webview" Navigating="NavigatingEventHandler" />

我认为这应该发生在Android ,如果你想用浏览器打开一个新窗口,你可以在你的自定义渲染器中为你的WebView使用SetWebChromeClient方法。

在android项目中创建一个自定义渲染器:

[assembly: ExportRenderer(typeof(WebView), typeof(AndroidWebView))]
namespace your namespace
{
  class AndroidWebView:WebViewRenderer
  {
      public AndroidWebView(Context context) : base(context)
      {
       
      }

      protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
      {
          base.OnElementChanged(e);
          Control.SetWebChromeClient(new MywebviewChrome());
      }

      private class MywebviewChrome : Android.Webkit.WebChromeClient
      {
          public override bool OnCreateWindow(Android.Webkit.WebView view, bool isDialog, bool isUserGesture, Message resultMsg)
          {
              Android.Webkit.WebView.HitTestResult result = view.GetHitTestResult(); 
              string data = result.Extra; 
              Context context = view.Context; 
              Intent browserIntent = new Intent(Intent.ActionView,Android.Net.Uri.Parse(data)); 
              context.StartActivity(browserIntent);

              return false;
          }


      }
  }
}

在您的表单项目 xaml 中:

<WebView HeightRequest="800" WidthRequest="600" x:Name="webview" ></WebView>

在您的 page.xaml.cs 中:

var htmlSource = new HtmlWebViewSource();
htmlSource.Html = @"<a target='_blank' href='http://www.web.com'> http://www.web.com </a>";
webview.Source = htmlSource;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM