5

我是通用应用程序开发的新手。任何人都可以帮助我进入以下代码,

我在通用应用程序中使用 Web 视图控件加载了一个网站。我想从同一个网站读取一些控制值。

我的标签控件 ID 在网站上是“lblDestination”。

我在通用应用程序中访问它,比如 MAinPage.xaml

<WebView x:Name="Browser"  HorizontalAlignment="Stretch"
                 VerticalAlignment="Stretch"
                 Loaded="Browser_Loaded"
                 NavigationFailed="Browser_NavigationFailed">
</WebView>

MAinPage.xaml.cs

Browser.InvokeScript("eval", new string[] { "document.getElementById('lblDestination')" }).ToString()

这是读取浏览器控件值的正确方法吗?我正在使用模拟器来测试这个应用程序,那么模拟器是否会造成问题?

4

1 回答 1

9

我不确定您在何时何地使用InvokeScriptJavaScripteval函数将内容注入网页。但通常我们可以使用WebView.DOMContentLoadedevent。当WebView完成对当前 HTML 内容的解析时会发生此事件,因此通过此事件我们可以确保 HTML 内容已准备好。

如果我们想在 Windows 10 通用应用程序的WebView内容中调用 JavaScript,我们最好使用WebView.InvokeScriptAsync方法as

[ Windows 8.1 之后的版本可能会更改或无法使用InvokeScript 。相反,使用InvokeScriptAsync。]

最后但同样重要的是,请注意该InvokeScriptAsync方法只能返回脚本调用的字符串结果。

调用的脚本只能返回字符串值。

因此,如果您的 JavaScript 的返回值不是字符串,则WebView.InvokeScriptAsync方法的返回值将是一个空字符串。

如果你使用

var value = await Browser.InvokeScriptAsync("eval", new string[] { "document.getElementById('lblDestination')" });

该值将是一个空字符串,因为document.getElementById('lblDestination')返回一个Element.

因此,要读取一些控制值,您可以尝试使用如下代码:

var innerText = await Browser.InvokeScriptAsync("eval", new string[] { "document.getElementById('lblDestination').innerText" });

如果你要获取的值不是字符串,你可能需要先在 JavaScript 中将其转换为字符串。例如:

var childElementCount = await Browser.InvokeScriptAsync("eval", new string[] { "document.getElementById('lblDestination').childElementCount.toString()" });
于 2016-03-30T08:38:44.443 回答