xMRi
xMRi

Reputation: 15375

Intercept TAB Key in WebView2

I want to intercept the Tab key inside Webview2.

It is possible to intercept a lot of function keys via ICoreWebView2AcceleratorKeyPressedEventHandler that I register with add_AcceleratorKeyPressed

But some keys like the cursor keys and the TAB key doesn't call this event handler. Same for the F5 key, it seams that some keys are reserved, strange because the position keys up, down, pos1, end can be intercepted.

Because the window of the WebView2 itself is located in another process there is no chance for me to use standard subclassing and I want to avoid to do subclassing with a hook.

Upvotes: 1

Views: 1848

Answers (2)

ko-barry
ko-barry

Reputation: 11

Another way to intercept keystrokes is as follows: https://github.com/MicrosoftEdge/WebView2Feedback/issues/1215

By setting AdditionalBrowserArguments("--enable-features=msWebView2BrowserHitTransparent") on CoreWebView2EnvironmentOptions, the host window can receive messages by PreTranslateMessage for further processing.

Upvotes: 0

xMRi
xMRi

Reputation: 15375

As mentioned in the discussion I solved the problem.

First I injected a Java script into the browser

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()
);

Than I added an ICoreWebView2WebMessageReceivedEventHandler with add_WebMessageReceived to handle the appropriate message from the hosted 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);

Upvotes: 3

Related Questions