【问题标题】:Wait for a page to load with CefSharp等待页面加载 CefSharp
【发布时间】:2017-09-13 16:06:12
【问题描述】:

首先,我是 C# 的新手,在学习 Cefsharp + javascript 的过程中,请尝试评论您认为有必要的任何解决方案,以免我问愚蠢的问题。

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

我认为解决方案是“NavStateChanged”,但我收到以下 C# 错误: "ChromiumWebBrowser 不包含 'NavStateChanged' 的定义"

谁能指出我正确的方向或给我一个sn-p?我不是要你为我写完整的东西,但我真的迷失了,我同时学习 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
    }

【问题讨论】:

标签: c# cefsharp chromium-embedded pageload


【解决方案1】:

对于其他想知道我做过同样事情的人:是的,它们已经过时了,感谢您提供链接 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');");
  }
};

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-02
      • 2023-03-26
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 2020-01-04
      相关资源
      最近更新 更多