I am trying to build a webview app for one of my projects using Xamarin but I can't seem to figure out how to make the webview element go to previous page instead of closing the app.
So I have figured out how to detect the back button being pressed and prevent it from closing the app but I want to make the web page go back and if the web page can't go back then close the app.
Here's my code at the moment:
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;
}
}
}
I have tried a couple of answers and I found this bit of code but it doesn't work as the override can't access the public WebPage browser var:
if (browser.CanGoBack)
{
browser.GoBack();
return true;
}
else
{
base.OnBackButtonPressed();
return true;
}
Any help would be much appreciated.
you need to make browser
a class level variable so you can access it anywhere in your page.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.