Xamarin Forms - Webview 检测 URL 更改

Xamarin Forms - Webview Detect URL Change

我正在尝试检测网络视图中的 url 是否与某个地址匹配。

例如,当用户在 webview 中处理付款时,它将重定向到 example.com。

我如何构造我的代码以自动检测网络视图 url 是否更改为 example.com?

这是我的 xaml 代码:


<Frame BorderColor="LightGray" CornerRadius="10" HasShadow="False">
   <WebView x:Name="eWayPaymentWebView" VerticalOptions="FillAndExpand" WidthRequest="500" HeightRequest="500">
   <WebView.Source>
      <HtmlWebViewSource x:Name="paymenthtml" Html="{Binding Html}"/>
   </WebView.Source>
   </WebView>
</Frame>

这是我的 CS 代码。

paymenthtml.Html = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'><style>img{max-width:100%}</style></header><html><head><title></title></head><body><div align='center'>
                                <script src=""payment.js""
                                   "data-label='ORDER NOW' " +
                                   "data-currency='AUD' " +
                                   "data-buttonerrorcolor='#f2dede' " +
                                   "data-buttonprocessedcolor='#dff0d8' " +
                                   "data-buttondisabledcolor='#f5f5f5' " +
                                   "data-buttoncolor='#35bd35' " +
                                   "data-buttontextcolor='#ffffff'" +
                                   "data-resulturl='https://www.example.com'>" +
                                   "</script></div></body></html>";

所以流程应该是。

  1. 在网络视图中显示 HTML javascript 按钮。
  2. 如果用户点击按钮并处理付款,它将重定向到 example.com
  3. 如果 webview 包含 example.com 然后做一些事情。

您可以在 Navigating 事件中获取当前 Url 。当您打开 WebView 或导航到 WebView 中的新网站时将调用它。

  public MainPage()
    {
        InitializeComponent();

        webview.Navigating += Webview_Navigating;

    }

    private void Webview_Navigating(object sender, WebNavigatingEventArgs e)
    {
        var url = e.Url;

        if (url.Contains("example.com"))
        {
           //...
        }

    }