【问题标题】:WebView2 - Get an attributeWebView2 - 获取属性
【发布时间】:2021-06-28 14:28:00
【问题描述】:

我正在尝试了解 WebView2 中的架构。使用 WebBrowser,我曾经从 GetElementById 返回的结果中获取属性,如下所示:Document.GetElementById("DropDownList").GetAttribute("selectedIndex")

我知道 WebView2 中的 ExecuteScriptAsync 可以运行 javascript 并以字符串形式返回结果。但是,它看起来不知道如何从元素中获取属性。下面的代码返回一个空值。虽然,getElementById 返回了正确的结果。
ExecuteScriptAsync("document.getElementById('DropDownList').getAttribute('selectedIndex')")

我的语法不正确吗?如何在 WebView2 中获取属性?是不是一定要在脚本里写个函数,从宿主机调用?

谢谢

【问题讨论】:

  • 你的 JavaScript 也从未使用过 Webbrowser。 -1 来自我。
  • @darbid:实际上在旧的 WebBrowser 中,您使用 C# 访问 dom,而不是 javascript(显示的代码是 C#)。
  • 我指的是“虽然,getElementById 返回了正确的结果。”

标签: javascript webview2


【解决方案1】:

HTMLSelectElement 没有名为“selectedIndex”的属性。它有一个名为“selectedIndex”的属性。

从WebView2这样称呼它:

await ExecuteScriptAsync("document.getElementById('DropDownList').selectedIndex");

【讨论】:

  • 太棒了!那行得通!谢谢!。您对 WebView2 非常了解。
  • 许多人对 javascript 属性与属性感到困惑。简单的规则是:属性可以直接写在html标签中,比如'id','name'等
【解决方案2】:

你需要等待这个方法。 see the reference

string res = await ExecuteScriptAsync("document.getElementById('DropDownList').getAttribute('selectedIndex')")

【讨论】:

  • 是的,我已经在等待这个方法了。正如我解释 getElementById 返回一个值,但如果我添加一个 getAttribute 它返回 null
  • 那么你有一个 JavaScript 问题。导航到该站点,打开开发工具,转到控制台并粘贴您的 JavaScript,然后按 Enter。会发生什么?
猜你喜欢
  • 1970-01-01
  • 2015-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 2023-02-10
  • 2023-03-22
相关资源
最近更新 更多