WPF中WebView2禁用F12和右键菜单

2023-11-22 12:57:54 浏览数 (1)

前言

默认WebView2加载网页是可以通过F12和右键打开调试窗口,但是大多情况下我们在发版时要禁用。

禁用F12

禁用F12是禁用按键事件来解决的。

代码语言:javascript复制
WebView.PreviewKeyDown  = WebView_PreviewKeyDown;

private void WebView_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // 检查按下的键是否是 F12,如果是,禁止其默认行为
    if (e.Key == Key.F12)
    {
        e.Handled = true;
    }
}

禁用右键菜单

右键菜单通过禁用鼠标右键事件不起作用。

所以这里在页面加载后执行JS实现。

代码语言:javascript复制
WebView.Visibility = Visibility.Hidden;

WebView.NavigationCompleted  = WebView_NavigationCompleted;

private async void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
    await WebView.CoreWebView2.ExecuteScriptAsync(
        @"
            document.addEventListener('contextmenu', function(event) {
                event.preventDefault();
            }, false);
        "
    );
    await Task.Delay(600);
    WebView.Visibility = Visibility.Visible;
}

整体代码

代码语言:javascript复制
private void ZuoyeWin_OnLoaded(object sender, RoutedEventArgs e)
{
    WebView.Visibility = Visibility.Hidden;
    WebView.PreviewKeyDown  = WebView_PreviewKeyDown;
    WebView.NavigationCompleted  = WebView_NavigationCompleted;
    LoadUrl();
}

private void WebView_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // 检查按下的键是否是 F12,如果是,禁止其默认行为
    if (e.Key == Key.F12)
    {
        e.Handled = true;
    }
}

private async void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
    await WebView.CoreWebView2.ExecuteScriptAsync(
        @"
            document.addEventListener('contextmenu', function(event) {
                event.preventDefault();
            }, false);
        "
    );
    await Task.Delay(600);
    WebView.Visibility = Visibility.Visible;
}

0 人点赞