使用 CefSharp 等待页面加载

Wait for a page to load with CefSharp

首先,我是 C# 的新手,正在学习 Cefsharp + javascript,所以请尝试评论您认为必要的任何解决方案,这样我就不会问愚蠢的问题了。

我试图等到页面用 Cefsharp 完成加载来执行我的代码,我已经尝试了在其他 Whosebug 问题上找到的几种解决方案/github 但没有成功。

我认为解决方案是 "NavStateChanged" 但我收到 C# 错误: "ChromiumWebBrowser does not contain a definition for 'NavStateChanged'"

任何人都可以指出正确的方向或给我一个片段吗?我不是要你为我写完整的东西,但我真的迷失在这里,我正在学习 C#、Cefsharp 和 javascript,而且很好......它势不可挡。

这是我在网上寻找解决方案时找到的代码,它也与很多 github 参考相匹配,但似乎不起作用:/

EventHandler<NavStateChangedEventArgs> handler = null;
handler = (sender, args) = > {

    //TODO : show a loading gif until the page load completes

    //Wait for while page to finish loading not just the first frame
    if (!args.IsLoading)
    {
        chromeBrowser.NavStateChanged -= handler;

        MessageBox.Show("The page has completed loading", "Load completed", 
                        MessageBoxButtons.OK);
        //TODO : once load complete show the actual page
    }

对于其他想知道我所做的同样事情的人:是的,它们已经过时了,谢谢 link amaitland!

https://github.com/cefsharp/CefSharp/wiki/General-Usage#handlers

这些似乎是与我相关的所有 3 个正确的加载状态:

browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();

public class RenderProcessMessageHandler : IRenderProcessMessageHandler
{
  // Wait for the underlying `Javascript Context` to be created, this is only called for the main frame.
  // If the page has no javascript, no context will be created.
  void IRenderProcessMessageHandler.OnContextCreated(IWebBrowser browserControl, IBrowser browser, IFrame frame)
  {
    const string script = "document.addEventListener('DOMContentLoaded', function(){ alert('DomLoaded'); });";

    frame.ExecuteJavaScriptAsync(script);
  }
}

//Wait for the page to finish loading (all resources will have been loaded, rendering is likely still happening)
browser.LoadingStateChanged += (sender, args) =>
{
  //Wait for the Page to finish loading
  if (args.IsLoading == false)
  {
    browser.ExecuteJavaScriptAsync("alert('All Resources Have Loaded');");
  }
}

//Wait for the MainFrame to finish loading
browser.FrameLoadEnd += (sender, args) =>
{
  //Wait for the MainFrame to finish loading
  if(args.Frame.IsMain)
  {
    args.Frame.ExecuteJavaScriptAsync("alert('MainFrame finished loading');");
  }
};

在某些情况下,我会等待特定元素出现,而不是等待浏览器完成加载。所以如果你还想等待页面加载完成,可以试试@Royals的方式