WebView2如何屏蔽F12调试窗口出现和仅保留输入框的右键菜单
List<string> unusedList= new List<string>
{
"back", "forward",
"reload","saveAs",
"print","other",
"createQrCode","share",
"webSelect","webCapture",
"openLinkInNewWindow","saveLinkAs",
"copyLinkLocation","saveImageAs",
"copyImageLocation","copyImage",
"pasteAndMatchStyle",
};
public Form1()
{
InitializeComponent();
this.Resize += new System.EventHandler(this.Form_Resize);
webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompleted;
webView21.NavigationStarting += EnsureHttps;
InitializeAsync();
}
private void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
webView21.CoreWebView2.Settings.AreDevToolsEnabled = false;
webView21.CoreWebView2.ContextMenuRequested += delegate (object sender1,
CoreWebView2ContextMenuRequestedEventArgs args1)
{
IList<CoreWebView2ContextMenuItem> menuList = args1.MenuItems;
CoreWebView2ContextMenuTargetKind context = args1.ContextMenuTarget.Kind;
foreach(var item in unusedList)
{
for (int index = 0; index < menuList.Count; index++)
{
Console.WriteLine(menuList[index].Name);
if (menuList[index].Name == item)
{
menuList.RemoveAt(index);
}
}
}
};
}
private void Form_Resize(object sender, EventArgs e)
{
webView21.Size = this.ClientSize - new System.Drawing.Size(webView21.Location);
button1.Left = this.ClientSize.Width - button1.Width;
textBox1.Width = button1.Left - textBox1.Left;
}
private void button1_Click(object sender, EventArgs e)
{
if (webView21 != null && webView21.CoreWebView2 != null)
{
webView21.CoreWebView2.Settings.AreDevToolsEnabled = false;
webView21.CoreWebView2.Navigate(textBox1.Text);
}
}
private void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
String uri = args.Uri;
if (!uri.StartsWith("https://"))
{
webView21.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
args.Cancel = true;
}
}
async void InitializeAsync()
{
await webView21.EnsureCoreWebView2Async(null);
webView21.CoreWebView2.WebMessageReceived += UpdateAddressBar;
await webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
await webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));");
}
void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
String uri = args.TryGetWebMessageAsString();
textBox1.Text = uri;
webView21.CoreWebView2.PostWebMessageAsString(uri);
}