can not disable Ctrl+O by JavaScript in IE 11 - javascript

I'm trying to disable Ctrl+o key combination in IE, the following code works fine in all IE versions except IE 11 unless I do an alert as you see in code below:
document.onkeydown = function(event) {
var x = event.keyCode;
console.log(event.keyCode);
console.log(event.ctrlKey);
if ((x == 79) && (event.ctrlKey)) {
if(navigator.userAgent.match(/rv:11.0/i)){
alert('Disabled');
}
event.cancelBubble = true;
event.returnValue = false;
event.keyCode = 0;
event.stopPropagation();
event.preventDefault();
return false;
}
};
I was wondering if anyone else is experiencing the same issue and they have solved it. :-)
Thanks.
Alex

I have no good solution unfortunately, but have created a case with Microsoft, and made a jfiddle that demonstrates the issue.
The only way we have found around this is the use of the:
<meta http-equiv="X-UA-Compatible" content="IE=7">
header, but there's no telling when support for that will go away - not to mention the obvious side-effects of running in IE7 mode.
Some additional notes:
Although the interception works natively on IE8 and IE9, only the IE=7 UA mode works
A page reload is required for the header to take effect, whether it is in the page or returned in the server response i.e. you cannot selectively jump in an out of IE7 mode in a single page app
Here is a link to the standards that IE11 was built against: http://www.w3.org/TR/DOM-Level-3-Events/#KeyboardEvent-supplemental-interface
Fiddle:
http://jsfiddle.net/bw5sLd15/1/
// The kitchen sink
function killKey( event ) {
event.cancelBubble = true;
event.bubbles = false;
event.returnValue = false;
event.stopPropagation();
event.stopImmediatePropagation();
event.preventDefault();
return false;
}

I came to the same conclusion as Alex & Max. In my specific use case, forcing compatibility mode would break other features.
I believe that in most cases a confirm dialog is the best workaround, as it still feels somewhat natural to the user - save for the extra step involved.
http://jsfiddle.net/dperish/sp72c0wt/3/
HTML:
<h1>Demonstration of IE11 event bubbling issue</h1>
<label>Enable Workaround<input type="checkbox" id="enableWorkaround"></label>
<p>Pressing CTRL-P or CTRL-O should NOT show the default open/print dialogs. The only workaround seems to be to interrupt the main thread either with alert(), confirm(), or by hitting a breakpoint in a debugger. </p>
<p>Unfortunately, a synchronous/blocking XHR call was not useful for this purpose. Nor was using the browser-specific showModalDialog.</p>
<div id="output"></div>
Javascript:
function onKeyDown(e) {
e = e || window.event;
if ((e.keyCode === 79 || e.keyCode === 80) && e.ctrlKey) {
e.preventDefault();
e.stopPropagation();
e.returnValue = false;
if ($("#enableWorkaround").is(":checked")) {
if (confirm("Run some custom method?")) {
customMethod(e.keyCode);
}
}
else {
customMethod(e.keyCode);
}
return false;
}
}
function customMethod(x) {
$("#output").append("<p>CustomMethod Says: KeyCode = " + x + "</p>");
return false;
}
$(document).ready(function() {
$(document).on("keydown", function (e) {
onKeyDown(e);
});
});

Related

How to disable CNTRL operation in javascript for all versions of IE , Mozilla and Chrome browsers

How to disable CNTRL operation in javascript for all versions of IE , chrome and Mozilla. I have referred many examples available Online, but they all used an alert message to display that CNTRL operation is disabled. But I need an solution without using an alert message to disable CNTRL operation. I have tried a few examples one such javascript example have been enclosed.
Example:-
function Disable_Control_C(event){
if (window.event && window.event.keyCode == 17){//For IE browser
alert('CTRL Key has been Disabled.')
return false;
}else if(event.ctrlKey){
alert('CTRL Key has been Disabled..')
return false;
}
}
Above javascript function has been called as follows.
<body onkeydown="return Disable_Control_C(event)">
Try:
function disableControl(e) {
if (window.event && window.event.keyCode == 17){
e.preventDefault();
return false;
} else if(event.ctrlKey){
e.preventDefault();
return false;
}
}
window.addEventListener('keypress', disableControl);
window.addEventListener('keydown', disableControl);

how do i prevent scroll down in javascript?

