CefSharp 新版本 C# JS 交互方式

13. How do you handle a Javascript event in C#?

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 the threads pool, to access your UI thread
        //You can cast sender to ChromiumWebBrowser
    //use Control.BeginInvoke/Dispatcher.BeginInvoke
}

你可能感兴趣的:(c#,cefsharp)