How to catch js button onclick event by CefShap on WinForms?

纵饮孤独 提交于 2021-01-05 07:26:37

问题


How can I intercept a js onClick on a button in an Html document that is running under WinForms with CefSharp browser controller so that C# code can intercept this event and do some actions already in .NET environment?


回答1:


For basic communication you can use CefSharp.PostMessage(message); in Javascript to send a message to .Net which triggers the browser.JavascriptMessageReceived event.

// 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
}


来源:https://stackoverflow.com/questions/60351835/how-to-catch-js-button-onclick-event-by-cefshap-on-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!