AsynchronousscriptdialogpromptsinWebView2onWindows
创始人
2024-09-21 04:30:32
0

在Windows的WebView2中异步调用脚本对话框时, 你需要使用CustomWebMessageBroker来监听并从脚本中接收消息。

以下是一些代码示例,演示了如何在Windows的WebView2中实现异步调用脚本对话框:

首先,为了接收来自脚本的消息,您需要在核心 WebView2控件中设置一个自定义WebMessageBroker,并在其中处理从脚本发送的消息。下面是创建自定义WebMessageBroker的范例:

// Create a custom WebMessageBroker
myWebView2.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;

private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
   // Handle incoming message from script
   string message = e.TryGetWebMessageAsString();
   if (message == "HelloWorld")
   {
      // Show custom prompt dialog
      // ...
   }
}

接下来,您可以在您的脚本中调用window.chrome.webview.postMessage API并设置消息参数,以向上一步中创建的自定义WebMessageBroker发送消息。以下是一个演示如何在脚本中发送消息给CoreWebView2_WebMessageReceived处理程序的示例:

// Call window.chrome.webview.postMessage to send message to CoreWebView2_WebMessageReceived
window.chrome.webview.postMessage("HelloWorld");

最后,在上述自定义WebMessageBroker的处理程序中,您可以实现在Windows所需的异步prompt方法来显示相应的消息。例如:

private async void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
   string message = e.TryGetWebMessageAsString();
   if (message == "HelloWorld")
   {
      await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
      {
         var promptDialog = new ContentDialog()
         {
            Title = "Prompt",
            Content = "Please enter your name:",
            PrimaryButtonText = "Ok",
            SecondaryButtonText = "Cancel"
         };

         var result = await promptDialog.ShowAsync();
         
         if (result == ContentDialogResult.Primary)
         {
            // Do something with user input
            // ...
         }
      });
   }
}

这里,我们使用了Windows的异步方法Dispatcher.RunAsync,以确保在UI线程上显示prompt对话框。然后,我们创建了一个ContentDialog并等待用户在提示对话框中单击OK或Cancel按钮。最后,我们可以在该对话框中获取用户输入并继续处理它。

相关内容

热门资讯

wepoke辅助挂!wepok... wepoke辅助挂!wepoke好友助力(透视辅助)WePoKer(一般真的有挂);WePoKer软...
微扑克有辅助挂!微扑克俱乐部,... 微扑克有辅助挂!微扑克俱乐部,微扑克ai人工智能,wepoke教程(有挂黑科技)1、微扑克ai机器人...
玩家攻略推荐!闽游麻将(透视辅... 玩家攻略推荐!闽游麻将(透视辅助)原来存在有挂(2023已更新)(哔哩哔哩);1、闽游麻将ai辅助优...
软件教程!wopoker轻量版... 软件教程!wopoker轻量版外 挂(wepoke辅助技巧)wepoKE(果然真的有挂)关于wopo...
微扑克ai辅助工具!微扑克辅助... 微扑克ai辅助工具!微扑克辅助多少钱,微扑克ai操作,可靠技巧(有挂ai代打);人气非常高,ai更新...
玩家科普!吉祥麻将怎么让系统发... 玩家科普!吉祥麻将怎么让系统发好牌(透视辅助)竟然存在有挂(2026已更新)(哔哩哔哩)亲,关键说明...
wepoke智能ai!wopo... wepoke智能ai!wopoker分析器,wEPOKE果真真的有挂,技巧教程(有挂详情);wopo...
微扑克ai机器人!微扑克ai操... 微扑克ai机器人!微扑克ai操作(透明挂)总是是真的有挂;微扑克是一种具有地方特色的麻将游戏,要想赢...
我来教大家!碣石暗宝链接有挂吗... 我来教大家!碣石暗宝链接有挂吗(透明挂)确实真的是有挂(2025已更新)(哔哩哔哩);亲,关键说明,...
微扑克辅助软件!微扑克可以用a... 微扑克辅助软件!微扑克可以用ai辅助(透明挂)本来是有挂1、每一步都需要思考,不同水平的挑战会更加具...