javascript - 我试图在鼠标单击 CEFSharp 中的 Winforms RichTextbox 时获取 html 标记名称,但将 null 作为异常

我试图在鼠标单击时获取 Selected Html 标记元素。我正在使用 CEFSharp。例如,当客户端单击 H1 或 P 标记时,选定的 HTML 标记元素名称将在 Richtextbox 上。


System.NullReferenceException: 'Object reference not set to an instance of an object.'

CefSharp.JavascriptResponse.Result.get returned null.

这是我的 demo.html 文件

<!DOCTYPE html>

<html lang="en" xmlns="">
    <meta charset="utf-8" />
    <h1>Hello World</h1>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the
    industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and
    scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into
    electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of
    Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus
    PageMaker including versions of Lorem Ipsum.
<script src=""></script>

这是我的脚本文件。我正在使用 jquery。

$('*', document.body).click(function (event) {

这是我的 winforms C# 代码

public partial class Form1 : Form
        public ChromiumWebBrowser chromeBrowser;

        public Form1()
        public void InitializeChromium()
            CefSettings settings = new CefSettings();
            chromeBrowser = new ChromiumWebBrowser();
            chromeBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
            chromeBrowser.JavascriptObjectRepository.Register("dotnetMessage", new DotNetMessage(),BindingOptions.DefaultBinder);
            // Add it to the form and fill it to the form window.
            chromeBrowser.Dock = DockStyle.Fill;
            chromeBrowser.LoadingStateChanged+= OnLoadingStateChanged;

        private async void OnLoadingStateChanged(object? sender, LoadingStateChangedEventArgs e)
            var scriptJsPath = string.Format(@"{0}\script.js", Application.StartupPath);
            var script = File.ReadAllText(scriptJsPath);
            // var script = @"(function(){return 'HALLOOOO'})();"; // this is working

            var result = await chromeBrowser
                .ContinueWith(t => t.Result.Result.ToString());
            richTextBox1.Invoke(new Action(() => { richTextBox1.Text = result; }));

        private void Form1_Load(object sender, EventArgs e)
            String page = string.Format(@"{0}\demo.html", Application.StartupPath);

    public class DotNetMessage
        public string Show(string message)
            return message;


您的脚本可能会评估为 jQuery 对象,该对象非常复杂,无法解析/表示为 .Net 对象。因此,在这种情况下,预计会返回 null。

应使用标记名称调用 DotNetMessage.Show 方法,您应更新 show 方法以更新richTextBox1.Text 属性。

对于简单的消息传递,我建议使用 CefSharp.PostMessage 而不是绑定对象。有一个例子