|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using System.Windows; |
| 7 | +using System.Windows.Controls; |
| 8 | +using System.Windows.Data; |
| 9 | +using System.Windows.Documents; |
| 10 | +using System.Windows.Input; |
| 11 | +using System.Windows.Media; |
| 12 | +using System.Windows.Media.Imaging; |
| 13 | +using System.Windows.Navigation; |
| 14 | +using System.Windows.Shapes; |
| 15 | +using Microsoft.Web.WebView2.Core; |
| 16 | + |
| 17 | + |
| 18 | +namespace WPFSample |
| 19 | +{ |
| 20 | + /// <summary> |
| 21 | + /// Interaction logic for MainWindow.xaml |
| 22 | + /// </summary> |
| 23 | + public partial class MainWindow : Window |
| 24 | + { |
| 25 | + public MainWindow() |
| 26 | + { |
| 27 | + InitializeComponent(); |
| 28 | + webView.NavigationStarting += EnsureHttps; |
| 29 | + InitializeAsync(); |
| 30 | + |
| 31 | + } |
| 32 | + |
| 33 | + async void InitializeAsync() |
| 34 | + { |
| 35 | + await webView.EnsureCoreWebView2Async(null); |
| 36 | + webView.CoreWebView2.WebMessageReceived += UpdateAddressBar; |
| 37 | + |
| 38 | + await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);"); |
| 39 | + await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));"); |
| 40 | + |
| 41 | + } |
| 42 | + |
| 43 | + void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args) |
| 44 | + { |
| 45 | + String uri = args.TryGetWebMessageAsString(); |
| 46 | + addressBar.Text = uri; |
| 47 | + webView.CoreWebView2.PostWebMessageAsString(uri); |
| 48 | + } |
| 49 | + |
| 50 | + void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args) |
| 51 | + { |
| 52 | + String uri = args.Uri; |
| 53 | + if (!uri.StartsWith("https://")) |
| 54 | + { |
| 55 | + webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')"); |
| 56 | + args.Cancel = true; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + private void ButtonGo_Click(object sender, RoutedEventArgs e) |
| 61 | + { |
| 62 | + if (webView != null && webView.CoreWebView2 != null) |
| 63 | + { |
| 64 | + webView.CoreWebView2.Navigate(addressBar.Text); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + } |
| 69 | + |
| 70 | +} |
| 71 | + |
0 commit comments