如何在Windows Form App中从JAVASCRIPT(它是HTML代码,我通过CefSharp调用)中调用C#函数
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;
}
}
JS调用的功能
public void Test(String message)
{
MessageBox.Show(message, "Test");
}
HTML代码,我需要在onclick事件中调用Test()
<span class="mySpan" onclick="<Some>.Test('It is working');"></span>
我尝试过的代码
内部InitialChromium函数
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
chromeBrowser.RegisterAsyncJsObject("boundAsync", new BoundObject());
BoundObject.cs
public class BoundObject
{
public void Test(String message)
{
MessageBox.Show(message, "Test");
}
}
HTML代码
<span class="mySpan" onclick="boundAsync.Test('It is working');"></span>
但这对我不起作用。请让我知道我在哪里错了?
谢谢!
答案 0 :(得分:2)
1.使用要调用的方法创建一个类
创建一个 CallbackObjectForJs 类,其中包含可从 javascript 调用的 showMessage 函数。
<audio id="my_audio" src="gallery/Welcome.MP3"></audio>
<script>
window.onload = function() {
document.getElementById("my_audio").play();
}</script>
2.注册JS对象
下一步是注册JS对象。这可以通过在 public class CallbackObjectForJs{
public void showMessage(string msg){//Read Note
MessageBox.Show(msg);
}
}
文件中添加以下代码来完成。
MainPage.xaml.cs
3.从 JavaScript 调用 C# 函数
接下来,只需从您的 javascript 代码中调用 C# 函数。
private CallbackObjectForJs _callBackObjectForJs;
public MainWindow()
{
InitializeComponent();
_callBackObjectForJs= new CallbackObjectForJs();
ChromiumWebBrowser.RegisterAsyncJsObject("callbackObj", _callBackObjectForJs);
}
注意:C# 函数的名称应该以小写字母开头。
替代解决方案,如<script>
callbackObj.showMessage("Hello World!");
</script>
给浏览器实例添加一个事件监听器:
@amaitland
从 javascript 调用 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
}
方法(该方法在 CefSharp.PostMessage
上下文中自动可用:
ChromiumWebBrowser