如何检测后退按钮点击并使webview返回

Rya*_*son 4 c# android xamarin

我正在尝试使用 Xamarin 为我的一个项目构建一个 webview 应用程序,但我似乎无法弄清楚如何让 webview 元素转到上一页而不是关闭应用程序。

所以我想出了如何检测被按下的后退按钮并防止它关闭应用程序,但我想让网页返回,如果网页无法返回,则关闭应用程序。

这是我目前的代码:

using System;
using Xamarin.Forms; 
using Xamarin.Forms.Xaml; 
using Application = Xamarin.Forms.Application; 

namespace myNewApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public class WebPage : ContentPage
    {
        public object _browser { get; private set; }

        protected override bool OnBackButtonPressed()
        {

                base.OnBackButtonPressed();
                return true;

        }

        public WebPage()
        {


            var browser = new Xamarin.Forms.WebView();

            browser.Source = "https://myurl.com";


            Content = browser;

        }



    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几个答案,我发现了这段代码,但它不起作用,因为覆盖无法访问公共网页浏览器变量:

if (browser.CanGoBack)
            {
                browser.GoBack();
                return true;
            }
            else
            {
                base.OnBackButtonPressed();
                return true;
            }
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激。

Jas*_*son 5

您需要创建browser一个类级别的变量,以便您可以在页面的任何位置访问它。

public class WebPage : ContentPage
{
    Xamarin.Forms.Webview browser;

    protected override bool OnBackButtonPressed()
    {

        base.OnBackButtonPressed();

        if (browser.CanGoBack)
        {
            browser.GoBack();
            return true;
        }
        else
        {
            base.OnBackButtonPressed();
            return true;
        }

    }

    public WebPage()
    {


        browser = new Xamarin.Forms.WebView();

        browser.Source = "https://myurl.com";


        Content = browser;

    }
}
Run Code Online (Sandbox Code Playgroud)