Xamarin Forms - 让WebView返回上一页

9

大家早上好,

我正在使用Xamarin.Forms开发一个小型跨平台Webview项目。我已经实现了Webview功能,但是我想添加一个工具栏,在其中放置返回和前进按钮。

我尝试了多种不同的方法,但似乎没有什么特别好的效果。我试图按照这个人的帖子导航工具栏来实现此功能。

我将我的代码附在下面,如果有人能帮我或者提供解决方案,那就太好了!

如果这个问题之前已经被其他用户回答过了,那我道歉。

App.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Xamarin.Forms;

namespace DisplayWebPage
{
    public class App : Application
    {
        public App()
        {
            // The root page of your application
            MainPage = new WebPage();
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

WebPage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;

using Xamarin.Forms;

namespace DisplayWebPage
{
    public class WebPage : ContentPage
    {
        public WebPage()
        {
            Content = new StackLayout
            {
                Children = {
                    new WebView
                    {
                        Source = "http://www.google.com"
                    }
                }
            };
        }
    }
}

我一直卡在这个问题上,希望能得到答案。

祝好

3个回答

3

按照以下方式编辑您的代码。首先,将MainPage包装在NavigationPage中,以使工具栏可见。

基本上,您需要创建一个变量,以便更轻松地访问您的WebView

然后,在ToolbarItems集合中创建一个按钮,该按钮可以触发事件。在该事件中,您可以调用WebView上已有的GoBack()方法。

您可能想查看Xamarin文档上的WebView,这可能是检查CanGoBack属性是否实际上可以返回的好方法。

请注意,我已分配了BackIcon.png,您可以将其替换为null或您自己的图标。此外,该代码尚未经过测试,这只是我的一时兴起,因此可能缺少一些分号或其他东西。

App.cs

// ... other code

public App()
{
   // The root page of your application
   MainPage = new NavigationPage(new WebPage());
}
// ... other code

WebPage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;

using Xamarin.Forms;

namespace DisplayWebPage
{
    public class WebPage : ContentPage
    {
        private WebView _webView;

        public WebPage()
        {
           // Assign a WebView to a global variable
            _webView = new WebView
                    {
                        Source = "http://www.google.com",
                        HeightRequest="1000",
                       WidthRequest="1000" 
                    };

            // Create toolbar items here
            ToolbarItems.Add(new ToolbarItem("Back", "BackIcon.png", () => { _webview.GoBack(); }));

            Content = new StackLayout
            {
                Children = { _webView}
            };
        }
    }
}

我已经在那段代码中添加了内容,但它仍然不能返回到上一页。另外,我正在 Android 模拟器上进行测试,但是我想要显示在屏幕顶部的工具栏根本没有出现? - Duggan
所以我认为工具栏已经可以使用了。我只是添加了以下内容:public App() { // The root page of your application MainPage = new NavigationPage(new WebPage()); }但现在 WebView 没有显示出来。有什么想法吗?我在某个地方读到过,每个 ContentPage 只能有一个项目,这可能是问题吗? - Duggan
1
尝试为您的 WebView 设置 WidthRequestHeightRequest - Gerald Versluis
所以我测试了几次,似乎运行正常... 偶尔会出现问题。我的意思是,我必须关掉模拟器,然后运行程序,再打开它,在那之后它就完美地运行了。我不知道这是不是只是模拟器的问题。今晚我会在我的设备上进行更多测试。如果你以前遇到过这样的情况,请告诉我 :) 我稍后会向你更新是否只是模拟器问题。谢谢帮助! - Duggan
如果这个回答帮助您实现了返回导航功能,请接受它作为答案 :) - Gerald Versluis

3
这段文字的翻译如下:

Gerald Versluis答案 很棒。基于此,我想分享一下在尝试解决以下问题后我的代码是什么样子的:

  • 尝试在 XAML 中实现工具栏和 Webview(使用 VS2017)
  • 当前页为首页时隐藏工具栏(不需要返回)
  • 重写设备返回按钮

App.xaml.cs

// ... using, namespace etc

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            MainPage = new NavigationPage(new MainPage());
        }
    }

// ...

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MyApp"
             x:Class="MyApp.MainPage"
             NavigationPage.HasNavigationBar="False"
             Title="My App">

    <ContentPage.ToolbarItems>
        <ToolbarItem Name="Back" Clicked="OnBack"></ToolbarItem>
    </ContentPage.ToolbarItems>

    <WebView x:Name="browser" Navigating="OnNavigating"></WebView>
</ContentPage>

MainPage.xaml.cs

using System;
using Xamarin.Forms;

namespace MyApp
{
    public partial class MainPage : ContentPage
    {
        string Url;

        public MainPage()
        {
            InitializeComponent();
            browser.Source = Url = GetUrl();
        }

        void OnBack(object sender, EventArgs args)
        {
            browser.GoBack();
        }

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

        void OnNavigating(object sender, WebNavigatingEventArgs args)
        {
            // Checking if we are at the home page url
            // browser.CanGoBack does not seem to be working (not updating in time)
            NavigationPage.SetHasNavigationBar(this, args.Url != Url);
        }

        string GetUrl()
        {
            // Possibly some mechanism to accomoddate for several locales
            return "...";
        }
    }
}

1
谢谢您,非常有帮助!所有其他解决方案都缺少一部分内容。 - OverMars

1

请尝试以下步骤: 在 WebView 对象中添加 Navigated 事件

 List<string> history = new List<string>();
 WebView myWebView = new WebView
 {
      Source = "http://www.google.com"
 };
myWebView.Navigated += WebViewPage_Navigated;
Children = myWebView;

然后定义以下函数:
public void WebViewPage_Navigated(object sender, WebNavigatedEventArgs e)
{
    WebNavigationResult result = e.Result;            
    if(result.Equals(WebNavigationResult.Success)){
        currentUrl = e.Url;
       history.Add(currentUrl);
    }            
}

现在你可以基于历史记录列表计数和当前元素绑定“前进”和“后退”元素(如果向后移动,则添加到前进列表)。希望这能帮到你。

1
你为什么想要这样做?WebView有默认的GoBackGoForward方法。在这里查看Xamarin文档:https://developer.xamarin.com/guides/cross-platform/xamarin-forms/user-interface/webview/#Navigation - Gerald Versluis
但是当用户点击片段链接时,表单无法前进或后退。 - Jacky Shek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接