簡體   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