Able to detect Ctrl+R But stop reloading page - javascript

I am able to detect Ctrl+R but unable to stop reloading page.
Please help me to fix this.
I am using this code.
$(document).keydown(function(e) {
if (e.keyCode == 65+17 && e.ctrlKey) {
alert('ctrl R');
exit;
return ;
}
});
Thanks in advance.

The standard / clean way to help user prevent unwanted page reload is via beforeunload and not via overriding key event, which is, in fact, futile: you do not know what key combination invoked page reload (for instance, f5 works alike in most browsers), he may press CTRL+R with locationbar focused so your page gets no event to capture, he may have pressed toolbar button…
Mentioned standard approach from linked MDN page
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
This will prompt user whenever he tries to reload / close / navigate away from your page no matter what initiated unload.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function () {
document.onkeydown = KeyPress;
function KeyPress(e) {
console.log(e);
var press = window.event? event : e
if (press.keyCode == 82 && press.ctrlKey) alert("Ctrl+R");
if ($.browser.mozilla) {
if (e.ctrlKey && keycode == 82) {
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
}
if ($.browser.msie) {
if (window.event.ctrlKey && press.keycode == 82) {
window.event.returnValue = false;
window.event.keyCode = 0;
window.status = "Refresh is disabled";
}
}
}
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>

Related

keyboard shortcut using javascript not working

I am using command + h as a shortcut key in my website. It is not doing the function to be done. After I click something on the window only it works flawlessly. Here is my code..
window.onkeydown = function(event) {
if (event.keyCode == 72 && (event.metaKey == true)) {
//some function
}
}
Somebody try to rectify . I have included this code only after the dom gets loaded
window.onkeydown will only work if it is focused. So on body load you should set focus.
<body onload="setFocus()">
function setFocus(){
window.focus();
}
Working DEMO HERE
You could probably make it work with focusing the body on window load with document.body.focus() and attaching an event listener like this:
window.onload = function() {
document.body.focus();
document.addEventListener("keydown", keyDownFunction, false);
};
function keyDownFunction(event) {
if(event.keyCode == 72 && (event.metaKey == true)) {
alert("You hit the right keys.");
}
}

JqueryMobile (SPA) Disable Browser backbutton and Refresh?

hi i am using jqueryMobile SPA template for my phone-gap app.
For web version my requirement is to disable or show warning message to user on click of browser back button. I googled my requirement but didn't find any desired solution.Please guide me . Thanks.
Try this-
FIDDLE
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if ( !! direction) {
alert(direction);
}
});
Please refer following link.
Refer This
Or you can use
window.history.forward(1);
when back button get pressed. But it loads and then redirected not proper way.
To disable Backbutton of browser i used
$(window).on("navigate", function (event) {
event.preventDefault();
window.history.forward(1);
});
But on pressing f5 it was creating error and redirecting me to login page.Thus i disable f5 ,ctrl+R button.
var ctrlKeyDown = false;
$(document).on("pagecreate", function (){
$(document).on("keydown", keydown);
$(document).on("keyup", keyup);
});
function keydown(e) {
if ((e.which || e.keyCode) == 116 || ((e.which || e.keyCode) == 82 && ctrlKeyDown))
{
// Pressing F5 or Ctrl+R
e.preventDefault();
} else if ((e.which || e.keyCode) == 17) {
// Pressing only Ctrl
ctrlKeyDown = true;
}
}
function keyup(e){
// Key up Ctrl
if ((e.which || e.keyCode) == 17)
ctrlKeyDown = false;
}
It completely fulfilled my requirement.Thanks to Suhas :) .

How to Disable the CTRL+P using javascript or Jquery?

