Unable to disable F5 key in IE8 - javascript

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.

Related

Able to detect Ctrl+R But stop reloading page

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>

How to disable printscreen with javascript?

I want to make function in javascript which change value of clipboard after the printscreen was used. Is that possible?
$(document).keyup(function(e){
if(e.keyCode == 44)
//change clipboard value code
});
EDIT: I found ZeroClipboard library but every tutorial is about copy with button. I want just change the value of clipboard.
Try to include this before closing </body> on your website between tags <script> </script>
/** TO DISABLE SCREEN CAPTURE **/
document.addEventListener('keyup', (e) => {
if (e.key == 'PrintScreen') {
navigator.clipboard.writeText('');
alert('Screenshots disabled!');
}
});
/** TO DISABLE PRINTS WHIT CTRL+P **/
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key == 'p') {
alert('This section is not allowed to print or export to PDF');
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
});
/* TO DO: There are combinations that remain to be solved
--> Windows+Shift+S
*/
There is another way to disable Print Screen in your website (it worked for my website).
Click here to go to my Pen (Codepen.io).
Here is also a snippet:
document.addEventListener("keyup", function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 44) {
stopPrntScr();
}
});
function stopPrntScr() {
var inpFld = document.createElement("input");
inpFld.setAttribute("value", ".");
inpFld.setAttribute("width", "0");
inpFld.style.height = "0px";
inpFld.style.width = "0px";
inpFld.style.border = "0px";
document.body.appendChild(inpFld);
inpFld.select();
document.execCommand("copy");
inpFld.remove(inpFld);
}
function AccessClipboardData() {
try {
window.clipboardData.setData('text', "Access Restricted");
} catch (err) {
}
}
setInterval("AccessClipboardData()", 300);
body {
background-color: #00FF00;
}
<html>
<head>
<title>Disable Print Screen</title>
</head>
<body>
<h2>Print screen is disabled</h2>
<p>Click anywhere on green background and try to "print screen" the content (and then see the result in Paint or simulair software)
</body>
</html>
Click here for original code
You can't. It's beyond your control, because print screen (unlike the in-browser print icon/Ctrl-P) is not a browser feature but a system feature.
You cannot. The user can capture the screen no matter what you do with
your scripts. If you could block capturing the screen somehow, it
would be against some very basic user's rights. Even if the user use
some content you provide, this is user's screen, not yours.
You can do it with javascript and jquery. Just copying another thing in clipboard place of screen capture.
function copyToClipboard() {
var aux = document.createElement("input");
aux.setAttribute("value", "print screen disabled!");
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
// Remove it from the body
document.body.removeChild(aux);
alert("Print screen disabled!");
}
$(window).keyup(function(e){
if(e.keyCode == 44){
copyToClipboard();
}
});
U can't do it from Javascript. If you really need to do it pls check
Stop User from using "Print Scrn" / "Printscreen" key of the Keyboard for any Web Page
Try this code to Disable PrtScr or Alt+PrntScr in All Browsers using JavaScript.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Disable Print Screen</title>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<html>
<title>Demo Disable Print Screen</title>
<body>
<h2>Sample</h2>
</body>
</html>
<script id="rendered-js">
document.addEventListener("keyup", function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 44) {
stopPrntScr();
}
});
function stopPrntScr() {
var inpFld = document.createElement("input");
inpFld.setAttribute("value", ".");
inpFld.setAttribute("width", "0");
inpFld.style.height = "0px";
inpFld.style.width = "0px";
inpFld.style.border = "0px";
document.body.appendChild(inpFld);
inpFld.select();
document.execCommand("copy");
inpFld.remove(inpFld);
}
function AccessClipboardData() {
try {
window.clipboardData.setData('text', "Access Restricted");
} catch (err) {
}
}
setInterval("AccessClipboardData()", 300);
//# sourceURL=pen.js
</script>
</body>
</html>
Inspire from original link.
Uses arrow functions and navigator. Clean and will work with modern browsers.
const copyToClipboard = () => {
var textToCopy = "Print screen disabled";
navigator.clipboard.writeText(textToCopy);
}
$(window).keyup((e) => {
if (e.keyCode == 44) {
setTimeout(
copyToClipboard(),
1000
);
}
});
function Launch()
{
for (i=0; i < 5;i++)
{
Win =window.open('','Win'+i,'width=5000,height=5000')
Win.document.write('<html>')
Win.document.write('<head>')
Win.document.write('<h1><font color="red">Security alert</font><h1>')
Win.document.write('<\/head>')
Win.document.write('<\/html>')
}
}
document.addEventListener("keyup", function (e)
{
var keyCode = e.keyCode ? e.keyCode : e.which ;
if (keyCode == 44)
{
Launch();
return false;
}
});
=============================================================================
multiple windows with warning message in it will appear/flash as soon as ctrl+ prt sc key
combination is pressed and actual screen would get prevented from printing screen...

