Search code examples
c#vb.netwebview2addhandler

How to stop Webview2 reloading website after NavigationCompleted event. VB.NET C#


I have a module that opens a Form with a Webview2 browser. The Webview2 control then uses the user username and password (which he entered earlier into two textboxes) to log into a website and loads through a few links to a specific webpage where the user can search for customers, www.login.ca/search. After the user enters a name and clicks on the search button the next page load for a second but then loads the www.login.ca/search page again. I just want to user to be able to continue through the page further without the browser reloading "login.ca/search" webpage.

I have this:

Imports System.Windows.Interop
Imports Microsoft.Web.WebView2.Core

Module SearchForCustomer

Public Sub CheckCustomer()
    WebviewForm.Show()
    OpenAndLogIn()
End Sub

Public Sub OpenAndLogIn()

    'Open webpage and log in
    Dim Loginwebaddress As String = "https://www.login.ca"
    WebviewForm.WebView21.Source = New Uri(Loginwebaddress)

    AddHandler(WebviewForm.WebView21.NavigationCompleted), AddressOf FirstPageWebView
End Sub

Private Async Sub FirstPageWebView(ByVal sender As Object, ByVal e As CoreWebView2NavigationCompletedEventArgs)
    Dim msg = TextBox1.Text 'Username
    Dim msg2 = TextBox2.Text 'password

    Await WebviewForm.WebView21.ExecuteScriptAsync($"document.getElementById('LoginUN').value = '{msg}';")
    Await WebviewForm.WebView21.ExecuteScriptAsync($"document.getElementById('Login1PW').value = '{msg2}';")
    Await WebviewForm.WebView21.ExecuteScriptAsync($"document.getElementById('Login1_DoLogin').click();")

    AddHandler(WebviewForm.WebView21.NavigationCompleted), AddressOf LoginWebpageLoaded
End Sub

Private Sub LoginWebpageLoaded

    'Load the search for customer page
    Dim Loginwebaddress As String = "https://www.login.ca/search"

    WebviewForm.WebView21.Source = New Uri(Loginwebaddress)

End Sub

Solution

  • The first line of FirstPageWebView should remove the handler again, since it should only be used once.

    When you call AddHandler you acutually have 2 handlers registered, and they will run both on every NavigationCompleted event.

    (I don't know Vb.Net so this code might be wrong, but I hope you get the idea:

    Private Async Sub FirstPageWebView(ByVal sender As Object, ByVal e As CoreWebView2NavigationCompletedEventArgs)
        RemoveHandler(WebviewForm.WebView21.NavigationCompleted), AddressOf LoginWebpageLoaded
        ......... more code .........