Found a way around Request BrowserId : 1 not found

Having problems with building or using the CefSharp .NET binding? Ask your CEF-related questions here. Please ask general usage questions on StackOverflow.

Moderator: amaitland

Found a way around Request BrowserId : 1 not found

Postby andla71 » Tue Nov 07, 2023 5:01 pm

So this post is to help amaitland with this bug:

I had issues with this bug with my automation software. Not sure if you can relate to this feeling but if things are not perfect it will come back and bite you even harder. So I finally told myself I need to deal with this somehow. So I found this thread talking about this issue.
https://github.com/cefsharp/CefSharp/issues/4621

Reproducing the error
I know Alex is very busy so in order to help him out I found the perfect place to reproduce the error:
Open this url in CefBrowser
https://chat.openai.com/

Then click Login.
Here you get 2 redirects.

On the login page you try to retrieve HTML.

I use this HORRIBLE code to do it. (Please forgive me Alex)
Code: Select all
    string script = @"

                var nodelist = document.querySelectorAll( `" + arg2 + @"` );
                var elements = [];
                for(var i=0; i <nodelist.length; i++)
                {
                    if(nodelist[i].outerHTML.includes(`" + arg3 + @"`))
                    {
                        var getall = `" + getall.ToString() + @"`;

                        elements.push(nodelist[i].outerHTML);
                        if(getall == 'False')
                        {
                            break;
                        }

                    }
                }

                elements;
            ";

    if (CheckItemLocalOrGlobal(arg4))
    {
        // Use await to asynchronously wait for the script evaluation to complete
        var response = await frame.EvaluateScriptAsync(script);

        if (response.Success && response.Result != null)
        {
            // Cast the result to a List<string> as it represents a list of HTML strings
            var data = ((List<object>)response.Result).Cast<string>().ToList();

            // Marshal the update back to the UI thread if necessary
            form1.Invoke(new MethodInvoker(() =>
            {
                if (!getall)
                {
                    SetTextLocalOrGlobal(arg4, data.FirstOrDefault());
                }
                else
                {
                    foreach (string element in data)
                    {
                        AddTextLocalOrGlobal(arg4, element + "\r\n");
                    }
                }
            }));
        }
    }
}
catch (Exception ex)
{
    CheckLDM("GetKnownHtml: Exception'" + ex.Message + "' ");
}


How to get around the problem?
Well the solution is even more embarrassing :D
but it should give some guidance to further narrow things down.
So I basically setup a RequestHandler:
Code: Select all
            int tabidx = int.Parse(Thread.CurrentThread.Name);
            ChromiumWebBrowser chrome = tabControl1.TabPages[tabidx].Controls[0] as ChromiumWebBrowser;



            if (chrome.RequestHandler == null)
            {
                chrome.RequestHandler = customRequestHandler;
            }
            var handler = (CustomRequestHandler)chrome.RequestHandler;
            SetTextLocalOrGlobal(arg2, handler.RedirectUrl);


The Request Handler shows all the stream of urls that the browser wants to load and we can take control of how the browser reacts.
Code: Select all
      public class CustomRequestHandler : CefSharp.Handler.RequestHandler
      {
          public string CurrentUrl { get; set; }

          public string RedirectUrl { get; set; }
          public bool PreventRedirect { get; set; }
          public bool StepRedirect { get; set; }
          protected override bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
          {


             
              if (StepRedirect && !request.Url.Equals(RedirectUrl, StringComparison.OrdinalIgnoreCase))
              {

                 
                  RedirectUrl = request.Url;
                  chromiumWebBrowser.LoadUrl("about:blank");

                  //chromiumWebBrowser.LoadUrl("about:blank");

                  //Thread.Sleep(2000);
                  //return true;  // Cancel the navigation
              }

              if (CurrentUrl == null)
              {
                  CurrentUrl = request.Url;
              }

              if (PreventRedirect && frame.IsMain && !request.Url.Equals(CurrentUrl, StringComparison.OrdinalIgnoreCase))
              {
                  return true;  // Cancel the navigation
              }
             

              return base.OnBeforeBrowse(chromiumWebBrowser, browser, frame, request, userGesture, isRedirect);
          }
      }

So with the section where I use StepRedirect I want to take control of the browser when there is any difference between the old url and the new url.
Then I simply do a load url "about:blank" to just tell the browser to load this instead. I'm not sure exactly what happens with this hack but it works. (It's not funny! :D )
You can see that I store the new url inside RedirectUrl so that I can retrieve it with
Code: Select all
 handler.RedirectUrl

