【问题标题】:How to catch js button onclick event by CefShap on WinForms?如何在 WinForms 中通过 CefSharp 捕获 js 按钮 onclick 事件?
【发布时间】:2020-02-22 11:44:48
【问题描述】:

如何拦截在带有 CefSharp 浏览器控制器的 WinForms 下运行的 Html 文档中的按钮上的 js onClick,以便 C# 代码可以拦截此事件并在 .NET 环境中执行一些操作?

【问题讨论】:

  • 我看过所有视频、文档和维基。我无法解决这个问题,或者我没有完全理解工作的问题。所有过时方法和新方法的手册都没有在文档中绘制。我想要一个具体的代码示例,说明如何拦截按键点击事件,仅此而已:)。
  • 完整示例请参见github.com/cefsharp/CefSharp.MinimalExample/commit/…,这可以使用新的 PostMessage 功能大大简化。仅仅说您已经看过所有文档/视频并没有帮助,因为我不知道您实际阅读了什么,您需要提供链接并展示您已经尝试过的内容。
  • 问题已解决,感谢您的提示。这非常困难,因为这个例子只出现在这个提交中,它不在master分支中(一个点击的具体例子),而且里面有很多水,很难理解什么方法和它们的设置与此问题有关。最后,我设法在此操作期间组织了对 Click 事件的监视和触发 C# 代码,但它看起来非常复杂,并且文档没有以任何方式揭示这一点。在我看来,这么复杂的实现应该封装起来,应该给用户..
  • 这个答案怎么样?

标签: c# winforms web events cefsharp


【解决方案1】:

对于基本通信,您可以在 Javascript 中使用 CefSharp.PostMessage(message); 向 .Net 发送消息,触发 browser.JavascriptMessageReceived 事件。

// After your ChromiumWebBrowser instance has been instantiated (for WPF directly after `InitializeComponent();` in the control constructor).
// Subscribe to the following events
browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived;
browser.FrameLoadEnd += OnFrameLoadEnd;

public void OnFrameLoadEnd (object sender, FrameLoadEndEventArgs e)
{
  if(e.Frame.IsMain)
  {
    //In the main frame we inject some javascript that's run on mouseUp
    //You can hook any javascript event you like.
    browser.ExecuteScriptAsync(@"
      document.body.onmouseup = function()
      {
        //CefSharp.PostMessage can be used to communicate between the browser
        //and .Net, in this case we pass a simple string,
        //complex objects are supported, passing a reference to Javascript methods
        //is also supported.
        //See https://github.com/cefsharp/CefSharp/issues/2775#issuecomment-498454221 for details
        CefSharp.PostMessage(window.getSelection().toString());
      }
    ");
  }
}

private void OnBrowserJavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
    var windowSelection = (string)e.Message;
    //DO SOMETHING WITH THIS MESSAGE
    //This event is called on a CEF Thread, to access your UI thread
    //use Control.BeginInvoke/Dispatcher.BeginInvoke
}

【讨论】:

  • 直接摘自github.com/cefsharp/CefSharp/wiki/…,请查看那里是否有任何进一步的改进。欢迎进一步改进,将其设为community wiki,以便其他人可以为这个答案做出贡献。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 2013-12-10
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多