I'm working on a cross browser paste capture. I've got this working & tested in Chrome and Firefox (on a mac). It should work on Chrome and Firefox on a PC as well but I have not had a chance to test it yet. Hopefully I'm not reinventing the wheel, I've looked for a good bit for a jQuery plugin or any javascript really that implements document-wide pasting.
This is not yet working in Opera (version 11.52) (on a mac, haven't tested on a PC). My issue is that when the cmd key is pressed, when I press the v key I do not get a keydown event. I'm not sure how to fix the issue as I'm not very framilar with Opera.
Work-in-progress jsfiddle is here.
The javascript below will not work as is, please see the jsfiddle for a working script. To make the script below work you need this os detection plugin.
Question to answer - How do I make this work in Opera?
Comments to leave if you like - Does this work for you? (post browser, os versions in comment)
update - Based on the comment Baez left this is a Opera on mac only issue.
update2 - I've updated the jsfiddle, its simplified the code a bit but still can't get it to work in mac Opera.
javascript (jquery)
$(document).ready(function() {
// Fake paste
var doFakePaste = false;
$(document).on('keyup', function(e) {
$('#status').html('');
if (($.client.os === "Mac" && e.which == 86 && e.metaKey) ||
($.client.os !== "Mac" && e.which == 86 && e.ctrlKey)) {
doFakePaste = false;
$('#paste').blur().remove();
}
}).on('keydown', function(e) {
$('#status').html('which: ' + e.which);
if (($.client.os === "Mac" && e.which == 86 && e.metaKey) ||
($.client.os !== "Mac" && e.which == 86 && e.ctrlKey)) {
doFakePaste = true;
// got a paste
$('<div></div>').attr('contenteditable', '').attr('id', 'paste').appendTo('body').on('paste', function(e) {
setTimeout(function() {
doFakePaste = false;
var html = $('#paste').html();
var text = $('#paste').text();
$('#resultA').text(html);
$('#resultB').text(text);
$('#paste').blur().remove();
}, 1);
}).focus();
}
});
$('#data').html('os: ' + $.client.os + ' browser: ' + $.client.browser);
});
html - Again see the jsfiddle for a working copy
<p>Click in this window and do a paste (ctrl-v or cmd-v). The pasted text will show up in the boxes below. I hope... the left box will be the HTML and the right box will be the TEXT.</p>
<div id="status"></div>
<div id="data"></div>
<div id="resultA"></div>
<div id="resultB"></div>
Not full answer, but part of my experience:
You can remove $.client.os and use e.which == 86 && (e.metaKey || e.ctrlKey)
You binded event on document. Bind event on div[contenteditable="true"] - may be it helps
Your code: attr('contenteditable', ''). contenteditable can be true, false and inherit ( = get value from parent )
Related
I have a web-application in which I use accesskey attribute to certain buttons. However I can't set alt + F accesskey since it opens the File menu of the firefox. I have tried the following code
onkeydown = function(e){
if(e.altKey && e.keyCode == 'F'.charCodeAt(0)) {
e.stopImmediatePropagation();
e.stopPropagation();
return false;
}
}
It doesn't seems like working in firefox but works fine in chrome. All other alt key combinations can be overridden except alt+F (file menu), alt+E(Edit menu), alt+V(View), alt+S(History), alt+B(Bookmark), alt+T(Tools), alt+H(Help) in firefox.
I am running it in Ubuntu. Is there a way to do it? It should be working in both Windows and Linux.
For alt + f or alt + F
following piece of code will work.
onkeydown = function(e){
if(event.altKey && event.keyCode == 70) {
console.log("alt + f pressed")
event.preventDefault();
}
}
if by saying alt + F - you mean you want to do alt + shift + f/F - following code will work in that case
onkeydown = function(e){
if(event.altKey && event.shiftKey && event.keyCode == 70) {
console.log("alt + shift + f/F pressed")
event.preventDefault();
}
}
Rest of the combinations will work in similar manner
Refer to the key code chart here
I have a need for an input (type='text') to go send results to the my server to check availability of something typed by the user.
I use the delegate to add the event handlers to the elements:
$(document).delegate('#signup', 'pageshow', function() {
var keydown = function(e) {
e = e || window.event;
var char = e.which || e.keyCode;
if (char == 8) {
$(".pagemessage").text("Pressed: '<BACKSPACE>'");
appcheckDomainOnKeyDown();
}
return true;
};
var keyup = function(e) {
e = e || window.event;
var char = e.which || e.keyCode;
if (char == 8) {
appcheckDomainOnKeyUp();
}
return true;
};
var keypress = function(e) {
e = e || window.event;
var char = e.which || e.keyCode;
var str = String.fromCharCode(char);
$(".pagemessage").text("Pressed: '" + str +"'");
if (/[a-zA-Z0-9-\._]/.test(str) || char == 8 || char == 9) {
appcheckDomainOnKeyDown();
appcheckDomainOnKeyUp();
return true;
}
return false;
};
The key handers work perfectly on my desktop but not on a mobile device. Hopefully you can see that I'm trying to allow certain characters into the box (and a backspace to delete the characters.
From the fact I cannot see the pagemessage element update, 'keypress' does not seem to be trapped. I tried handling this in the keyup/keydown, but I'm not sure how to apply the shiftKey bits to get an actual character pressed - for example pressing + 5 would give '%' however in the keydown it returns shiftKey and 5.
I read the documentation and the closest I could find to 'keypress' was a 'tap' event, but that didn't work either.
I have tried trapping the 'keypress' event as suggested in one post here, and on a desktop this does not trap the backspace, and does nothing at all on a mobile device.
I then tried this as suggested in another post:
var inputEV = 'oninput' in window ? 'input' : 'keyup';
$("#new_domain").off(inputEV);
$("#new_domain").on(inputEV, function (e) {
keydown(e);
keyup(e);
});
and it does not work in either desktop browser or mobile device.
I then tried changing the input type to 'search', and I get a pretty enhancement, that a keypress does add a clear button... but does nothing on the mobile device regarding my own functionality.
I think I have run out of things to try, the only thing left is to add a button to go check - and no one wants that :)
Anyone know how I can do what I need?
In case it's relevant, I'm using chrome on my desktop and android device (HTC one, and Nexus 5)
Keyup should work. It works in this example: http://jsbin.com/aNEBIKA/2/. That tested find on my Galaxy S3. Each keypress updates the footer h3 element with the text entered.
Could it be that you are binding your listeners at the wrong time? The documentation does suggest binding like this:
$(document).bind('pageinit')
http://demos.jquerymobile.com/1.2.0/docs/api/events.html
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.
In the snippet below, Ctrl+Enter (event.which == 13) is working. However, Ctrl+R (event.which == 9) is not.
if ($('.selector')) {
$(document).keypress(function(event) {
if ( event.altKey && event.which == 13 ) {
$('.link a').trigger('click');
} else if ( event.altKey && event.which == 82 ) {
$('.link a').trigger('click');
} else {
return false;
}
});
}
The problem with your code is the keyPress listener behaves differently and uses a different set of keyCode. For keyPress the r key is 114 while for keyDown it is 82.
Also another problem is browser's default reload function will override your function because keypress is executed after you release the key. To solve this, change keypress to keydown.
$(document).keydown(function(e){
if(e.which === 82 && e.ctrlKey){ //keycode is 82 for keydown
alert("Pressed!");
e.preventDefault(); //stop browser from reloading
}
});
http://jsfiddle.net/DerekL/3P9NS/show
PS: It seems like Firefox is ignoring e.preventDefault (which by W3C standards it should). The best thing to do to support all browsers is to choose another combination, or use ctrl + alt + r.
if(e.which === 82 && e.ctrlKey && e.altKey){
Based on some quick testing at http://api.jquery.com/event.which/, it seems you want event.which == 82, not event.which == 9. Although most browsers tend to use Ctrl + R to refresh the page, so this might not be the best way to handle whatever you're doing.
A cross-Browser solution to prevent Ctrl+R refresh page:
LIVE DEMO (works in Firefox, Chrome, Safari, Opera)
var keyEv = navigator.userAgent.indexOf('Firefox')>-1?["keypress",114]:["keydown",82];
$(document)[keyEv[0]](function(e) {
if ( e.ctrlKey && e.which == keyEv[1] ){
e.preventDefault();
alert("CTRL+R");
}
});
By simply testing for our navigator.userAgent you can decide what Key event listener to use and the respective R key code.
If you need to handle both R and ENTER in combination with Ctrl than you just need this little tweak:
LIVE DEMO (again all browsers :) )
var keyEv = navigator.userAgent.indexOf('Firefox')>-1?["keypress",114]:["keydown",82];
$(document)[keyEv[0]](function(e) {
var k = e.which;
if ( e.ctrlKey && k==keyEv[1] || k==13 ){ // no XBrowser issues with 13(Enter)
// so go for it!
e.preventDefault();
alert("Do something here");
}
});
My users would like to be able to hit Ctrl+S to save a form. Is there a good cross-browser way of capturing the Ctrl+S key combination and submit my form?
App is built on Drupal, so jQuery is available.
This works for me (using jquery) to overload Ctrl+S, Ctrl+F and Ctrl+G:
$(window).bind('keydown', function(event) {
if (event.ctrlKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 's':
event.preventDefault();
alert('ctrl-s');
break;
case 'f':
event.preventDefault();
alert('ctrl-f');
break;
case 'g':
event.preventDefault();
alert('ctrl-g');
break;
}
}
});
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
Key codes can differ between browsers, so you may need to check for more than just 115.
You could use a shortcut library to handle the browser specific stuff.
shortcut.add("Ctrl+S",function() {
alert("Hi there!");
});
This jQuery solution works for me in Chrome and Firefox, for both Ctrl+S and Cmd+S.
$(document).keydown(function(e) {
var key = undefined;
var possible = [ e.key, e.keyIdentifier, e.keyCode, e.which ];
while (key === undefined && possible.length > 0)
{
key = possible.pop();
}
if (key && (key == '115' || key == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true;
});
This one worked for me on Chrome...
for some reason event.which returns a capital S (83) for me, not sure why (regardless of the caps lock state) so I used fromCharCode and toLowerCase just to be on the safe side
$(document).keydown(function(event) {
//19 for Mac Command+S
if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-s pressed");
event.preventDefault();
return false;
});
If anyone knows why I get 83 and not 115, I will be happy to hear, also if anyone tests this on other browsers I'll be happy to hear if it works or not
I combined a few options to support FireFox, IE and Chrome. I've also updated it to better support mac
// simply disables save event for chrome
$(window).keypress(function (event) {
if (!(event.which == 115 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) && !(event.which == 19)) return true;
event.preventDefault();
return false;
});
// used to process the cmd+s and ctrl+s events
$(document).keydown(function (event) {
if (event.which == 83 && (navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey)) {
event.preventDefault();
save(event);
return false;
}
});
$(document).keydown(function(e) {
if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try pressing ctrl+s somewhere.
This is an up-to-date version of #AlanBellows's answer, replacing which with key. It also works even with Chrome's capital key glitch (where if you press Ctrl+S it sends capital S instead of s). Works in all modern browsers.
I would like Web applications to not override my default shortcut keys, honestly. Ctrl+S already does something in browsers. Having that change abruptly depending on the site I'm viewing is disruptive and frustrating, not to mention often buggy. I've had sites hijack Ctrl+Tab because it looked the same as Ctrl+I, both ruining my work on the site and preventing me from switching tabs as usual.
If you want shortcut keys, use the accesskey attribute. Please don't break existing browser functionality.
#Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis.
Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets Ctrl+Del as "Blockquote" rather than "delete word forward". I'm curious if there's a standard list somewhere of "browser-safe" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.
To Alan Bellows answer: !(e.altKey) added for users who use AltGr when typing (e.g Poland). Without this pressing AltGr+S will give same result as Ctrl+S
$(document).keydown(function(e) {
if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true; });
I like this little plugin. It needs a bit more cross browser friendliness though.
This should work (adapted from https://stackoverflow.com/a/8285722/388902).
var ctrl_down = false;
var ctrl_key = 17;
var s_key = 83;
$(document).keydown(function(e) {
if (e.keyCode == ctrl_key) ctrl_down = true;
}).keyup(function(e) {
if (e.keyCode == ctrl_key) ctrl_down = false;
});
$(document).keydown(function(e) {
if (ctrl_down && (e.keyCode == s_key)) {
alert('Ctrl-s pressed');
// Your code
return false;
}
});
example:
shortcut.add("Ctrl+c",function() {
alert('Ok...');
}
,{
'type':'keydown',
'propagate':false,
'target':document
});
usage
<script type="text/javascript" src="js/shortcut.js"></script>
link for download: http://www.openjs.com/scripts/events/keyboard_shortcuts/#
This Plugin Made by me may be helpful.
Plugin
You can use this plugin you have to supply the key Codes and function to be run like this
simulatorControl([17,83], function(){
console.log('You have pressed Ctrl+Z');
});
In the code i have displayed how to perform for Ctrl+S. You will get Detailed Documentation On the link. Plugin is in JavaScript Code section Of my Pen on Codepen.
I solved my problem on IE, using an alert("With a message") to prevent default Behavior:
window.addEventListener("keydown", function (e) {
if(e.ctrlKey || e.metaKey){
e.preventDefault(); //Good browsers
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { //hack for ie
alert("Please, use the print button located on the top bar");
return;
}
}
});
This was my solution, which is much easier to read than other suggestions here, can easily include other key combinations, and has been tested on IE, Chrome, and Firefox:
$(window).keydown(function(evt) {
var key = String.fromCharCode(evt.keyCode).toLowerCase();
switch(key) {
case "s":
if(evt.ctrlKey || evt.metaKey) {
fnToRun();
evt.preventDefault(true);
return false;
}
break;
}
return true;
});
A lot of answers in this thread mention e.which or e.Keycode which are not recommended nowadays according to MDN and https://keyjs.dev/. Moreover, the most-rated answer looks a little bit overdone since it also brings other hotkeys which leads to usage of switch. I did not check the third-party libraries, but I always try to use as few third-party libraries as possible.
Here's my solution (since you mentioned jQuery in your question):
$(document).keydown(function(e) {
if (e.ctrlKey && e.key == "s" || e.metaKey && e.key == "s") {
myFunction();
e.preventDefault();
}
});
The e.metaKey is here because of Mac devices.
The myFunction(); line is where you specify your function. The e.preventDefault(); line is here to prevent opening of the "Saveā¦" window. If you want to keep it for some reason, feel free to remove this line.