Determine if WPF WebBrowser is loading a page

2019-08-10 08:25发布

问题:

I have a WPF System.Windows.Controls.WebBrowser control in a Window. A user can enter information and hit a submit button into the webpage displayed by the WebBrowser. After the page posts back it uses a scripting object to communicate with my application. I need to make sure that once the submit button has been pressed, the form doesn't close or otherwise stop waiting for the web page to post back. It would be great if I could check the state of the WebBrowser or its document via a property like "IsLoading" and cancel any actions if it is loading. I didn't see anything like that so I was thinking of setting a flag on the Navigating event and unsetting it on the Navigated or LoadCompleted event, but there is a case where I click a link on the web page (tied to javascript, it doesn't go to a new page) where Navigating is fired, but Navigated and LoadCompleted never fire. Is there a way to determine the state of the browser on demand?

回答1:

As per MSDN if the Navigating event gets invoked then the Navigated Event will also get fired unless you explicitly Cancel the navigation. I tried the below code-snippet it seems to be working fine. (i.e) whenever the Navigated event is getting fired following Navigating event.

void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        browser = new WebBrowser();
        browser.Navigate(new Uri("http://www.google.com"));
        browser.Navigating += new NavigatingCancelEventHandler(browser_Navigating);
        browser.Navigated += new NavigatedEventHandler(browser_Navigated);
    }

    void browser_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        Console.WriteLine("Loading Webpage !!");
    }

    void browser_Navigated(object sender, NavigationEventArgs e)
    {
        Console.WriteLine("Webpage Loaded !!");
    }

If this is not what you are looking for, then provide the webpage URL in which you are facing the issue.



回答2:

No, there does not appear to be a way to query the WPF browser's status on demand. I settled on my original idea of setting my own flag in the Navigating event handler and unsetting it in the Navigated event handler. It was not working reliably for me because there was a script that canceled navigation (javascript:void(0)).