Here I tried to disable the Ctrl+P but it doesn't get me alert and also it shows the print options
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
alert('fine');
return false;
}
});
http://jsfiddle.net/qaapD/10/
I am not sure how can I disable the Ctrl+P combination itself using jQuery or JavaScript.
Thanks
You can't prevent the user from printing, but you can hide everything when the user prints the document by using simple CSS:
<style type="text/css" media="print">
* { display: none; }
</style>
Updated fiddle.
If you would like to show the visitor a custom message when he/she try to print rather then just a blank page, it's possible with client side code but first wrap all your existing contents like this:
<div id="AllContent">
<!-- all content here -->
</div>
And add such a container with the custom message:
<div class="PrintMessage">You are not authorized to print this document</div>
Now get rid of the <style type="text/css" media="print"> block and the code would be:
if ('matchMedia' in window) {
// Chrome, Firefox, and IE 10 support mediaMatch listeners
window.matchMedia('print').addListener(function(media) {
if (media.matches) {
beforePrint();
} else {
// Fires immediately, so wait for the first mouse movement
$(document).one('mouseover', afterPrint);
}
});
} else {
// IE and Firefox fire before/after events
$(window).on('beforeprint', beforePrint);
$(window).on('afterprint', afterPrint);
}
function beforePrint() {
$("#AllContent").hide();
$(".PrintMessage").show();
}
function afterPrint() {
$(".PrintMessage").hide();
$("#AllContent").show();
}
Code is adopted from this excellent answer.
Updated fiddle. (showing message when printing)
After much testings on various browsers, it is easier to intercept the keys when they are down (not pressed) because some of this "App integrated keys" are difficult to intercept with the "keypress" event.
I came up with this script that is sort of cross browser compatible (I didn't test for Microsoft's IE). Notice that the browsers return different codes for some keys. In my case I wanted to prevent Ctrl+P.
The key "P" on chrome is seen as e.keyCode == 80, on opera, it is e.charCode == 16, while on firefox it is e.charCode == 112
$(document).on('keydown', function(e) {
if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
alert("Please use the Print PDF button below for a better rendering on the document");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
});
I used jQuery.
This is basically Peters answer from above. The difference is I added the accountability for mac when pressing the cmd+p button combo to print a page.
$(document).on('keydown', function(e) {
if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
alert("Please use the Print PDF button below for a better rendering on the document");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
});
To disable Ctrl+P printing by using javascript use below code:
window.addEventListener('keydown', function(event) {
if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
event.preventDefault();
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
event.stopPropagation();
}
return;
}
}, true);
Your code works in the jsfiddle example? What browser are you using? Itested it with the latest chrome and it worked fine.
You can also add:
e.preventDefault();
This Actually worked for me in chrome. I was pretty suprised.
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
Print(); e.preventDefault();
}
});
Where Print is a function I wrote that calls window.print(); It also works as a pure blocker if you disable Print();
As noted here: https://stackoverflow.com/a/20121038/2102085
window.print() will pause so you can add an onPrintFinish or onPrintBegin like this
function Print(){
onPrintBegin
window.print();
onPrintFinish();
}
(Again this is just chrome, but Peter has a downvoted solution below that claims the keycodes are different for ff and ie)
had a journy finding this, should be canceled on the keydown event
document.addEventListener('keydown',function(e){
e.preventDefault();
return false;
});
further simplified to :
document.onkeydown = function(e){
e.preventDefault();
}
given you have only one keydown event
there are some shortcuts you simply can't override with javascript, i learned it the hard way. I suppose CTRL+P is one of them.
one way to override them would be to deploy a chrome pacakged app.
Try this
//hide body on Ctrl + P
jQuery(document).bind("keyup keydown", function (e) {
if (e.ctrlKey && e.keyCode == 80) {
$("body").hide();
return false;
}
});
Here is the code, it work for me
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.key === "p") {
event.preventDefault();
}
});
<script>
function isKeyPressed(event)
{
if(event.ctrlKey == 1)
{
alert("Please Submit exam form befor printing");
}
}
</script>
<body onkeydown="isKeyPressed(event)">
<p>this is the solution</p>
</body>
If you want to disable printing of your webpage you're wasting your time: it can't be done. Even if you work out how to capture CTRL-P users can still use the browsers menu bar to find the print command, or they can take a screen shot of the browser.
Stop trying to control the user, put your energy into making your site / app more useful, not less useful.
edit 2016: in the 3 years this has been up it has gathered 3 downvotes. I'm still not deleting it. I think it is important to tell fellow developers when they are given impossible tasks, or tasks that make no sense.
edit 2018: still think it's important that people that have this question read this answer.