ok... I might be a lazy one to search but it is a bit annoying that all I can find is
"how can i set scroll down event" when I searched "how do i prevent scroll down".
in my javascript code, I set event for down arrow key. When I press down arrow
from the browser, the browser not only does an event I set, but also does
scrolling down the page which is not I intended to. So here is my question.
How can I disable scroll down function which occurs when I press down arrow?
any help will be appreciated.
If you want to prevent the vertical scrollbar and any vertical scrolling action by the user, you can use this javascript:
document.body.style.overflowY = "hidden";​
Or, this can also be set with a CSS rule:
body {overflow-y: hidden;}
On the other hand, if what you're trying to do is to prevent the default key handler for the down arrow from doing anything after you process the down array, then you need to call e.preventDefault() like this:
function myKeyDownHandler(e) {
// your code here
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false; // older versions of IE (yuck)
}
return false;
}
A cleaner way if you need to do this in more than one place would be to make your own cross browser function for this:
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false; // older versions of IE (yuck)
}
}
function myKeyDownHandler(e) {
// your code here
preventDefault(e);
return false;
}
This is one of those perfect examples where a cross-browser framework (jQuery/YUI/etc) saves you time because they've already done all this cross-browser work for you.
Here's an interesting article on preventDefault and stopPropagation().
Here is an example page that doesn't allow for the use of the arrow keys for scrolling:
<script>
document.onkeydown = function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
if (keyCode >= 37 && keyCode <= 40) {
return false;
}
};
</script>
<body style="height:3000px;">
</body>

problem with keypress (in jquery) with IE

problem with keypress (in jquery) with IE
$(document).keypress(function(key) {
if (key.which == 99 && key.metaKey == true) {
alert("Don't Copy");
return false;
}
});
It doesn't work !
How can I fix it ?
I think you want to check the status of ctrlKey to block Ctrl + C:
$(document).keydown(function(key) {
if (key.which == 67 && key.ctrlKey) {
alert("Don't Copy");
return false;
}
});
It does work on all major browsers (FF4b7, IE 8), but not entirely correct in Chrome 8: although the alert pops up, the copy-to-clipboard behaviour is not suppressed.
That said, if you want to prevent the user from copying your texts to the clipboard, I'll have to disappoint you: someone can simply use the (context) menu option or view your page's source. There's nothing that you can do about that.
why keypress?
$('*').bind('copy',function(key) {
alert("Don't Copy");
return false;
});

Overriding Browser's Keyboard Shortcuts

I'd like to add support for keyboard shortcuts to a couple of pages in my web application by intercepting the keypress event handler of the document object, not the accesskey attribute.
The problem is that every browser has its own keyboard combinations, so it's impossible to come up with a set of keyboard combinations that work on all web browsers and yet consistent.(e.g. It'd be silly if the shortcut for save was Ctrl + Shift + S while one for delete was Alt + D.)
So I figured it would be just simpler to override browser shortcuts altogether in a couple of pages with mine.
All downside aside, is it possible? If so, how do you do it?
onkeydown = function(e){
if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){
e.preventDefault();
//your saving code
}
}
There's an excellent coverage of this here: http://unixpapa.com/js/key.html
As for whether this is something that should be done, stackoverflow's question editor override's quite a few keys without disrupting too much (hover over the toolbar buttons).
Here is my solution to this problem:
Most (if not all) of the browser's shortcuts will be overriden. Only system ones, like Alt + Tab or the Windows key won't.
document.onkeydown = overrideKeyboardEvent;
document.onkeyup = overrideKeyboardEvent;
var keyIsDown = {};
function overrideKeyboardEvent(e){
switch(e.type){
case "keydown":
if(!keyIsDown[e.keyCode]){
keyIsDown[e.keyCode] = true;
// do key down stuff here
}
break;
case "keyup":
delete(keyIsDown[e.keyCode]);
// do key up stuff here
break;
}
disabledEventPropagation(e);
e.preventDefault();
return false;
}
function disabledEventPropagation(e){
if(e){
if(e.stopPropagation){
e.stopPropagation();
} else if(window.event){
window.event.cancelBubble = true;
}
}
}
Here is my Solution:
document.onkeydown = function () {
if ((window.event.keyCode == 121) && (window.event.ctrlKey))) {
window.event.returnValue = false;
window.event.cancelBubble = true;
window.event.keyCode = 0;
return false;
}
}

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

