防止 WebBrowser 控件在设置 contentEditable 时自动添加 <A> 标记

Prevent WebBrowser Control from automatically adding <A> Tag when contentEditable is set

我使用 WebBrowser 控件并在其中包含如下文本:

some text https://www.example.com some text.

这是我添加文本并启用网络浏览器编辑内容的代码:

public partial class Form1 : Form
{
    private HTMLBody _body;

    public Form1()
    {
        InitializeComponent();
        webBrowser1.Navigate("about:blank");
    }

    private void webBrowser1_DocumentCompleted(object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        _body = ((HTMLBody)((HTMLDocument)webBrowser1.Document.DomDocument).body);
        _body.contentEditable = true.ToString();
        _body.innerHTML = "some text https://www.example.com some text";
    }
}

如果我 运行 它并更改了 link 的一部分(为了输入其他内容而不是 'example.com' 并且失去了焦点)然后它会自动在我的周围添加标签 <a> link。你可以在 innerHTML 属性 中看到它。但这对我来说是错误的。

有没有办法避免这种行为? 非常感谢!

您可以在文档中关闭自动检测url。为此,在为正文设置新内容后,在 DocumentCompleted evnet 中添加以下代码行:

webBrowser1.Document.ExecCommand("AutoUrlDetect", false, false);

您还可以在不添加对 mshtml.dll 的引用的情况下使内容可编辑。为此,您可以简单地使用:

this.webBrowser1.DocumentText = @"<HTML><BODY contentEditable=""true""></BODY></HTML>";