Unable to disable F5 key in IE8

I want to disable F5 key in my web application. I am using the following code:
<html>
<head>
<script type="text/javascript">
window.onkeydown=function(e) {
if (e.keyCode === 116 ) {
alert("This action is not allowed");
e.keyCode = 0;
e.returnValue = false;
return false;
}
}
</script>
</head>
<body>
<p> F5 Test IE8</p>
</body>
</html>
The above code works fine in Chrome but in IE8 it is not working. On pressing F5 the page gets refreshed on IE8. I have tried using e.preventDefault(), but nothing works. Any help??
Try next code:
<html>
<head>
<script type="text/javascript">
document.onkeydown=function(e) {
e=e||window.event;
if (e.keyCode === 116 ) {
e.keyCode = 0;
alert("This action is not allowed");
if(e.preventDefault)e.preventDefault();
else e.returnValue = false;
return false;
}
}
</script>
</head>
<body>
<p> F5 Test IE8</p>
</body>
</html>
You must use document object instead of window object. In IE8 window object does not support onkeydown.
You must use e=e||window.event; code line because in IE8- when event registered as element.on... no parameter is received into event handler function (e from your example is undefined);
Tested in IE8, firefox and chrome:
document.onkeydown=function(e) {
var event = window.event || e;
if (event.keyCode == 116) {
event.keyCode = 0;
alert("This action is not allowed");
return false;
}
}
Also see this example.

Internet Explorer or any Browser F1 keypress displays your own help

I would like to display the user selected help file when pressing F1. This should work on every browser where I test my application. How can I stop the default help file from being displayed?
AFAIK, the default action of the F1 key can be changed in any browser except for IE. The Microsoft teams are usually sticklers for maintaining a consistent user experience across their applications and that's why F1 opens help regardless of returning false. That being said, there's a workaround in the form of the window.onhelp event.
// Internet Explorer
if ("onhelp" in window)
window.onhelp = function () {
showMyHelpInsteadOfTheUsualDefaultHelpWindow(true);
return false;
}
// Others
else {
document.onkeydown = function(evt) {
cancelKeypress = (evt.keyCode == 112);
if (cancelKeypress) { // F1 was pressed
showMyHelpInsteadOfTheUsualDefaultHelpWindow(true);
return false;
}
}
// Additional step required for Opera
document.onkeypress = function(evt) {
if (cancelKeypress)
return false;
}
}
"Others" step was adapted from a deleted answer, which was adapted from another answer which, in turn, was adapted from another answer.
Actually, you can cancel the native Help in IE, by setting event.keyCode to 0:
Tested in IE8 & Chrome
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var cancelKeypress = false;
// Need to cancel event (only applies to IE)
if ( "onhelp" in window ) {
// (jQuery cannot bind "onhelp" event)
window.onhelp = function () {
return false;
};
}
$(document).keydown(function ( evt ) {
// F1 pressed
if ( evt.keyCode === 112 ) {
if ( window.event ) {
// Write back to IE's event object
window.event.keyCode = 0;
}
cancelKeypress = true;
// Trigger custom help here
alert("My help");
return false;
}
});
// Needed for Opera (as in Andy E's answer)
$(document).keypress(function ( evt ) {
if ( cancelKeypress ) {
cancelKeypress = false; // Only this keypress
return false;
}
});
});
</script>
</head>
<body>
</body>
</html>

Categories