Marcin Limanski
Marcin Limanski

Reputation: 13

Detect URL change in WPF WebBrowser

Using the WebBrowser in WPF, how can I check for a change in the URL? is there an even that can be fired when it hits a condition? Below I have a button event that sets the App.browserLinkCheck as the target URL, and opens the WebBrowser instance.

private void btNextWelcomeNewHire_Click(object sender, System.Windows.RoutedEventArgs e)
{
    App.borwserLinkCheck = App._PasswordSyncWebLink;
    webBrowser.Navigate(new Uri(App.borwserLinkCheck));
    //webBrowser.Navigating += webBrowser_Navigating;
}

Upvotes: 1

Views: 6552

Answers (2)

Marcin Limanski
Marcin Limanski

Reputation: 13

Thanks to @Omribitan example I have managed to over come the NullException issue by adjusting the code:

private String targetStringToCompare = "www.example.com";

void myBrowser_Navigating(object sender, NavigatingCancelEventArgs e)
{
    if (e.Uri.AbsoluteUri.ToString() == targetStringToCompare)
    {
        // Do something when the change will be detected
    }
}

Upvotes: 0

Omri Btian
Omri Btian

Reputation: 6547

You can use Navigating event to detect or even cancel navigation in the webBrowser.

You can save the current WebBrowser url and compare it with the new one received in the Navigating event and compare them to see if it has changed.

    private Uri currentUri;

    void myBrowser_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        if (currentUri.AbsolutePath != e.Uri.AbsolutePath)
        {
            // Url has changed ...

            // Update current uri
            currentUri = e.Uri;
        }
    }

Upvotes: 4

Related Questions