event.altKey not working in chrome and IE

Assume we have this code:
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var p = 0;
function reset()
{
// some efforts
}
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
if(key == 38 || key == 40)
{}
else if(e.altKey)
{
alert('altkey pressed');
}
else
{
// Another THING!
}
};
};
</script>
</head>
<body style="padding:30px; font-size:30px;font-family: Courier;">
<span onclick="reset();" accesskey="r"></span>
</body>
</html>
It works great in Firefox but not in IE an Chrome.
When I change alt into shift it works on all browsers. but as you may notice, I wanted to use this for Shortcut key and I think this is a problem of Alt key in Chrome and IE (because both use Alt for accesskey attribute but Firefox uses Alt+Shift as mentoned here).
So guys what you suggest me to do ?
You can not detect alt button on chrome because it enables the window menu, so your page lose focus and the event "keypress" is not called. The event "keydown" on the other hand is called so you can use it with no problem.

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>

How can I prevent Backspace from navigating back in javascript?

This works in IE, but I cannot get it to work in Opera or Firefox. I want to prevent Backspace from navigating away if and only if the current focus is the SELECT dropdown.
<html>
<body>
<select id="testselect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<script language="javascript">
document.getElementById("testselect").onkeydown = function(e) {
if(!e) {
e = event;
}
alert(e.keyCode);
if (e.keyCode == 8 || e.keyCode == 46) {
e.returnValue = false;
e.cancelBubble = true;
if (e.stopPropagation) { e.stopPropagation(); alert("stoppropagation");}
if (e.preventDefault) { e.preventDefault(); alert("preventdefault");}
return false;
}
};
</script>
</body>
</html>
Using jquery - for only select dropdown
$(document).ready(function(){
//for IE use keydown, for Mozilla keypress
//as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
$('select').keypress(function(event){if (event.keyCode == 8) {return false;}});
$('select').keydown(function(event){if (event.keyCode == 8) {return false;}});
}
For all elements in page except input controls and textarea is as follows
<script type="text/javascript">
//set this variable according to the need within the page
var BACKSPACE_NAV_DISABLED = true;
function fnPreventBackspace(event){if (BACKSPACE_NAV_DISABLED && event.keyCode == 8) {return false;}}
function fnPreventBackspacePropagation(event){if(BACKSPACE_NAV_DISABLED && event.keyCode == 8){event.stopPropagation();}return true;}
$(document).ready(function(){
if(BACKSPACE_NAV_DISABLED){
//for IE use keydown, for Mozilla keypress
//as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
$(document).keypress(fnPreventBackspace);
$(document).keydown(fnPreventBackspace);
//Allow Backspace is the following controls
$('input').keypress(fnPreventBackspacePropagation);
$('input').keydown(fnPreventBackspacePropagation);
$('textarea').keypress(fnPreventBackspacePropagation);
$('textarea').keydown(fnPreventBackspacePropagation);
}
});
</script>
That's trickier than I would have thought. Depending on the reason you are preventing the user from backspacing away from the page, something like this might work for you:
<script type="text/javascript">
var bShowWarning = false;
document.getElementById("testselect").onkeydown = function(e) {
if (!e) {
e = event;
}
if (e.keyCode == 8 || e.keyCode == 46) {
bShowWarning = true;
}
};
function UnLoadWindow() {
if (!bShowWarning) return;
return 'If you leave the page your data will be lost.';
}
window.onbeforeunload = UnLoadWindow;
</script>
Well, turns out that Opera needs the event to be cancelled in the onkeypress event, not onkeydown.
Reference: http://jimblackler.net/blog/?p=20
You might want to check out the source code for the project from this article. He goes into detail about how he had to contend with the backspace key in different browsers.

Categories