简体   繁体   English

在 Windows 窗体应用程序中使用 CefSharp 从 javaScript 调用 C# 函数

[英]Call C# function from javaScript using CefSharp in Windows Form App

How to call a C# function from JAVASCRIPT ( which is in HTML code, I am calling through CefSharp ) in Windows Form App如何从 Windows 窗体应用程序中的 JAVASCRIPT(在 HTML 代码中,我通过 CefSharp 调用)调用 C# 函数

CefSharp Components CefSharp 组件

public partial class Form1 : Form
{
    public ChromiumWebBrowser chromeBrowser;

    public Form1()
    {
        InitializeComponent();

        // Start the browser after initialize global component
        InitializeChromium();
    }

    public void InitializeChromium()
    {

        CefSettings settings = new CefSettings();

        settings.CefCommandLineArgs.Add("enable-media-stream", "1");

        Cef.Initialize(settings);

        chromeBrowser = new ChromiumWebBrowser("localhost/myproject/index.html");

        this.Controls.Add(chromeBrowser);

        chromeBrowser.Dock = DockStyle.Fill;
    }
}

Function To Be called By JS JS调用的函数

public void Test(String message)
{
    MessageBox.Show(message, "Test");
}

HTML Code Where I need to call Test() at onclick event我需要在 onclick 事件中调用 Test() 的 HTML 代码

<span class="mySpan" onclick="<Some>.Test('It is working');"></span>

Code I Tried,我试过的代码,

Inside InitializeChromium Function内部 InitializeChromium 函数

CefSharpSettings.LegacyJavascriptBindingEnabled = true;

chromeBrowser.RegisterAsyncJsObject("boundAsync", new BoundObject());

BoundObject.cs绑定对象.cs

public class BoundObject
{
    public void Test(String message)
    {
        MessageBox.Show(message, "Test");
    }
}

HTML CODE代码

<span class="mySpan" onclick="boundAsync.Test('It is working');"></span>

But It doesn't work for me.但这对我不起作用。 Please let me know where am I wrong?请让我知道我错在哪里?

Thanks in advance!提前致谢!

Here is a tutorial http://windowsapptutorials.com/wpf/call-c-sharp-javascript-using-cefsharp-wpf-app/这是一个教程http://windowsapptutorials.com/wpf/call-c-sharp-javascript-using-cefsharp-wpf-app/

1. Create a Class with the Method to be Invoked 1. 用要调用的方法创建一个类

Create a CallbackObjectForJs class that contains a showMessage function which would be invoked from javascript.创建一个 CallbackObjectForJs 类,其中包含将从 javascript 调用的 showMessage 函数。

public class CallbackObjectForJs{
    public void showMessage(string msg){//Read Note
        MessageBox.Show(msg);
    }
}

2. Register the JS object 2.注册JS对象

The next step is to register the JS object.下一步是注册JS对象。 This can be done by adding the following code in the MainPage.xaml.cs file.这可以通过在MainPage.xaml.cs文件中添加以下代码来完成。

private CallbackObjectForJs _callBackObjectForJs;
public MainWindow()
{
    InitializeComponent();
    _callBackObjectForJs= new CallbackObjectForJs();
    ChromiumWebBrowser.RegisterAsyncJsObject("callbackObj", _callBackObjectForJs);
}

3. Invoke the C# function from JavaScript 3. 从 JavaScript 调用 C# 函数

Next, simply invoke the C# function from your javascript code.接下来,只需从您的 javascript 代码调用 C# 函数。

<script>
    callbackObj.showMessage("Hello World!");
</script>

Note: The name of the C# function should start with a small letter.注意: C# 函数的名称应以小写字母开头。


Alternative Solution like suggested by @amaitland @amaitland建议的替代解决方案

Add an event listener to the browser instance:向浏览器实例添加事件侦听器:

public MainWindow()
{
    InitializeComponent();
    
    //Initialize ChromiumWebBrowser
    
    //Hook up event
    browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived;
}

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
    //You can cast sender to ChromiumWebBrowser
    //use Control.BeginInvoke/Dispatcher.BeginInvoke
}

From javascript, invoke the CefSharp.PostMessage method (Which is automatically available within the ChromiumWebBrowser context:从 javascript 调用CefSharp.PostMessage方法(该方法在ChromiumWebBrowser上下文中自动可用:

//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.
CefSharp.PostMessage(window.getSelection().toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM