event.altKey not working in chrome and IE - javascript

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.

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...

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.

How can I capture keyboard events are from which keys?

I googled and got the following codes on the Net.However, when I press a keyboard key,it is not displaying me an alert box. I want to get which character I have pressed in the alert box. How do I fix this?
<script type="text/javascript">
var charfield=document.getElementById("char")
charfield.onkeydown=function(e){
var e=window.event || e;
alert(e.keyCode);
}
</script>
</head>
<body id="char">
</body>
</html>
If you want to get the character typed, you must use the keypress event rather than the keydown event. Something like the following:
var charfield = document.getElementById("char");
charfield.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode > 0) {
alert("Typed character: " + String.fromCharCode(charCode));
}
};
try this jquery code
$("body").keypress(function(e){
alert(e.which);
});
I can't off the top of my head think of a good situation in which to use the "on some event" method of a DOM element to deal with events on that element.
The best practice is to use addEventListener (or attachEvent in older versions of Internet Explorer) like so:
charfield.addEventListener('keydown', function (e) { alert(e.keyCode); }, false);
If you want to account for attachEvent as well:
(function (useListen) {
if (useListen) {
charfield.addEventListener('keydown', alertKeyCode, false);
} else {
charfield.attachEvent('onkeydown', alertKeyCode);
}
})(charfield.addEventListener);
function alertKeyCode(e) {
alert(e.keyCode);
}
You'll get the appropriate key code:
charfield.onkeydown=function(evt){
var keyCode = (evt.which?evt.which:(evt.keyCode?evt.keyCode:0))
alert(keyCode);
}

How to hijack key combos in javascript?

In Gmail, for example, when one presses Ctrl + B, instead of it getting passed to the browser (which would normally bring up some sort of bookmark manager), it hijacks it for formatting purposes, i.e. turn on bold formatting for the message ur in the middle of comoposing. Same for Ctrl+i, Ctrl+u.
How is this done?
You would attach an onkeydown or onkeyup event handler to the global document object. For example, if I wanted to make the title bar change to "asdf" each time Ctrl-M was pressed, I would register the event handler through window.onload, like this:
window.onload = function()
{
document.onkeydown = function(event)
{
var keyCode;
if (window.event) // IE/Safari/Chrome/Firefox(?)
{
keyCode = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyCode = event.which;
}
var keyChar = String.fromCharCode(keyCode).toLowerCase();
if (keyChar == "m" && event.ctrlKey)
{
document.title = "asdf";
return false; // To prevent normal minimizing command
}
};
};
W3Schools has more information on using these events: onkeydown and onkeyup.
Also, I think I should note that there are some discrepancies across browsers in regards to the event properties (like, for example, in Firefox, you're supposed to access the keycode through event.which, while in IE it's event.keyCode, although Firefox may support event.keycode—confusing, isn't it?). Due to that, I'd recommend doing this stuff through a JavaScript framework, such as Prototype or jQuery, as they take care of all the icky compatibility stuff for you.
Here is the source for an HTML page that uses jQuery and does what htw's solution does.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Hijack Example</title>
<script type="text/javascript" src="../scripts/jquery-1.2.1.js">
</script>
<script type="text/javascript">
$(function(){
document.title = "before keypress detected";
$(document).keydown(function(event) {
// alert('stuff happened: ' + msg + " " + event.keyCode);
var keyChar = String.fromCharCode(event.keyCode).toLowerCase();
if (keyChar == "m" && event.ctrlKey) {
document.title = "ctrl-m pressed!";
}
});
});
</script>
</head>
<body id="body">
<p>Change the path to jquery above as needed (search for ../scripts/jquery-1.2.1.js)</p>
<p>Watch the title bar, then press control-M, then watch the title bar again!</p>
</body>
</html>
Hope this helps somebody!
Use the onkeydown or onkeyup event to fire a handler function:
var body = document.getElementsByTagName("body")[0];
body.onkeydown = function(event) {
var str = "";
for (var prop in event) {
str += prop + ": " + event[prop] + "<br>";
}
body.innerHTML = str;
};
With that you can see what properties an event object has.

Categories