Now I can carefully load every url one at a time with browser.load("https://ww")
When I do that I can retrieve the HTML and I don't get this error.
I'm sure there is a way to refine this hack to make it automagically but that is up to Alex the real wizard. I'm just an apprentice level 3. Alex is Level 999. ;)

I hope this help.
andla71
Techie
 
Posts: 28
Joined: Sat Oct 31, 2020 12:19 pm

Re: Found a way around Request BrowserId : 1 not found

Postby amaitland » Fri Nov 10, 2023 2:53 pm

Apricate the effort. Thanks. Unfortunately it's not a complete reliable example that reproduces the problem.

What I'm really looking for us a unit test that reliably reproduces the problem. If that's something you can help out with then see https://github.com/cefsharp/CefSharp/is ... 1802991766 for details.

There are cases where a `not found it's likely the browser is already closed` error are expected.

Code: Select all
browser.Load(url);
await browser.EvaluateScriptAsPromiseAsync(script);


Calling `Load/LoadUrl` then immediately trying to eval some javascript is not valid as the code doesn't wait for the browser to finish loading the page.

This is a common mistake, you need to ask yourself, am I waiting for the page to finish loading before attempting to eval javascript?
Maintainer of the CefSharp project.
amaitland
Virtuoso
 
Posts: 1292
Joined: Wed Jan 14, 2015 2:35 am

Re: Found a way around Request BrowserId : 1 not found

Postby andla71 » Fri Nov 10, 2023 7:52 pm

Do you think that the redirects that is taken care of on the backend (the behind the scenes machinery) is not letting the pages finish in a correct manner thus causing the error?

BTW even if it is not a completely reliable example it is a very basic and simple example that causes the error consistently every time. From my experience as a novice programmer is that fixing one thing if you have a very basic and extracted to the core example, in many cases will fix all problems related to that issue.
andla71
Techie
 
Posts: 28
Joined: Sat Oct 31, 2020 12:19 pm

Re: Found a way around Request BrowserId : 1 not found

Postby amaitland » Fri Nov 10, 2023 8:24 pm

If you are attempting to eval your javascript when a redirect is happening then yes. If that's the case then this isn't a bug in `CefSharp`, your code probably needs restructuring to wait for page loads correctly.

BTW even if it is not a completely reliable example it is a very basic and simple example that causes the error consistently every time. From my experience as a novice programmer is that fixing one thing if you have a very basic and extracted to the core example, in many cases will fix all problems related to that issue.


Whilst you maybe able to reliably reproduce the error, what you've provided is not a runnable/debuggable example.

If you are unable to provide a unit test then

- Fork https://github.com/cefsharp/CefSharp.MinimalExample on GitHub
- Clone your fork
- Modify one of the examples to reproduce your problem
- Remove any unnecessary code that's not required to reproduce the problem, spent a decent amount of time on this, remove anything that isn't strictly necessary
- Make sure all your changes are in a single commit (Squash all your changes into a single commit if required).
- Push your changes to your GitHub fork.
- Post a link to your fork.
Maintainer of the CefSharp project.
amaitland
Virtuoso
 
Posts: 1292
Joined: Wed Jan 14, 2015 2:35 am

Re: Found a way around Request BrowserId : 1 not found

Postby andla71 » Mon Nov 13, 2023 6:42 pm

I removed as much as I dared and I hope you approve.
https://github.com/andla71/CefSharp.Min ... e.WinForms

I forgot:
Run the app.
Click login button.
Then at the top I have a loooooong stretchy button that will try to run the javascript.
andla71
Techie
 
Posts: 28
Joined: Sat Oct 31, 2020 12:19 pm

Re: Found a way around Request BrowserId : 1 not found

Postby andla71 » Tue Nov 14, 2023 8:56 pm

Reading your post again I realize that I was a bit tired and what you said didn't click.
So I want to be clear that I do not try to run the javascript inside a redirect.
I run the javascript when the browser is finished and have loaded the login page.
Many of the resistance have died finding this information so May the force be with
you Master Amaitland.
andla71
Techie
 
Posts: 28
Joined: Sat Oct 31, 2020 12:19 pm


Return to CefSharp Forum

Who is online

Users browsing this forum: No registered users and 113 guests