如何在webview中处理确认对话框? UWP windows 10 app C#

我正在通过c#开发uwp app(win 10)

我想把我的网站放在xaml webview元素中。

大多数function都是可行的。

但我无法处理确认对话框

例如

这是示例html和js代码

   function confirmBox(message) { if (confirm(message)) { alert("yes"); } else { alert("no"); } }  

这是我的xaml代码

  

这是我的C#代码

 webView1.ScriptNotify += webView1_ScriptNotify; webView1.NavigationCompleted += webView1_NavigationCompleted; async void webView1_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) { await webView1.InvokeScriptAsync("eval", new string[] { "window.confirm = function(confirmMessage) { window.external.notify('typeConfirm:' + confirmMessage) }" }); await webView1.InvokeScriptAsync("eval", new string[] { "window.alert = function(AlertMessage) { window.external.notify('typeAlert:' + AlertMessage) }" }); } private async void webView1_ScriptNotify(object sender, NotifyEventArgs e) { Windows.UI.Popups.MessageDialog dialog; string[] messageArray = e.Value.Split(':'); string message; string type; if (messageArray.Length > 1) { message = messageArray[1]; type = messageArray[0]; } else { message = e.Value; type = "typeAlert"; } dialog = new Windows.UI.Popups.MessageDialog(message); Debug.WriteLine("type=" + type + " ,message=" + message); if (type.Equals("typeConfirm")) { dialog.Commands.Add(new UICommand( "Yes", new UICommandInvokedHandler(this.CommandInvokedHandler))); dialog.Commands.Add(new UICommand( "Cancel", new UICommandInvokedHandler(this.CommandInvokedHandler))); dialog.DefaultCommandIndex = 0; dialog.CancelCommandIndex = 1; } var result = await dialog.ShowAsync(); if (result.Label.Equals("Yes")) { // return true; } else { // return false } } 

问题是确认js函数将始终返回false

在用户点击是或否之前。

我可以得到用户选择的按钮。 但为时已晚。

在这种情况下,js函数“confirm”永远不会返回true。

有人可以帮帮我吗?

谢谢。

这不行。 JS在单线程上运行,不会等待c#调用的结果。 因此警报不会等待MessageDialog的结果。

请注意,winrt项目中的webview更适合显示一些静态html。 如果您确实想要将MessageDialog作为确认对话框弹出,那么您需要完成之前在c#代码中使用javascript执行的所有其余工作。

例如,如果要更改html控件的某些文本,则需要准备一个完整的html字符串,然后在CommandInvokedHandler回调中检查命令状态,并让webview导航到(webView.NavigateToString)新的html字符串。

如果您需要接收从WebView托管的脚本发送的应用程序代码中的通知和数据,则需要处理ScriptNotify事件。 您可以参考此示例 (场景6)。