D
D
Dmitry Afonchenko2015-10-13 01:06:13
C++ / C#
Dmitry Afonchenko, 2015-10-13 01:06:13

How to make code run after page loads in C# webBrowser element?

Good evening, everyone, comrades, such a question has arisen, you need to get an access_token to authenticate the VKontakte application. I send a specific request for access rights, the user confirms it, after which there is a redirect to the page in the address bar, which contains the access_token. The code below is now running before the redirect happens and therefore gets the wrong string, so it doesn't get the access_token. How to be in this situation?

public string reqToken(string Scope, WebBrowser webBrowserAuth)
        {
            using (var req = new HttpRequest())
            {
                req.UserAgent = Http.ChromeUserAgent();
                CookieDictionary cookies = new CookieDictionary(false);
                req.Cookies = cookies;

                String Data = req.Get(String.Format("https://oauth.vk.com/authorize?client_id={0}&scope={1}&display=page&response_type=token&redirect_uri=https://oauth.vk.com/blank.html", appID, Scope)).ToString();
                
                // Вот это действие нужно выполнить только после редиректа
                Uri u = new Uri(req.Response.Address.ToString());
                webBrowserAuth.Url = u;
 
                char[] simbol = { '=', '&' };
                string[] str = webBrowserAuth.Url.ToString().Split(simbol);

                string token = str[1];

                return token;
            }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
littleguga, 2015-10-13
@Indermove

Add the webBrowser_DocumentCompleted event and get access_token in it.
For example, like this:

string vkUrl = webBrowser1.Url.AbsoluteUri;
      if (vkUrl.Contains("access_token"))
      {
        var match = Regex.Match(vkUrl, @"=(.*?)&");
        vkAT = match.Groups[1].ToString();
        match = Regex.Match(vkUrl, @"&user_id=(.*)");
        vkUserId = match.Groups[1].ToString();
        string[] dataNames = {"UID", "AT"};
        string[] data = {vkUserId, vkAT};
      }

Detailed article about Async/await , so 1 (although they also offer it via Event), so 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question