I want to handle F1-F12 keys using JavaScript and jQuery.
I am not sure what pitfalls there are to avoid, and I am not currently able to test implementations in any other browsers than Internet Explorer 8, Google Chrome and Mozilla FireFox 3.
Any suggestions to a full cross-browser solution? Something like a well-tested jQuery library or maybe just vanilla jQuery/JavaScript?
I agree with William that in general it is a bad idea to hijack the function keys. That said, I found the shortcut library that adds this functionality, as well as other keyboard shortcuts and combination, in a very slick way.
Single keystroke:
shortcut.add("F1", function() {
alert("F1 pressed");
});
Combination of keystrokes:
shortcut.add("Ctrl+Shift+A", function() {
alert("Ctrl Shift A pressed");
});
The best source I have for this kind of question is this page: http://www.quirksmode.org/js/keys.html
What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).
I am not sure if intercepting function keys is possible, but I would avoid using function keys all together. Function keys are used by browsers to perform a variety of tasks, some of them quite common. For example, in Firefox on Linux, at least six or seven of the function keys are reserved for use by the browser:
F1 (Help),
F3 (Search),
F5 (Refresh),
F6 (focus address bar),
F7 (caret browsing mode),
F11 (full screen mode), and
F12 (used by several add-ons, including Firebug)
The worst part is that different browsers on different operating systems use different keys for different things. That's a lot of differences to account for. You should stick to safer, less commonly used key combinations.
It is very simple.
$(function(){
//Yes! use keydown because some keys are fired only in this trigger,
//such arrows keys
$("body").keydown(function(e){
//well so you need keep on mind that your browser use some keys
//to call some function, so we'll prevent this
e.preventDefault();
//now we caught the key code.
var keyCode = e.keyCode || e.which;
//your keyCode contains the key code, F1 to F12
//is among 112 and 123. Just it.
console.log(keyCode);
});
});
Without other external class you can create your personal hack code simply using
event.keyCode
Another help for all, I think is this test page for intercept the keyCode (simply copy and past in new file.html for testing your event).
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
td,th{border:2px solid #aaa;}
</style>
<script type="text/javascript">
var t_cel,tc_ln;
if(document.addEventListener){ //code for Moz
document.addEventListener("keydown",keyCapt,false);
document.addEventListener("keyup",keyCapt,false);
document.addEventListener("keypress",keyCapt,false);
}else{
document.attachEvent("onkeydown",keyCapt); //code for IE
document.attachEvent("onkeyup",keyCapt);
document.attachEvent("onkeypress",keyCapt);
}
function keyCapt(e){
if(typeof window.event!="undefined"){
e=window.event;//code for IE
}
if(e.type=="keydown"){
t_cel[0].innerHTML=e.keyCode;
t_cel[3].innerHTML=e.charCode;
}else if(e.type=="keyup"){
t_cel[1].innerHTML=e.keyCode;
t_cel[4].innerHTML=e.charCode;
}else if(e.type=="keypress"){
t_cel[2].innerHTML=e.keyCode;
t_cel[5].innerHTML=e.charCode;
}
}
window.onload=function(){
t_cel=document.getElementById("tblOne").getElementsByTagName("td");
tc_ln=t_cel.length;
}
</script>
</head>
<body>
<table id="tblOne">
<tr>
<th style="border:none;"></th><th>onkeydown</th><th>onkeyup</th><th>onkeypress</td>
</tr>
<tr>
<th>keyCode</th><td> </td><td> </td><td> </td>
</tr>
<tr>
<th>charCode</th><td> </td><td> </td><td> </td>
</tr>
</table>
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">CLEAR</button>
</body>
</html>
Here is a working demo so you can try it right here:
var t_cel, tc_ln;
if (document.addEventListener) { //code for Moz
document.addEventListener("keydown", keyCapt, false);
document.addEventListener("keyup", keyCapt, false);
document.addEventListener("keypress", keyCapt, false);
} else {
document.attachEvent("onkeydown", keyCapt); //code for IE
document.attachEvent("onkeyup", keyCapt);
document.attachEvent("onkeypress", keyCapt);
}
function keyCapt(e) {
if (typeof window.event != "undefined") {
e = window.event; //code for IE
}
if (e.type == "keydown") {
t_cel[0].innerHTML = e.keyCode;
t_cel[3].innerHTML = e.charCode;
} else if (e.type == "keyup") {
t_cel[1].innerHTML = e.keyCode;
t_cel[4].innerHTML = e.charCode;
} else if (e.type == "keypress") {
t_cel[2].innerHTML = e.keyCode;
t_cel[5].innerHTML = e.charCode;
}
}
window.onload = function() {
t_cel = document.getElementById("tblOne").getElementsByTagName("td");
tc_ln = t_cel.length;
}
td,
th {
border: 2px solid #aaa;
}
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<table id="tblOne">
<tr>
<th style="border:none;"></th>
<th>onkeydown</th>
<th>onkeyup</th>
<th>onkeypress</td>
</tr>
<tr>
<th>keyCode</th>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th>charCode</th>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">CLEAR</button>
</body>
</html>
Solution in ES6 for modern browsers and IE11 (with transpilation to ES5):
//Disable default IE help popup
window.onhelp = function() {
return false;
};
window.onkeydown = evt => {
switch (evt.keyCode) {
//ESC
case 27:
this.onEsc();
break;
//F1
case 112:
this.onF1();
break;
//Fallback to default browser behaviour
default:
return true;
}
//Returning false overrides default browser event
return false;
};
This works for me.
if(code ==112) {
alert("F1 was pressed!!");
return false;
}
F2 - 113,
F3 - 114,
F4 - 115,
and so fort.
You can use Vanilla Javascript and the KeyboardEvents keydown, keypress or keyup.
Use event.key (preferably) or event.code and compare them against the key name like event.key === "F1".
When working with Function keys you probably want to suppress the default behaviour (On windows many of the function keys are used by the browser).
This can be achieved by calling preventDefault() on the keydown event.
Even if you want to listen to the keyup event you need to call preventDefault() on the keydown event, because the browser shortcut is bound to that event.
Keep in mind, that calling preventDefault() on keydown will also suppress the keypress event.
document
.addEventListener("keydown", e => {
if(e.key === "F1") {
// Suppress default behaviour
// e.g. F1 in Microsoft Edge on Windows usually opens Windows help
e.preventDefault()
}
})
document
.addEventListener("keyup", e => {
if(e.key === "F1") {
// Handle the keyup event
doSomething()
}
})
One of the problems in trapping the F1-F12 keys is that the default function must also be overridden. Here is an example of an implementation of the F1 'Help' key, with the override that prevents the default help pop-up. This solution can be extended for the F2-F12 keys. Also, this example purposely does not capture combination keys, but this can be altered as well.
<html>
<head>
<!-- Note: reference your JQuery library here -->
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
<h1>F-key trap example</h1>
<div><h2>Example: Press the 'F1' key to open help</h2></div>
<script type="text/javascript">
//uncomment to prevent on startup
//removeDefaultFunction();
/** Prevents the default function such as the help pop-up **/
function removeDefaultFunction()
{
window.onhelp = function () { return false; }
}
/** use keydown event and trap only the F-key,
but not combinations with SHIFT/CTRL/ALT **/
$(window).bind('keydown', function(e) {
//This is the F1 key code, but NOT with SHIFT/CTRL/ALT
var keyCode = e.keyCode || e.which;
if((keyCode == 112 || e.key == 'F1') &&
!(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
{
// prevent code starts here:
removeDefaultFunction();
e.cancelable = true;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
// Open help window here instead of alert
alert('F1 Help key opened, ' + keyCode);
}
// Add other F-keys here:
else if((keyCode == 113 || e.key == 'F2') &&
!(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
{
// prevent code starts here:
removeDefaultFunction();
e.cancelable = true;
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
// Do something else for F2
alert('F2 key opened, ' + keyCode);
}
});
</script>
</body>
</html>
I borrowed a similar solution from a related SO article in developing this. Let me know if this worked for you as well.
My solution to this problem is:
document.onkeypress = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
return false;
}
}
With the magic number 123 which is the key F12.
Consider that your app will not be remotely mobile friendly.
Just add this event listener:
function keyDown(e)
{
let charStr, key = e.which || e.keyCode;
if (key >= 112 && key <= 123)
{
e.preventDefault();
e.stopPropagation();
charStr = "F" + (key - 111);
switch (charStr)
{
case "F1":
alert("F1");
break;
case "F2":
alert("F2");
break;
default:
alert("Other F key");
break;
}
}
}
document.addEventListener('keydown', keyDown);
This has very good browser compatibility. I don't know about Internet Explorer 8 or Mozilla FireFox 3, but hardly still relevant in 2022.
Add a shortcut:
$.Shortcuts.add({
type: 'down',
mask: 'Ctrl+A',
handler: function() {
debug('Ctrl+A');
}
});
Start reacting to shortcuts:
$.Shortcuts.start();
Add a shortcut to “another” list:
$.Shortcuts.add({
type: 'hold',
mask: 'Shift+Up',
handler: function() {
debug('Shift+Up');
},
list: 'another'
});
Activate “another” list:
$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
type: 'hold',
mask: 'Shift+Up',
list: 'another'
});
Stop (unbind event handlers):
$.Shortcuts.stop();
Tutorial:
http://www.stepanreznikov.com/js-shortcuts/
Try this solution if works.
window.onkeypress = function(e) {
if ((e.which || e.keyCode) == 116) {
alert("fresh");
}
}
You can do this with jquery like this:
$("#elemenId").keydown(function (e) {
if(e.key == "F12"){
console.log(e.key);
}
});

Categories

Resources