I'm building an SPA where it would be quite useful if I could capture the shortcuts cmd/ctrl+shift+1 through 9. It appears to me that this should be possible, since no browser I know binds these keys to anything else, but for some reason, pressing cmd+shift+1 (I'm using a macbook) fails to even cause a keyboard event.
Is this an inherent limitation of Chrome, or is there some special thing that I don't know of that needs to be done to capture these events?
I don't have a macbook, but I can capture ctrl+shift+1 (be sure to give focus to the snippet results frame):
document.body.addEventListener('keyup', function(e)
{
if((e.code == 'Digit1' || e.code == 'Numpad1') && e.ctrlKey && e.shiftKey)
{
console.log('ctrl+shift+1');
}
else
{
console.log(e.key, 'pressed')
}
});
This is layout dependent, i.e. if you are not using QWERTY, beware! See the KeyboardEvent page for help with different keyboard layouts.
Related
How can I get platform specific shortcut, or key binding for a specific process?
As an example how can I get the information that on Windows shortcut for copying is Ctrl + C ? (I'd like the information on all of the tagged languages if possible) I mean both text editing and file manager usage, and also would like to know if they're independent.
If I understand you, you want rewrite system command of browser. In browser all process start after some event. You can copy text , if you use command for copy: document.execCommand('copy'); and you can rewrite all events except paste.
Example:
document.addEventListener('keydown', (ev) => {
if(ev.keyCode === 67 && ev.ctrlKey === true) { // ctrl+c
console.log(ev);
ev.preventDefault();//block default action of browser
}
});
and trigger copy:
document.addEventListener('keydown', (ev) => { //ctrl+z
if(ev.keyCode === 90 && ev.ctrlKey === true) {
console.log(ev);
document.execCommand('copy');
ev.preventDefault();
}
});
All execCommand: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
To expand on my comment above, you need to check for evt.metaKey to catch standard macOS shortcuts, which use the same letter keys for the basic Cut/Copy/Paste/Undo as Windows (X/C/V/Z), but combined with the different command (⌘) modifier key.
It doesn't hurt in most cases if a Mac user can also use their control key as well as the command key for a shortcut, so the easiest solution is to check for both. Here's code from the previous answer modified to do that:
document.addEventListener('keydown', (ev) => {
if (ev.keyCode === 67 && (ev.ctrlKey || ev.metaKey)) { // Copy shortcut
console.log(ev);
ev.preventDefault(); // block default action of browser
}
});
On a Windows system, you'll probably never see a keyboard event with metaKey being true, because as far as I can tell, any keypress using the Win key (⊞), which theoretically maps to metaKey, will be intercepted by Windows before a web browser has any chance to look at it.
If you want to explore more about key events and modifier keys, I threw together a quick CodePen here for that: https://codepen.io/kshetline/pen/MWmKrPM?editors=1010
I'm building a node-webkit app, am listening for keypress events (in an angular directive).
Most combinations of keypress are working, but ctrl+f and ctrl+a are both not working.
This problem is specific to node-webkit. I've got the ctrl+a etc. working in the browser, but not in node-webkit.
I'm listening for keypress with the usual
document.bind('keypress',function...)
window.bind('keypress', function...)
window.bind('onkeypress', function...)
window.bind('keydown', function...)
any suggestions? Remember, the other combinations of keys ctrl+shift+o, etc. are working.
As this is a node-webkit app, there is no browser based 'find' function, and I'm disabling the 'select all'.
Isn't it an answer you where looking for?
There is a fiddle in answer of ctrl+f. If you replace 70 to 65 in this example, it will also work for ctrl+a.
document.onkeydown = function (e) {
/// check ctrl + f key
if (e.ctrlKey === true && e.keyCode === 70/*65*/) {
e.preventDefault();
console.log('Ctrl + f was hit...');
return false;
}
}
Here is a library you can use to add ctrl+f "find" support in NW.js.
https://github.com/nwutils/find-in-nw
ctrl+a to "select all" is already built in to Normal and SDK versions of NW.js
However, if you want to override the default "ctrl+a", then Andrew's answer is correct and will do that. Listen for the event and prevent default.
Note: Juan Mendes answer is the selected answer because it had the most useful response to my situation. Though AxGryndr also had some useful information. Read both answers and they are both good for different situations. Thank you both for helping with this.
I already asked a similar question about this here which did solve the first part of my problem now I have another. I want the Ctrl + N to launch a script that contains an AJAX but once I run the .get function it cause the default to launch. Does anyone know a work around for this.
This fiddle has some code that shows my problem. Here is some of the code.
function checkkey(e)
{
if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey)
{
try{e.preventDefault();}catch(ex){}
var m_objXMLHttpReqObj = new XMLHttpRequest();
m_objXMLHttpReqObj.open("GET", "", false);
m_objXMLHttpReqObj.send();
}
}
JSFIDDLE
Your code was not preventing the default behavior
function checkkey(e) {
if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey) {
e.preventDefault();
// Now send your AJAX
It also seems that AJAX is interfering with the ability to stop the default behavior. You were trying to send a synchronous AJAX request (don't ever do that, it will halt the browser) and you weren't giving it a URL to go to (triggering an error). As soon as you change your settings to properly give it a URL and to make it asynchronous, then it does work in FF.
Here's the working code
function checkkey(e) {
if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey){
e.preventDefault();
var m_objXMLHttpReqObj = new XMLHttpRequest();
m_objXMLHttpReqObj.open("GET",
// URL to go to
"/echo/html/",
// Asynchronous
true);
m_objXMLHttpReqObj.send("");
}
}
However, in Chrome (it may not be of use to you, but to others who read this answer), if you add a console.log at the top of your handler, you'll see that the handler never gets. Therefore, Chrome doesn't even let you see the CTRL+N combination and you can't do anything about it. Just like Windows applications don't get notified of CTRL+ALT+DEL
If the application has to work for multiple browsers, my suggestion is to use a different combination like ALT+SHIFT+N, you really don't want to take over the basic browser shortcuts.
I believe your issue is that you are checking for a keypress and performing your action too late after the keyup. If you change your code to bind to the keydown of Ctrl+N I think your would be able to get the desired result. Something like:
var pKey
$(function() {
$(window).keydown(function(e) {
if(e.which == 17) {
pKey = e.keyCode;
}
else {
if(pKey == 17 && e.keyCode == 78) {
e.preventDefault();
console.log(e);
}
}
});
});
I added the global variable to capture the Ctrl key down which is keycode 17. I then capture the keycode 78 on the second keydown which is the N. Prior e.preventDefault() was not enough to prevent the new window so I had to add the extra lines for e.stopPropagation(), e.stopImmediatePropagation() and the console.log(e) can be removed. As Juan M has mentioned the others are no longer needed so I have updated the code to not include them.
Note: Firefox made a change in key biding priority. It use to be System>Website>Firefox however it seems people were complaining about websites that hijacked short cuts so the priority has changed to be System>Firefox>Website which means even if your website binds Ctrl+N the priority of Firefox for a new windows takes over.
Hi we are facing the problem with escape key in our web application. If user press the escape key the web application gets stop loading.
I tried using all these with(onkeydown and onkeyup)
document.attachEvent("onkeydown", win_onkeydown_handler);
window.attachEvent("onkeydown", win_onkeydown_handler);
window.document.attachEvent("onkeydown", win_onkeydown_handler);
I cant able detect the escape(KeyCode=27) in my web application .. but i am able to detect refresh,f5 and all other keys
Note: i face this problem in IE
This helps me to prevent escape in iframe
function disableEscapeAndRefresh(){
try{
if(window.frames && window.frames[0]){
window.frames[0].focus();
for (var i_tem = 0; i_tem < window.frames.length; i_tem++){
if(document.all && document.body.filters)
window.frames[i_tem].document.onkeydown = new Function("var e=window.frames["+i_tem+"].event; if(e.keyCode==116){e.keyCode=0;alert('Refresh Not Allowed');return false;}if(e.keyCode==27){e.keyCode=0;alert('Escape Not Allowed');return false;};");
}
}
}catch(e){
}
}
call this method in iframe onload
I don't think there's any way to trap that... it's the equivalent of clicking the X to stop the page loading.
Assuming that you are targeting versions of IE that have attachEvent enabled, you can use this to detect the escape key being pressed. The handling of the event is the usual code for preventing default event behaviour, though this may not work on cancelling the page download as this may be seen as a security flaw (imagine the unscrupulous developer that wants to prevent the user from cancelling a malicious download):
document.attachEvent('onkeydown', function(){
if(window.event.keyCode == 27) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
});
http://jsfiddle.net/steveukx/LJHs8/
each browser has find on page functionality (ctrl+F). Is there a way to detect user searches in javascript so that I could attach additional actions.
Here is a solution which can account for alternative page find situations (ex. Command+F, '/' on Firefox). It checks for any of these keypresses and sets a timer when they occur. If the window is blurred soon after, then it is assumed that the Find dialog is showing.
Disadvantages: does not account for the "Find" dialog being launched via the menu. I don't see any way to be sure about this part, since (as far as I know, at least) browser UI is off-limits to Javascript running inside the DOM.
var keydown = null;
$(window).keydown(function(e) {
if ( ( e.keyCode == 70 && ( e.ctrlKey || e.metaKey ) ) ||
( e.keyCode == 191 ) ) {
keydown = new Date().getTime();
}
return true;
}).blur(function() {
if ( keydown !== null ) {
var delta = new Date().getTime() - keydown;
if ( delta >= 0 && delta < 1000 )
console.log('finding');
keydown = null;
}
});
jsFiddle, tested in Chrome, Safari and Firefox
You could do (to detect whenb a user press ctrl+f):
window.onkeydown = function(e){
if(e.keyCode == 70 && e.ctrlKey){
//user pressed ctrl+f
}
Fiddle here: http://jsfiddle.net/d8T72/
Of course you can try to hook into ctrl+f or cmd+f shortcut, but even if that works on "some" browsers, that way you only would know that an user pressed that shortcut and is most likely to search for something.
If the browser allows to overwrite that shortcut, you could further block the default behavior and implement your own search logic on the site. But that is considered most times as very bad practice. Overwritting native browser behavior is pretty pretty bad.
On the other hand, there is no "event" which gets triggered when a browser executed a search process. In short words, no, there actually is no way to detect or hook into a search process with javascript (if there is one, it's never gonna be cross browser compatible).
As initially suggested by #Nicola Peluchetti, here is a slightly improved version by feature sniffing:
window.onkeydown = function(e){
var ck = e.keyCode ? e.keyCode : e.which;
if(e.ctrlKey && ck == 70){
alert('Searching...');
}
}
Browser search test case »