【问题标题】:Intercept TAB Key in WebView2在 WebView2 中拦截 TAB 键
【发布时间】:2020-11-03 11:33:13
【问题描述】:

我想截取Webview2里面的Tab键。

我在add_AcceleratorKeyPressed注册的ICoreWebView2AcceleratorKeyPressedEventHandler可以拦截很多功能键

但某些键(如光标键和 TAB 键)不会调用此事件处理程序。 F5键也一样,接缝有些键是保留的,奇怪的是位置键up、down、pos1、end都可以截取。

因为 WebView2 本身的窗口位于另一个进程中,所以我没有机会使用标准子类化,我想避免使用钩子进行子类化。

【问题讨论】:

  • 你写了一个javascriptkeydown事件处理程序,然后你可以使用window.chrome.webview.postMessageWebView2控件发送消息。
  • 感谢您的回答。您是否有任何链接或来源显示 Win32/COM 应用程序的这种基本用途?
  • 此页面:docs.microsoft.com/da-dk/microsoft-edge/webview2/gettingstarted/… 展示了如何注入脚本并接收消息。
  • 它不适用于 TAB 键,因为 TAB 不被视为 Accelerator Keys。我同意波尔的观点。您可以使用here 中的postMessage 在主机和Web 内容之间进行通信。
  • 我找到了一个更详细的 WebView2 C++ 示例,并且有一段关于 Communicating the WebViews 的段落。它有示例展示如何使用window.chrome.webview.postMessage 并在 JavaScript 端为接收到的消息添加事件侦听器。也可以参考一下。

标签: c++ com microsoft-edge webview2


【解决方案1】:

正如讨论中提到的,我解决了这个问题。

首先我在浏览器中注入了一个 Java 脚本

m_spWebView->AddScriptToExecuteOnDocumentCreated(
    L"window.document.addEventListener('keydown', function(e) {\n"
    L" if (e.keyCode===9 || e.keyCode===13) {\n"
    L"  window.chrome.webview.postMessage('" CHAR_TOKEN L"'+e.keyCode.toString()); \n"
    L"  e.preventDefault(); \n"
    L"}});\n"
    ,Callback<ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler>(this,&CBrowserWV2Wnd::OnAddScriptToExecuteOnDocumentCreated).Get()
);

然后我添加了 ICoreWebView2WebMessageReceivedEventHandleradd_WebMessageReceived 来处理来自托管 WebView2 的适当消息。

LPWSTR pwStr = nullptr;
args->TryGetWebMessageAsString(&pwStr);
if (_wcsnicmp(pwStr,CHAR_TOKEN,MfxCountOf(CHAR_TOKEN)-1)==0)
{
    // Get the Keycode from the message
    auto iChar = wcstol(pwStr+MfxCountOf(CHAR_TOKEN)-1,nullptr,10);
    // Do something with the intercepted character
    ...
}
::CoTaskMemFree(pwStr);

【讨论】:

  • 感谢您发布此问题的解决方案。您可以将您的答案标记为已接受的答案。它可以在未来帮助其他社区成员解决类似的问题。感谢您的理解。
猜你喜欢
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2021-12-09
  • 2022-08-22
  • 1970-01-01
相关资源
最近更新 更多