简体   繁体   中英

What is the right way to dispose a WebView page in Xamarin.Forms?

The problem

I have an app in Xamarin.Forms that opens a WebView after a login screen.

Each time the user logs out and in again, a new Page and ViewModel are created.

Inpecting the device via Chrome's Remote Devices I can still see the older WebViews.

For the navigation I use a custom NavigationService inpired by the Evolve App from a couple of years ago.

What I've tried so far

Disposing both the Page and it's ViewModel when poping the WebViews's Page.

This is the code that pops the WebView's Page and return to the Login Page

public async Task NavigateBackAsync(bool IgnoraNavegacao) { _isNavigating = true;

try
{
    /* Omitted for clarity */

    if (currentPage is IDisposable)
        ((IDisposable)currentPage).Dispose();

    if (!(currentPage.GetType() == _homeViewModel))
    {
        await navigationPage.PopAsync();
    }
}
finally
{
    _isNavigating = false;
}

The Dispose of the Page, where Browser is my WebView defined in XAML:

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

public virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        Browser = null;

        var bindingContext = BindingContext as IDisposable;
        bindingContext?.Dispose();

        BindingContext = null;
    }
}

And this is the Dispose of the ViewModel:

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        OnNavigatingCommand = null;
        OnNavigatedCommand = null;
        OnBackButtonPressedCommand = null;
    }
}

And this is what I see on Chrome after logging in four times:

Chrome远端装置

Interestingly enough the first time it "works": after I log out and log in again only one WebView is seen on Chrome.

Please let me know if any more information is needed.

Any pointers to the right direction would be greatly appreciated.

When second to this page.If you didn't create a webview using the singleton mode, then you won't get the previous webview.

So there are two options:

One:

Using the singleton mode,when next to this page,you can get the old webview.

Two:

When leaving the page, you can set the old instance of the WebView to be null .

In OnDisappearing method:

 protected override void OnDisappearing()
    {
        base.OnDisappearing();
        if (null != webView)
        {
            webView = null;
        }
    }

Or before Navigation.PopAsync() do it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM