Xamarin Forms - making webview go back

12,785

Solution 1

Edit your code like this. First wrap your MainPage in a NavigationPage to make the toolbar visible.

It basically comes down to create a variable to be able to access your WebView easier.

Then create a button in you ToolbarItems collection which can trigger an event. And in that event you can call the already available GoBack() method on the WebView.

You probably want to check out the Xamarin documentation on the WebView, it is probably a good idea to check if you can actually go back with the CanGoBack property.

Note that I have assigned a BackIcon.png you can replace it with null or your own icon of course. Also the code hasn't been tested, this is just out of the top of my head so maybe there are missing some semi-colons or stuff.

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}
            };
        }
    }
}

Solution 2

The answer by Gerald Versluis is great. Based on that, I would like to share how my code looks like after I tried to solve the following issues:

  • Tried to implement the toolbar and webview in XAML (using VS2017)
  • Hiding toolbar when front page is displayed (no need for back)
  • Overriding the device back button

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 "...";
        }
    }
}

Solution 3

Try following steps: Add Navigated event in WebView object

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

Then define following function:

public void WebViewPage_Navigated(object sender, WebNavigatedEventArgs e)
{
    WebNavigationResult result = e.Result;            
    if(result.Equals(WebNavigationResult.Success)){
        currentUrl = e.Url;
       history.Add(currentUrl);
    }            
}

Now you can bind 'Forward' and 'Prev' element based on history list count and current element (if moved to back, then add to forward list). Hope this helps.

Share:
12,785
Duggan
Author by

Duggan

Updated on July 26, 2022

Comments

  • Duggan
    Duggan almost 2 years

    Morning all,

    I am working on a little crossplatform webview project in Xamarin.Forms. I have the webview working but I want to add in a toolbar which has a Back and Forward buttons.

    I tried a number of different ways but nothing seems to be working particularly well. I tried to implement this feature by following this guys post Navigation Toolbar

    I will attach my code below and if someone could give me a hand with this or a solution that would be great!

    And if this question has already been answered previously by another user then I apologize.

    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"
                        }
                    }
                };
            }
        }
    }
    

    Looking forward to getting an answer to this as ive been stuck on it for quite awhile now.

    Kind regards

  • Gerald Versluis
    Gerald Versluis over 8 years
    Why would you want to do this? The WebView has default GoBack and GoForward methods. See the Xamarin documentation here; developer.xamarin.com/guides/cross-platform/xamarin-forms/…
  • Duggan
    Duggan over 8 years
    I have added in that code there and it still isnt going back to the previous page. Also Im testing on a Android emulator but the toolbar that I want on top of the screen isnt showing up at all?
  • Duggan
    Duggan over 8 years
    So i got the toolbar working I think. I just added in public App() { // The root page of your application MainPage = new NavigationPage(new WebPage()); } But now the WebView isnt showing up. Any ideas? I read somewhere that you can only have one item on each ContentPage, could this be the issue?
  • Gerald Versluis
    Gerald Versluis over 8 years
    Try giving your WebView a WidthRequest and HeightRequest
  • Duggan
    Duggan over 8 years
    So I have tested it a few times and it seems to work...every now and again. By that I mean, I have to have the emulator turned off then run the program then turn it back on and it works perfectly after that. I dont know if its just a problem with the emulator or what. I'll have to do a few more tests on my device later tonight. If you have ever come across something like this before please let me know :) I will keep you update later when I find out if its just an emulator issue or not.Thanks for helping!
  • Gerald Versluis
    Gerald Versluis over 8 years
    If it has helped you to achieve the navigating back functionality please accept it as an answer :)
  • Jacky Shek
    Jacky Shek about 7 years
    But the forms cannot goForward or goBack when user clicked fragment links.
  • OverMars
    OverMars over 3 years
    Thank you for this, very helpful! All other solutions were missing a piece of the picture.