Home > Software engineering >  NSMenuItem not receiving keyEquivalentModifierMask control with WKWebView
NSMenuItem not receiving keyEquivalentModifierMask control with WKWebView

Time:07-06

NSApplication.mainMenu with 2 NSMenuItem and the following keyEquivalent:

  • ⌃ ⇥ (Control Tab)
keyEquivalent = String(utf16CodeUnits: [unichar(NSTabCharacter)]
keyEquivalentModifierMask = NSEvent.ModifierFlags.control
  • ⌃ ⇧ ⇥ (Control Shift Tab)
keyEquivalent = String(utf16CodeUnits: [unichar(NSTabCharacter)]
keyEquivalentModifierMask = [NSEvent.ModifierFlags.control, NSEvent.ModifierFlags.shift]

They work as expected with any NSView except with a WKWebView and any other keyEquivalent combination work.

Apparently the menu item is not receiving the event, as clicking directly on the item works as expected too, even if the key equivalent didn't.

How to make it work?

CodePudding user response:

Seems like WKWebView intercepts ⌃ ⇥ and ⌃ ⇧ ⇥ without passing them down the NSReponder chain, like it does with some other commands.

These commands use the selectors from NSWindow:

The solution is to subclass WKWebView and implement those selectors.

Example:

final class WebView: WKWebView {
    @objc func selectNextKeyView(_ sender: Any?) {
        // implement Control Tab
    }
    
    @objc func selectPreviousKeyView(_ sender: Any?) {
        // implement Control Shift Tab
    }
}
  • Related