简体   繁体   中英

How to get the URL of a WebBrowser control

        if (webBrowser1.Url.AbsoluteUri == "www.google.com")
        {
            label9.Text = webBrowser1.Url.AbsoluteUri;
        }

This is my current code. When I press the button to run this I get the error.

Object reference not set to an instance of an object.

And I don't know why it does that or how to fix it. Any help will be great.

Also It have to work in a timer so that it can be checked.

The Url Property will remain null untill the control is rendered so use this:

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
     if (webBrowser1.Url.ToString() == "www.google.com") {
          label9.Text = webBrowser1.Url.ToString();
     }
}

And in your button Click event add:

webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);

I thought id comment on this, I literally took your

"webBrowser1.Url.AbsoluteUri;"

and in my case im using a combotextbox so Double click your browser form and it will take you to the even handler, i just put

"combobox1.text= webBrowser1.Url.AbsoluteUri;"

and it works for me now. You got me on the time, but whatever you need to check, check for the combobox1.text or whatever you are using for your url's

if your browser1 is chromiumwebbrowser, then use

    string url = browser1.Address;

call the url and you will get it.

probably your webBrowser1.Url is null try below to get url

    string url = "";
    if (webBrowser1.Url != null)
    {
        url = webBrowser1.Url.AbsoluteUri;
    }
    if (url == "www.google.com")
    {
        label9.Text = url;
    }

Well you didn't set any url (no page is loaded inside the web browser). You could try this:

webBrowser1.Url = new Uri("http://www.google.com", UriKind.Absolute);

And get the url this way: webBrowser1.Url.ToString();

Wait for the page to load and the press then button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM