
CefSharp浏览器js调用C#方法?如果我们需要通过JavaScript与.NET交互而不评估任何脚本(例如,处理某些事件),则可以将.NET对象注入JavaScript端。
CefSharp浏览器js调用C#方法
这种方法的局限性在于,应在初始化浏览器之前在CefSharp浏览器中注册.NET对象。因此,我们不能使用XAML编辑器来创建浏览器-在这种情况下,浏览器将在我们注入.NET对象之前初始化,并且会引发异常。
因此,在本教程中,我们将直接从C#代码创建一个浏览器。但是,在标记中我们仍然需要做一件事-设置将用作浏览器容器的网格名称。
MainWindow.xaml将如下所示:
<Window x:Class="InjectDotNetToJavaScript.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:InjectDotNetToJavaScript"
mc:Ignorable="d"
Title="InjectDotNetToJavaScript" Height="350" Width="525">
<!--Set the name of the root grid-->
<Grid Name="MainGrid">
</Grid>
</Window>
现在我们需要创建.NET类,该类将被注入JavaScript端。稍后,我们将使用JavaScript调用其方法。此类的单个方法将仅显示消息框,其中包含通过参数传递的文本。您可以将其放在MainWindow.xaml.cs中的MainWindow类附近:
public class DotNetMessage
{
public void Show(string message)
{
MessageBox.Show(message);
}
}
然后让我们实现MainWindow行为:
public partial class MainWindow : Window
{
private ChromiumWebBrowser Browser;
public MainWindow()
{
InitializeComponent();
//Create the browser
Browser = new ChromiumWebBrowser();
//Inject the new instance of .NET object into the CefSharp
Browser.RegisterJsObject("dotNetMessage", new DotNetMessage());
//After the browser is initialized load the HTML file which will call registered .NET object
Browser.IsBrowserInitializedChanged += (sender, args) =>
{
if (Browser.IsBrowserInitialized)
{
Browser.LoadHtml(File.ReadAllText("index.html"));
}
};
//Add browser to the root grid of the window
MainGrid.Children.Add(Browser);
}
}
最后一步是创建一个HTML文件,该文件将使用JavaScript调用注册的.NET对象。下面提供了index.html的源代码。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
//This function gets the text from the input and passes it
//into the Show method of the registered .NET object
function ShowDotNetMessage() {
var message = document.getElementById('textbox').value;
dotNetMessage.show(message);
}
</script>
<!--This input contains the text we want to pass into the .NET object-->
<input type="text" id="textbox"/>
<!--This button call the JavaScript method which passes the input text to the .NET object-->
<button onclick="ShowDotNetMessage()">Show message</button>
</body>
</html>
生成并启动应用程序后,在加载的窗口中,我们可以将要在消息框中显示的文本输入到输入中,然后按“显示消息”按钮。键入的文本将由JavaScript端处理,传递给.NET对象,.NET对象将使用键入的文本调用MessageBox.Show方法。
结果的屏幕截图如下。


【江湖人士】(jhrs.com)原创文章,作者:江小编,如若转载,请注明出处:https://jhrs.com/2021/40319.html
扫码加入电报群,让你获得国外网赚一手信息。
文章标题:CefSharp浏览器js调用C#方法