如何在通用Windows应用程序中调用WebView中的javascript函数
我是Universal app开发的新手。 任何人都可以帮助我编写代码,
我在通用应用程序中使用Web视图控件加载了一个网站。 我想从同一个网站上读取一些控制值。
我的标签控件ID是网站上的’lblDestination’。
我在像MAinPage.xaml
这样的通用应用程序中访问它
MAinPage.xaml.cs
Browser.InvokeScript("eval", new string[] { "document.getElementById('lblDestination')" }).ToString()
这是读取浏览器控件值的正确方法吗? 我正在使用模拟器来测试这个应用程序,那么模拟器是否会产生问题?
我不确定在何时何地使用InvokeScript
和JavaScript eval
函数将内容注入网页。 但通常我们可以使用WebView.DOMContentLoaded
事件 。 当WebView完成解析当前HTML内容时会发生此事件,因此通过此事件,我们可以确保准备好HTML内容。
如果我们想在Windows 10 Universal应用程序中调用WebView内容中的JavaScript,我们最好使用WebView.InvokeScriptAsync
方法作为
[在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()" });