Khoa
Khoa

Reputation: 263

Xamarin Forms - Webview Detect URL Change

I'm trying to detect if the url in the webview matches a certain address.

For example, when the user processes a payment in webview, it will redirect to example.com.

How would I structure my code to automatically detect if the webview url changes to example.com?

Here's my xaml code:


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

Here's my CS code.

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>";

So the flow would be.

  1. Show HTML javascript button in webview.
  2. If the user clicks on the button and processes payment, it will redirect to example.com
  3. If webview contains example.com then do something.

Upvotes: 1

Views: 2434

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

You can get the current Url in the event Navigating . It will been invoked when you open the WebView or navigate to a new web in the 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"))
        {
           //...
        }

    }

Upvotes: 4

Related Questions