【问题标题】:How to access Document property in Webview2 control?如何访问 Webview2 控件中的文档属性?
【发布时间】:2023-02-10 06:14:59
【问题描述】:

我现有的 C# Winforms 项目之前有默认的 WebBrowser 控件。由于无法加载现代网站,我开始使用 Webview2 控件。

早期的 WebBrowser 控件用于提供 Document 属性;这是 WebView2 控件中缺少的。我们如何访问 Document 和随后的 webview2 加载页面的 DOM?

目前我在以下行收到编译错误:

var _document = webBrowser.Document;

错误信息:

错误 CS1061 WebView2 不包含“Document”的定义,并且找不到接受“WebView2”类型的第一个参数的可访问扩展方法“Document”(是否缺少 using 指令或程序集引用?)

关于如何解决这个问题的任何指示都会有所帮助。

【问题讨论】:

  • 为什么不阅读documentation about WebView2?
  • @UweKeim 我确实和其他许多网站一起阅读了它们,但找不到任何关于我的问题的参考资料。
  • 您最有可能描述要对 DOM 对象执行的操作。不要认为您可以只用 WebView2 对象替换 WebBrowser Control 对象,然后保留您拥有的相同代码——如果您使用的是 ObjectForScripting,那可能会很有用。
  • 你如何访问 DOM? Javascript。
  • 这回答了你的问题了吗? WebView2 (2020/06) -> Where's the DOM?

标签: c# winforms webview2


【解决方案1】:

若要访问 Windows 窗体或 WPF 应用程序中 WebView2 控件的文档属性,可以使用 CoreWebView2.Document 属性。此属性返回 CoreWebView2Document 类的实例,该实例提供对 WebView2 控件中加载的当前网页内容的访问。

以下是如何在 Windows 窗体应用程序中访问 Document 属性的示例:

private void webView2_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
{
    var webView2 = sender as Microsoft.Web.WebView2.WinForms.WebView2;
    var document = webView2.CoreWebView2.Document;
    // Use the document object to interact with the content of the web page
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多