You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CefSharp WinForms中JS调用VB.NET函数失败及双向交互问题

CefSharp WinForms中JS与VB.NET交互问题解决

一、JS调用VB.NET函数无反应的解决方法

你的代码核心问题是JS调用的方法名称与VB.NET类中的方法不匹配,同时可优化注册逻辑确保稳定性:

  1. 修正方法名称匹配问题
    你在JS中调用的是hello.show("Hello World"),但VB.NET的DotNetMessage类中定义的方法是ShowMsg,CefSharp默认区分大小写,导致无法找到对应方法。

    • 方案1:修改JS代码,调用正确的方法名:
      <head>
          <script>
      function ShowDotNetMessage(){
          hello.showMsg("Hello World");
      }
          </script>
      </head>
      <input type="button" id="myButton" onclick="ShowDotNetMessage();" value="Click Me">
      
    • 方案2:修改VB.NET类的方法名,与JS调用一致:
      Public Class DotNetMessage
          Public Sub Show(Message As String)
              MessageBox.Show(Message)
          End Sub
      End Class
      
  2. 优化对象注册逻辑
    注册时明确指定要暴露的方法,避免潜在问题:

    ' 对应方案1的方法名
    browser.JavascriptObjectRepository.Register("hello", New DotNetMessage(), False, {"ShowMsg"})
    ' 或者对应方案2:
    ' browser.JavascriptObjectRepository.Register("hello", New DotNetMessage(), False, {"Show"})
    
  3. 确保注册时机正确
    将对象注册放在IsBrowserInitializedChanged事件中,确保浏览器初始化完成后再注册:

    Private Sub IsBrowserInit(sender As Object, e As EventArgs)
        ' 先注册对象,再加载页面
        browser.JavascriptObjectRepository.Register("hello", New DotNetMessage(), False, {"ShowMsg"})
        browser.Load("index.html")
    
        If browser.JavascriptObjectRepository.IsBound("hello") Then
            MessageBox.Show("Bound")
        Else
            MessageBox.Show("Not Bound")
        End If
    End Sub
    

二、VB.NET调用JS函数的实现方法

在CefSharp中,通过ExecuteScriptAsync方法可以实现VB.NET调用JS函数,支持直接调用和异步获取返回值:

  1. 直接调用JS函数或代码片段

    ' 示例:在VB.NET按钮点击事件中调用JS函数
    Private Sub CallJSFunction_Click(sender As Object, e As EventArgs) Handles CallJSFunction.Click
        ' 调用已定义的JS函数
        browser.ExecuteScriptAsync("ShowDotNetMessage();")
        ' 直接执行JS代码
        browser.ExecuteScriptAsync("alert('这是来自VB.NET的弹窗');")
    End Sub
    
  2. 异步获取JS执行结果
    如果需要获取JS执行的返回值,使用异步等待方式:

    Private Async Sub GetJSResult_Click(sender As Object, e As EventArgs) Handles GetJSResult.Click
        Dim response = Await browser.ExecuteScriptAsync("return 'JS执行结果:' + (100 + 200);")
        If response.Success Then
            MessageBox.Show(response.Result.ToString())
        Else
            MessageBox.Show("JS执行失败:" & response.Message)
        End If
    End Sub
    

内容的提问来源于stack exchange,提问作者The Newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 16:43:18