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

我已经在通用应用中使用网络 View 控件加载了一个网站。我想从同一网站上读取一些控制值。

我的标签控件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()

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

最佳答案

我不确定您在何时何地将 InvokeScript 与JavaScript eval函数一起使用来将内容注入(inject)网页。但是通常我们可以使用 WebView.DOMContentLoaded event。当 WebView 完成对当前HTML内容的解析后,将发生此事件,因此通过此事件,我们可以确保准备好HTML内容。

而且,如果我们想在Windows 10 Universal应用程序的 WebView 内容内调用JavaScript,我们最好将 WebView.InvokeScriptAsync method用作



最后但并非最不重要的一点,请注意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()" });

关于c# - 如何在Universal Windows App中的WebView中调用javascript函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36286761/

10-16 03:01