How to invoke javascript functions in a WebView in Universal Windows App

一世执手 提交于 2019-11-29 11:34:01

I'm not sure where and when you use InvokeScript with the JavaScript eval function to inject content into the web page. But usually we can use WebView.DOMContentLoaded event. This event occurs when the WebView has finished parsing the current HTML content so with this event we can make sure the HTML content is prepared.

And If we want to invoke JavaScript inside the WebView content in Windows 10 Universal app, we'd better use WebView.InvokeScriptAsync method as

[InvokeScript may be altered or unavailable for releases after Windows 8.1. Instead, use InvokeScriptAsync.]

Last but not least, please do note that the InvokeScriptAsync method can only return the string result of the script invocation.

The invoked script can return only string values.

So if the return value of your JavaScript is not a string, the return value of WebView.InvokeScriptAsync method will be a empty string.

If you use

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

the value will be a empty string as document.getElementById('lblDestination') returns an Element.

So to read some control value, you can try using code like following:

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

And if the value you want to get is not a string, you may need to convert it to string in JavaScript first. For example:

var childElementCount = await Browser.InvokeScriptAsync("eval", new string[] { "document.getElementById('lblDestination').childElementCount.toString()" });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!