6

Environment: Windows 10 Pro - ver. 1903, VS2019 latest version, WPF Core

When I have a manual control on an HTML page displayed inside WebView2 control, I can disable the context menu by simply adding oncontextmunu={return false;} as an attribute to <body> tag. But in most cases the web page is displayed based on user interaction (what page user navigates to etc.).

Question: How can we disable to context menu of a webpage displayed in WebView2 control?

Remarks:

  1. I have noticed that in some cases where a JavaScript is loaded along with a webpage, the oncontextmunu={return false;} does not disable the context menu even if I add this attribute programmatically to the body tag of loaded page. I see AreDefaultContextMenusEnabled property of Microsoft.Web.WebView2.Core.CoreWebView2Settings class but VS2019 does not recognize any such property for WebView2.
  2. There was a similar issue on the old WebBrowser control of WPF as described here and here, and I have the similar situation for WebView2.
  3. According to bullet 5 of this Microsoft link the issue was resolved. But the solution there seems to be related to C++ while I'm using C#. Maybe, there is an alternative.
nam
  • 21,967
  • 37
  • 158
  • 332
  • 4
    Use: webView21.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false; AFTER the CoreWebView has been initialized. – Poul Bak Aug 09 '20 at 22:08
  • Does this answer your question? [How do you override the ContextMenu that appears when right clicking on WebView2 Control?](https://stackoverflow.com/questions/62624373/how-do-you-override-the-contextmenu-that-appears-when-right-clicking-on-webview2) – Poul Bak Aug 09 '20 at 22:15
  • 2
    @PoulBak Your suggestion of using `webView21.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false; AFTER the CoreWebView has been initialized` worked (thank you) for my particular case. Not sure if it would work or not in other cases. As explained [here](https://stackoverflow.com/a/62662908/1232087) by a member of MS Edge WebView2 team, their team does not yet have full support for customizing the context menu. But there are workaround - such as the one you demoed [here](https://stackoverflow.com/a/62732034/1232087). Ref for [initialization](https://stackoverflow.com/a/62987060/1232087) – nam Aug 10 '20 at 03:15

1 Answers1

13

Mostly, the reason for disabling the Context Menu is for preventing the End-User from inspecting the page source. Thus, we should also disable the accelerator keys using both instructions:

webView.CoreWebView2.Settings.AreBrowserAcceleratorKeysEnabled = false;
webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;

since the End-User can use Ctrl+Shift-C and F12 for DevTools check Accelerator Keys

90Degree
  • 199
  • 1
  • 5