Entrepreneur Geek

Nirav Mehta on life, technology and future

Archive for the ‘suppress handling’ tag

How to stop keyboard event propagation – Flex / JavaScript?

with 6 comments

In a Flex application we are building, we want to listen to Ctrl+N to create a new file. The browser listens to the keystroke and opens a new window. We do not want it to open a new window.

This has been a problematic thing for many. I did a lot of research, trial & error, but I still don’t have a solution. I can catch all key events, using some JavaScript, I can also prevent Ctrl+W and Ctrl+S. But not Ctrl+N. Do you have something?

References:

Situations / Test Cases:

  • Should work: Ctrl + N (New), Ctrl + O (Open), Ctrl + W (Close), Ctrl + Q (Quit)
  • Ctrl + C (Copy), Ctrl + V (Paste), Ctrl + X (Cut) – this works with current Flex app. New code must not break it
  • Should work on Windows, Mac, Linux
  • Should work on Firefox, IE, Safari, Chrome
  • What if focus is not in Flex app?
  • What if user goes to another window, comes to our app and presses a keyboard shortcut? (this will lose focus)
  • Will cut / copy / paste from Browser’s Edit menu work?

JavaScript does it:

Flex documentation says:
When handling a key or key combination that the underlying operating system or browser recognizes, the operating system or browser generally processes the event first. For example, in Microsoft Internet Explorer, pressing Control+w closes the browser window. If you trap that combination in your Flex application, Internet Explorer users never know it, because the browser closes before the ActiveX Flash Player has a chance to react to the event.

Notes:

  • KeyboardEvent is non cancelable in Flex.
  • stopImmediatePropagation(), preventDefault(), stopPropagation() – don’t stop the propagation
  • I can detect the keys very well, problem is suppressing the default browser action
  • Don’t want to have a full HTML/JavaScript/ExternalInterface handling like Buzzword. Ideally, want to let Flex handle it’s own events, HTML handle browser events and suppress them.

Any ideas?

TIA!

Written by Nirav

November 19th, 2008 at 5:55 pm