Search code examples
c#webview2

Webview2 Navigation


Currently in Webview2 browser if navigated to a particular URL as written below

browser.Source = URL;

This triggers NavigatingStarting event asynchronously.

How can I trigger a synchronous call for each source being set to trigger the event?

Problem: I am keeping a bool variable to check for the if navigation triggered inside my application and resetting it at the end for the navigatingstarting event. since it is an asynchronous call it is resetting after the first call without the next call being inside my application.

void SetBrowserUrl(Uri value)
{
    m_bInsideNavigateCall = true;
    priorsWebBrowser.Source = value;
}
    
void priorsWebBrowser_NavigationStarting(object sender, 
    CoreWebView2NavigationStartingEventArgs e)
{
    if(m_bInsideNavigateCall)
    {
        e.Cancel = false;
        m_bInsideNavigateCall = false; // Reset for next inside call
    }
    else
    {
        e.Cancel = true;
    }
}

Here the issue is if call SetBrowserUrl twice. Navigate starting cancels the second call made because it is not synchronous


Solution

  • I have created a list of strings.

    List<String> insideNavigatingURLS; //Class level variable
    

    Just before calling web-browser to navigate, I add the URL to list.

      internalURLs.Add(uri.AbsolutePath.ToLower());                     
      webBrowser.Source = uri; 
    

    In the NavigationStarting Event added a check to see if list contains the navigation url if it doesn't then will cancel the request.

    void webBrowser_Navigating(object sender, CoreWebView2NavigationStartingEventArgs e)
    {
        if (!internalUrls.Contains(e.Uri))  
        {
            e.Cancel = true; 
        }
        else
        {                
            internalUrls.Remove(e.Uri);
            e.Cancel = false;
        }
    } 
    

    So when back or forward navigation is triggered, the list doesn't contain a URL and the navigation request is cancelled