[英]How to detect back button click and make webview go back
我正在尝试使用 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;
}
}
}
我已经尝试了几个答案,我发现了这段代码,但它不起作用,因为覆盖无法访问公共网页浏览器变量:
if (browser.CanGoBack)
{
browser.GoBack();
return true;
}
else
{
base.OnBackButtonPressed();
return true;
}
任何帮助将非常感激。
您需要将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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.