如何在WinForms上通过CefShap捕获js按钮onclick事件?

1 c# events winforms web cefsharp

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

ama*_*and 5

对于基本通信,您可以使用CefSharp.PostMessage(message); 在 Javascript 中发送消息到 .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
}
Run Code Online (Sandbox Code Playgroud)