简体   繁体   中英

Web page: detect and block certain keyboard shortcuts

I want to detect and block certain keyboard shortcuts on a webpage. For example, say I want to prevent alt-tab for switching apps (just an example, assume any global shortcut)

Here's as far as I can think it out:

  • attach a keyboard event listener to document (or window ?)
  • use event.which to check which key combination was pressed
  • if it was a blacklisted shortcut, stop the browser from executing it

But, I don't know how to
A) detect multiple keys (eg alt and tab together), or
B) stop them from executing (can I just return false ?).

Can anyone tell me how to accomplish the above?
Thanks!

You want to prevent screenshots from being taken? Forget it right now .

No matter what elaborate mechanisms you put into place, they will be trivial to circumvent by un-focusing the browser window (or just the document, eg by clicking into the address bar), and pressing the screenshot key then.

There is no chance for you to do this except by installing client software on the computer that controls what the user does, or maybe using some proprietary ActiveX control that makes its contents un-print-screenable. Both approaches are hugely difficult and have tons of downsides.

You cannot block keyboard combinations that belong to the OS . Only keyboard combinations that roam inside the browser and are not OS specific.

If you want to protect your content , don't publish it in public. Or put a decent license on it

// lookup table for keycodes
var key = { s: 83 };

document.onkeydown = function (e) {
  // normalize event
  e = e || window.event;

  // detecting multiple keys, e.g: Ctrl + S
  if (e.ctrlKey && !e.altKey && e.keyCode === key.s) {
    // prevent default action
    if (e.preventDefault) {
      e.preventDefault();
    }
    // IE
    e.returnValue = false;
  }
};

Detecting Keystrokes Compatibility Table ( QuirksMode )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM