使用Xamarin.Forms Webview检测URL更改并将当前URL与原始URL比较

时间:2019-05-23 18:50:51

标签: c# xamarin.forms webview

因此,我正在创建一个使用Xamarin.Forms Webview的应用程序。我试图检测URL何时发生更改,如果发生更改,则将原始URL与当前URL进行比较,然后显示或隐藏相应的按钮。按钮的目的是返回到上一页并继续前进,直到到达其原始目的地为止。我只希望当用户不在主屏幕上时显示此“返回”按钮。否则,请始终显示。

我已经用if(webview.cangoback ...)尝试了所有操作,但是没有检测到URL更改。我尝试设置一个与原始URL相等的字符串,然后使用.Equals来比较webview.source(这是我目前所在的位置)

我刚刚开始研究webviewNavigating,但还是一无所获。

namespace Webview_Test
{
    public partial class MainPage : ContentPage
    {
        public static string CurrentUrl { get; set; }
        public MainPage()
        {

            InitializeComponent();

            string CurrentUrl = "https://www.google.com/";

            var _webView = new WebView()
            {
                Source = "https://www.google.com/",
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            Button BackButton = new Button
            {
                Text = "Go Back",
                BackgroundColor = Color.FromHex("990000"),
                TextColor = Color.White
            };
            BackButton.Clicked += OnBackButtonClicked;

            void OnBackButtonClicked(object sender, EventArgs e)
            {
                _webView.GoBack();
            }


            Grid grid = new Grid
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions =
                {
                    new RowDefinition { Height = GridLength.Auto },
                    new RowDefinition { Height = GridLength.Auto },
                    new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                    new RowDefinition { Height = new GridLength(50, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(15, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(15, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(36, GridUnitType.Absolute) }
                },
                ColumnDefinitions =
                {
                    new ColumnDefinition { Width = GridLength.Auto },
                    new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                    new ColumnDefinition { Width = new GridLength(50, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(50, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                    new ColumnDefinition { Width = GridLength.Auto }
                }
            };

            grid.Children.Add(_webView, 0, 6, 0, 7);

            if (_webView.Source.Equals(CurrentUrl))
            {
                grid.Children.Remove(BackButton);
            }
            else
            {
                grid.Children.Add(BackButton, 2, 4, 4, 6);
            }

            Content = grid;
        }
    }
}

我的预期结果是主页上没有显示“返回”按钮。但是在首页以外的任何页面上,它都应显示“返回”按钮。用逻辑的话来说就是OriginalURL = CurrentURL不显示按钮。如果OriginalURL!= CurrentURL显示按钮。

3 个答案:

答案 0 :(得分:0)

我在每个平台上都创建了自定义的webView渲染器,以获取webView的当前网址,虽然有点复杂,但最终可以使用。

iOS 部分中,覆盖LoadingFinished方法以获取当前网址:

[assembly: ExportRenderer(typeof(MyWebView), typeof(MyWebViewRenderer))]
namespace App374.iOS
{
    public class MyWebViewRenderer : WebViewRenderer,IUIWebViewDelegate
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement == null)
            {   // perform initial setup
                UIWebView myWebView = (UIWebView)this.NativeView;

                Delegate = new CustomWebViewDelegate(e.NewElement as WebView);
            }
        }
    }

    public class CustomWebViewDelegate : UIWebViewDelegate
    {
        Xamarin.Forms.WebView formsWebView;

        public CustomWebViewDelegate(WebView webView)
        {
            formsWebView = webView;
        }

        public override void LoadingFinished(UIWebView webView)
        {
            var url = webView.Request.Url.AbsoluteUrl.ToString();

            MainPage.CurrentUrl = webView.Request.Url.AbsoluteString;

            MainPage.checkToShowButton();
        }

    }
}

在Android部分中,重写OnPageFinished方法以获取当前网址:

[assembly: ExportRenderer (typeof (MyWebView), typeof (MyWebViewRenderer))]
namespace App374.Droid
{
    public class MyWebViewRenderer : WebViewRenderer
    {
        public MyWebViewRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {
                // lets get a reference to the native control
                var webView = (global::Android.Webkit.WebView)Control;
                webView.SetWebViewClient(new MyWebViewClient());
                webView.SetInitialScale(0);
                webView.Settings.JavaScriptEnabled = true;
            }
        }
    }

    public class MyWebViewClient : WebViewClient
    {
        public override void OnPageFinished(Android.Webkit.WebView view, string url)
        {
            base.OnPageFinished(view, url);

            MainPage.CurrentUrl = url;

            MainPage.checkToShowButton();
        }
    }
}

然后隐藏代码,检查每次导航后是否显示“返回”按钮:

 public partial class MainPage : ContentPage
    {
        public static string CurrentUrl { get; set; }

        public static MyWebView _webView;

        public static Grid grid;

        public static Button BackButton;


        public MainPage()
        {

            InitializeComponent();

            string CurrentUrl = "https://www.baidu.com/";

            _webView = new MyWebView()
            {
                Source = CurrentUrl,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.FillAndExpand
            };


            BackButton = new Button
            {
                Text = "Go Back",
                BackgroundColor = Color.FromHex("990000"),
                TextColor = Color.White
            };

            grid = new Grid
            {
                 //...
            };

            grid.Children.Add(_webView, 0, 6, 0, 7);


            Content = grid;

            checkToShowButton();

            //Button click
            BackButton.Clicked += OnBackButtonClicked;
            void OnBackButtonClicked(object sender, EventArgs e)
            {
                _webView.GoBack();        

                checkToShowButton();

                if (_webView.CanGoBack == false)
                {
                    grid.Children.Remove(BackButton);
                }
            }
        }

        //Check whther to show goBack button
        public static void checkToShowButton()
        {

            if ("https://www.baidu.com/".Equals(MainPage.CurrentUrl) || CurrentUrl == null || CurrentUrl == "")
            {
                grid.Children.Remove(BackButton);
            }
            else
            {

                if (grid != null)
                {
                    grid.Children.Add(BackButton, 2, 4, 4, 6);
                }

            }
        }

    }

    public class MyWebView : WebView { }

我上传了整个样本here,您可以检查一下。让我知道它是否有效。

注意 :我测试了_webView.Navigated,发现它只有在加载webView时才第一次触发。

 _webView.Navigated += (sender, e) => {

 };

引用:webview-check-when-website-address-changed

答案 1 :(得分:0)

您是否尝试过导航活动?我在下面放一些例子。

public string OriginalURL = "https://www.stackoverflow.com"

private async void Webview_Navigating(object sender, WebNavigatingEventArgs e)
{
   if(e.Url != OriginalURL){ 
      //do your code, show the button or use if(webview.CanGoBack){//your code},etc

}

答案 2 :(得分:0)

可能已经晚了,但这可以帮助您轻松,快速,没有问题。

var url = await webView.EvaluateJavaScriptAsync("window.location.href");