Dou Safrano
Dou Safrano

Reputation: 11

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

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?

Upvotes: 1

Views: 4488

Answers (1)

amaitland
amaitland

Reputation: 4409

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
}

Upvotes: 6

Related Questions