检测 WPF WebBrowser 中的 URL 更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19184336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:47:14  来源:igfitidea点击:

Detect URL change in WPF WebBrowser

c#.netwpfurlwebbrowser-control

提问by Marcin Limanski

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.browserLinkCheckas the target URL, and opens the WebBrowser instance.

在 WPF 中使用 WebBrowser,如何检查 URL 中的更改?有没有可以在达到条件时触发的偶数?下面我有一个按钮事件,它将 设置App.browserLinkCheck为目标 URL,并打开 WebBrowser 实例。

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

回答by Omri Btian

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

您可以使用Navigating事件来检测甚至取消 webBrowser 中的导航。

You can save the current WebBrowserurl and compare it with the new one received in the Navigatingevent and compare them to see if it has changed.

您可以保存当前的WebBrowserurl 并将其与Navigating事件中收到的新 url 进行比较,然后比较它们是否已更改。

    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;
        }
    }

回答by Marcin Limanski

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

感谢@Omribitan 示例,我通过调整代码设法克服了 NullException 问题:

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
    }
}