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
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值