I am trying to prevent page refresh only when user clicks Ctrl with R.
I try with the preventDefault() method as following but it does not work:
function disableCtrlR(s) { if ((s.which || s.keyCode) == 17 && (s.which || s.keyCode) == 82) s.preventDefault(); };
$(document).ready(function(){
$(document).on("keydown", disableCtrlR);
});
Any help on this will be appreciated. Thanks.
PS. I know this is not an ideal solution but this is the only solution for me to solve the bug on my webpage while waiting for the bug to be resolved.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on("keydown", function(e) {
e = e || window.event;
if (e.ctrlKey) {
var c = e.which || e.keyCode;
if (c == 82) {
e.preventDefault();
e.stopPropagation();
}
}
});
});
</script>
<h1>If you click in here, you won't be able to refresh with Ctrl+R</h1>
<input type="text" />
Using jQuery 2.1.1, this will disable reload by Ctrl+R
To check if there is a control key pressed simultaneously in an key event, you'll check for the KeyboardEvent.ctrlKey property.
// beware ES6 below, will fail in Netscape
onkeydown = e => {
if(e.key === 'r' && e.ctrlKey){
e.preventDefault();
console.log('ctrl + r')
}
}
<input autofocus>
Addendum:
As you mentioned in your question, this is very-much "not an ideal solution". Blocking default browser behavior should be made only on special cases, like here blocking the ctrl+R shortcut should only be done on some part of a web-application that really needs this shortcut, and not on the document itself. That's part of why I never talked about blocking the page refresh in this answer (which would need some extra work to work in this intent on all platforms).
Related
I've been having troubles with the Control + S button, I would like to remap the Control + S button to something else instead of the save page as window.
** I know that its not possible to disable it**
I want the functionality like what https://www.hastebin.com/ has, where if you control + s it does an action. I've already tried
$(window).keypress((e) => {
if (!(e.which == 115 && e.ctrlKey) && !(e.which == 19)) return true;
console.log('bruh');
e.preventDefault();
return false;
});
That DOES work, but the save as page still shows up, where as on hastebin, it does not when you do ctrl + S
Any ideas?
Use keydown rather than keypress:
$(window).on("keydown", (e) => {
if (e.key === "s" && e.ctrlKey) {
console.log("Ctrl+S");
e.preventDefault();
}
});
<div>Click here, then press Ctrl+S</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In that example I've used the key property rather than the deprecated which property, but if you need to support obsolete browsers you could use which (perhaps as a fallback).
CTRL+S fires keydown event, not keypress event AFAIK.
$(window).on("keydown", (e) => {
if (e.key === "s" && e.ctrlKey) e.preventDefault();
});
How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});
I need to implement a shortcut alt+b, calling a function. My problem is, that everytime i press this shortcut, a Firefox and an IE open a Menu-Bar "Edit". Is there any solution to prevent this default behavior? Or maybe it is possible to close this menu-bar after calling a function?
What i have tried but without success
$(document).keydown(function(e) {
if (e.keyCode == 18 || e.which==18)
{
e.preventDefault();
}
});
Try this, it will only run the console.log() if you hit Alt+B. Replace the console with anything you want.
$(window).keydown(function(event) {
if(event.altKey && event.keyCode == 66) {
event.preventDefault();
console.log("Hey! alt+B event captured!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This seems to work for me:
$(document).keydown(function(e) {
// check for alt+b
if (e.keyCode == 66 && e.altKey === true) {
e.preventDefault();
}
});
You need to check the press of b, not alt.
My code works well, but I do not need this "beforeunload warning" when reloadind same page (reload button ou F5 key) , or when a click in the "back" button...
My original working code:
<script>
window.onbeforeunload = function (e) {
var msg = '\n\n\nARE YOU SURE?\n\n\n';
e = e || window.event;
if (e)
e.returnValue = msg;
//some extra conditions
document.getElementById("popUpOut").style.display = 'block';
return msg;
}
</script>
So, this is my question: How to disable beforeunload in these situations ("back button" and "reload page)?
You can't do that. A page refresh is like navigating away and unloading the DOM so the onbeforeunload event will always be called but you can prevent it using jquery for keys pressed for Ctrl + R or F5 and Backspace.
For Ctrl + R use this:
$(document).keydown(function (e) {
if (e.keyCode == 65 && e.ctrlKey) {
e.preventDefault();
}
});
For F5 use this:
$(document).keydown(function (e) {
if (e.which || e.keyCode) == 116) {
e.preventDefault();
}
});
First of all, let me say that, ""I do not want"" stop reloading the page! BUT controll the beforeunload message!
So if you allow me, I will try to explain:
A) I just want do DECIDE in that event I show (or not) the "warning
exit message"
As far everyone say to me that, "it is impossible" do control UnbeforeUnload event, I make some tests and depending of the browser it is perfecty possible, BUT this is a "working progress rechearch"
So I know this:
1) listening the keyboard it's very easy to "chose the event" and,
what I want do show in the "warning mewssage" for each one.
2) Listening the history I can chose what happends on "Navigator's
Back button", dand do the same.
3) The code below works fine in chome...
And to control the keyboard, I have this, very simple code in JS:
document.onkeydown = KeyCheck;
function KeyCheck(e) {
var key = (window.event) ? event.keyCode : e.keyCode;
if(key==116) {flag_beforeunload=false;}
if(key==8) {flag_beforeunload=false;}
if (e.keyCode == 82 && e.ctrlKey) {flag_beforeunload=false;}
document.getElementById("container").innerHTML = "key = "+key + " - " + flag_beforeunload;
}
window.onbeforeunload = function(e){
var msg = 'You are sure to exit?';
e = e || window.event;
if(e)
if (flag_beforeunload == true) {
return msg;
}
}
Following, here (dotnsf site) is where I get the code for control the browser's "back button and"... I can even disable it.
but it is en Jquery, following is my code, but in JS:
window.onpopstate = function(event) {
window.history.back(-1)
if( !event.state ){
//the to lines below, disable the back button
// history.pushState( "nohb", null, "" );
// return;
// the following line iIcan use to control the envent, in UnBeforeUnload
// flag_beforeunload=false;
}
}
}
And finaly, this is my question:
I apreciate more help, and solutions for others navigators than Chrome!
Thanks a lot !
How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});