Javascript 如何处理webview中的确认对话框?UWP windows 10应用程序C#
我正在开发uwp应用程序(Win10)的c# 我想把我的网站放在xaml webview元素中 大部分功能都是可行的 但是我不能处理确认对话框 比如说 这是示例html和js代码Javascript 如何处理webview中的确认对话框?UWP windows 10应用程序C#,javascript,c#,webview,uwp,Javascript,C#,Webview,Uwp,我正在开发uwp应用程序(Win10)的c# 我想把我的网站放在xaml webview元素中 大部分功能都是可行的 但是我不能处理确认对话框 比如说 这是示例html和js代码 <button id="btnConfirm" onclick="confirmBox('sure to delete?')">click me to confirm</button> <button id="btnAlert" onclick="alert('alert message'
<button id="btnConfirm" onclick="confirmBox('sure to delete?')">click me to confirm</button>
<button id="btnAlert" onclick="alert('alert message')">click me to alert</button>
<script type="text/javascript">
function confirmBox(message) {
if (confirm(message)) {
alert("yes");
} else {
alert("no");
}
}
</script>
问题是confirmjs函数总是返回false
在用户单击“是”或“否”之前
我可以让用户选择按钮。但是太晚了
在这种情况下,js函数“confirm”永远不会返回true
有人能帮我吗
谢谢。这行不通。JS在单线程上运行,不会等待c#调用的结果。因此,警报不会等待MessageDialog的结果 请注意,winrt项目中的webview更适合显示一些静态html。如果您确实希望弹出一个消息对话框作为确认对话框,那么您需要完成以前在c代码中使用javascript所做的所有rest工作
例如,如果要更改html控件的某些文本,则需要准备一个完整的html字符串,然后检查CommandInvokedHandler回调中的命令状态,并让webview导航到(webview.NavigateToString)新的html字符串。如果需要接收从webview托管脚本发送的应用程序代码中的通知和数据,您需要处理ScriptNotify事件。你可以参考这一场景。你好,姚明,谢谢你的回复。我知道你的意思。在我的senario,这个网站已经完全建立了很长一段时间了。所以我不知道确认函数调用了多少次。因此,我无法逐个处理CommandInvokedHandler。我需要确保原来的网站功能工作良好。谢谢你的回复。现在我发现等待c#call的结果是不可能的。你好,吴芳芳谢谢你的回复。在我研究了这个样本之后。没有提到如何获取确认函数的返回值。
<WebView Grid.Row="1" x:Name="webView1" Source="ms-appx-web:///HTMLPage1.html" Width="auto" Height="auto"/>
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
}
}