Web page: detect and block certain keyboard shortcuts - javascript

I want to detect and block certain keyboard shortcuts on a web page. For example, say I want to prevent alt+tab for switching apps (just an example, assume any global shortcut).
Here's as far as I can think it out:
attach a keyboard event listener to
document (or window?)
use event.which to check which key
combination was pressed
if it was a blacklisted shortcut,
stop the browser from executing it
But, I don't know how to
A) detect multiple keys (e.g. alt and tab together), or
B) stop them from executing (can I just return false?).
Can anyone tell me how to accomplish the above?

You want to prevent screenshots from being taken? Forget it right now.
No matter what elaborate mechanisms you put into place, they will be trivial to circumvent by un-focusing the browser window (or just the document, e.g. by clicking into the address bar), and pressing the screenshot key then.
There is no chance for you to do this except by installing client software on the computer that controls what the user does, or maybe using some proprietary ActiveX control that makes its contents un-print-screenable. Both approaches are hugely difficult and have tons of downsides.

You cannot block keyboard combinations that belong to the OS. Only keyboard combinations that roam inside the browser and are not OS specific.
If you want to protect your content, don't publish it in public. Or put a decent license on it

// lookup table for keycodes
var key = { s: 83 };
document.onkeydown = function (e) {
// normalize event
e = e || window.event;
// detecting multiple keys, e.g: Ctrl + S
if (e.ctrlKey && !e.altKey && e.keyCode === key.s) {
// prevent default action
if (e.preventDefault) {
e.preventDefault();
}
// IE
e.returnValue = false;
}
};
Detecting Keystrokes Compatibility Table (QuirksMode)

Related

How do I disable Default Browser Shortcuts in Flutter Web?

Problem
If I implement shortcuts for CTRL + + and CTRL + - in my Flutter web app, the browser will still zoom by default. I want to prevent the browser from doing so when I override the shorcuts.
Use case
When I have my custom shortcut behavior (using Shortcuts e.g.), I do not want the browser to still respond to it, but there is no way to prevent the default action in Flutter itself.
Another example is CTRL + D, which creates a bookmark in Firefox. I want to use the shortcut for duplication in my Flutter web app.
How do I prevent the defaults?
You can prevent the default browser actions directly in HTML using JS. Flutter has not implemented a way to trigger this using the framework (and I doubt they will because it is web-specific).
If you wanted to, you could also do this using Dart code instead, using the dart:html library. However, it is most convenient to directly include the following JavaScript code in the index.html of your Flutter web app (in the <body> tag):
<script>
// This prevents default browser actions on key combinations.
// See https://stackoverflow.com/a/67039463/6509751.
window.addEventListener('keydown', function(e) {
if (event.target == document.body) {
// Prevents going back to the previous tab.
if (event.key == 'Backspace') {
event.preventDefault();
}
}
if (event.metaKey || event.ctrlKey) {
switch (event.key) {
case '=': // Prevent zooming in.
case '-': // Prevent zooming out.
case 'd': // Prevent bookmark on Firefox e.g.
case 'g': // Prevent open find on Firefox e.g.
case 'z': // Prevent restoring tab on Safari.
event.preventDefault();
break;
}
}
});
</script>
As you can see, I added a few examples, like CTRL + D et al. inspired by Rive.
Additionally, I added a snippet that prevents going back to the previous tab on pressing backspace. The use case for this is if you want to use backspace as a shortcut for deletion outside of text input.

Catch save (Ctrl/Cmd+S) keyboard shortcut in the browser?

Is there a cross-browser way or cross browser solution to capture the "Save" keyboard shortcut in the browser? For example, in GMail if you use CMD + S it will save the email and not prompt the browser to download the webpage (default behavior). I would rather use a cross browser solution than add event listeners and write it from scratch.
One cross browser solution is to check out keycode.js. Less hassle to worry about looking for browser caveats and such.
I know it's old, but it still works. You can check out its demo too!
Looking at the demo, and the header comments in the .js, something like this?
document.onkeydown = function(e) {
e = e || window.event
var k = KeyCode.translate_event(e);
if( k.ctrl && !k.alt && !k.shift && k.code == 83 ) //83 is the code for s
save(); //Magic function
if(e.preventDefault) {
e.preventDefault();
}
return false;
};

Disable ALT+F4, yes I know it isn't recommended

I need a JavaScript script that would disable users from closing using ALT+F4. I have looked everywhere but it just everyone just says it isn't advised.
May not even be possible, if it isn't I will just have to detect when the user does quit out this way and log it in a database.
Here is my current script, it detects if the user presses either ALT or F4, but I can't get it to cancel that key press. Is there a way to make the browser think the user pressed another key as well so the combo would be ALT + G + F4 for example, which would disrupt the ALT+F4 combo?
//Run on keydown, disable user from quiting via ALT+F4
document.onkeydown = function(evt) {
evt = evt || window.event;
//Get key unicode
var unicode = evt.keyCode ? evt.keyCode : evt.charCode;
//Check it it's ALT or F4 (115)
if (unicode == 115 || evt.altKey == 1)
{
window.event.cancelBubble = true;
window.event.returnValue = false;
}
};
That key event is (on most OSs I guess) processed by the OS before it'S even sent to the browser, so cancelling the event inside the browser won't help a thing - even if it was Javascript that is executed inside the browser's UI, not only the current document.
Therefore - what you're trying to do cannot be done.
One can prevent the resulting window closure with:
window.onbeforeunload = funcRef
I think readers landing here might want to be reminded of this (as I did).
For related details, see
Jquery prevent window closing
try to use the code below:
window.webContents.on("before-input-event",(event,input)=>{
if(input.code=='F4'&&input.alt)event.preventDefault();});

How to Disable Function keys using Javascript?

I'm having a page where i need to disable the Function keys mainly F12(Developertools).
I'm showing some sensitive data in the page so at any case i cannot make the users see the html and take the hidden fields.
I checked some javascript which is working for almost all the keys except the Function keys like f1, f12 etc.
Is there anyway that i can disable these buttons in the browser?
document.onkeyup = KeyCheck;
function KeyCheck() {
var KeyID = event.keyCode;
alert(KeyID);
switch (KeyID) {
case 123: //F12 KEY CODE
alert('hello');
return false;
break;
}
}
This is the code which im using for overriding the key. When I searched, the keycode of F12 key is 123 and im using the same code for overriding it. But unfortunately its not even hitting the "CASE" and the message box is not appearing when pressing F12, F1 etc buttons.
Please Help me in this.
There is no reliable way to prevent users from tampering with your javascript data, when you've sent it. Always use server-side checks to verify the returned data.
People can still use the browser's menu to enable the dev console. Or through right-click --> "Inspect Element", or by using hotkeys to open different sections of the console, then tabbing to another page in the console, or by using one of the hotkeys I've failed to mention.
Or, they can simply disable javascript. (Or edit the javascript to disable the block)
Now, you can be a little more thorough in disabling whatever button's functionality, by adding a:
event.preventDefault() in your event listener, but still, it's unreliable.
document.onkeydown = KeyCheck;
It worked.
No, you can't diasble view source/developer tools or any other application level functionality of the browser via JavaScript on the page.
There are plenty ways to see source of the web page. You are up to very hard task to restrict all external parties to access/store/view your HTML. Here is partial list of other things you'll have to disable:
proxies, including HTTP debuggers/proxies like Fiddler or ones that are built in to browsers.
direct GET requests from console tools like curl.
all sorts of web crawlers, including search engines like Google.
Use HTTPS and do not send sensetive information unless strictly required is the much easier way of protecting it than trying to limit what users can do with their machines.
Try this out:
<script language="JavaScript">
document.onkeypress = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
//alert('No F-12');
return false;
}
}
document.onmousedown = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
//alert('No F-keys');
return false;
}
}
document.onkeydown = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
//alert('No F-keys');
return false;
}
}
</script>
This Code works Perfectly for me to Disable Right Click and Disable F12
<script language=JavaScript>
var message="You Have No Permission";
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
When user press F12 key, browsers developer tool bar will open in the below portion of the browser.
By using the developer tool bar user can see the design, javascript code and corresponding css applied to the controls in the page. To prevent the user to do that we will hide the developer tool bar.
Here is the code

Detect Close window event in Firefox

I know it is a very asked question, but believe me I don't find the answer through the Web.
My purpose is to trigger the message box only if the user clicks on the close (X) button.
The user continues to get the message box if he clicks on the back/forward button and also if he uses F5, CTRL+R, ...
I do not want to associate any other action than the window close button click as behind, there will be a session kill with Ajax. So it is not acceptable to kill the session if the user types F5 button.
Here is my code. For info, I know that there is a way in IE to check the event object clientY, but this does not work in Firefox.
$("a").click(function () {
window.onbeforeunload = null;
});
window.onbeforeunload = function (e) {
var closewindowmessage="If you leave this page, your session will be definitely closed.";
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = closewindowmessage;
}
// For Safari
return closewindowmessage;
};
There's no definitive way of detecting why/how a page is being unloaded. You could rebuild your site to use the now ever so popular "anchor navigation" method which stores data in the HTML anchor, such as http://www.example.com/page#something=something. This would at least typically solve the problem for the back/forward buttons but not when the user is reloading the page.
Other than that, you could employ various ad hoc ways of tracking the mouse and keyboard action before the user tries to unload the page. You could for example track when the user drags the mouse diagonally up to the right – that probably means he's just about to close the the window/tab, so keep the message. Diagonally up to the left – that probably means he's just about to click the back forward buttons or maybe enter something to the address field. If you're really serious, conduct a study of how people move the cursor and correlate that with whether they're about to close the page or do something "allowed". Then again, on a Mac the close button is in the upper left corner of the window. And so on and so forth. It'll still just be best guesses.
You could also track upward mouse movements and show a big red message in the browser viewport (not a popup/alert) to warn the user before he even considers leaving the page.
Tracking keyboard events is a little bit more deterministic, but still requires some cross browser and platform research. I leave you with this code, which I'm hoping may work as a boilerplate. It logs the key presses and suppresses the message if F5 or Apple+R (Mac) was pressed. Otherwise it will show a message containing a list of all logged key presses.
The analysis needs testing and extension; it's only been tested on Firefox Mac. One bug that I can immediately point out is that if you press Apple+R,R you'll still get prompted because the second page instance never recorded any keydown event for the Apple key – only for the R key. It will also fail if the user presses something inbetween, like Apple+L,R. You might be fine with just checking if the last key pressed was R.
<script>
// Create an empty array.
window.keys = [];
// Log every key press
window.onkeydown = function (e) {
var evt = window.event || e;
var keyCode = e.keyCode || e.which;
window.keys.push(keyCode)
}
function analyzeKeyPresses(){
keys.reverse(); // Reverse the array so it's easier to handle.
var doBlock = true;
// Here we only apply certain checks if there are enough keys in the array. Don't want a JS error...
switch(window.keys.length){
case 0:
doBlock = true; // Redundant. If there are no key presses logged, assume we should prompt the user.
break;
default: // Two or more key presses logged.
if(keys[0] == 82 && keys[1] == 224) doBlock = false; // User pressed apple+r on a Mac - don't prompt!
if(keys[0] == 82 && keys[1] == 17) doBlock = false; // User pressed ctrl+r on Windovs (untested) - don't prompt!
// Note: No break! Intentional fall-through! We still want to check for F5!
case 1: // One or more key presses logged.
if(keys[0] == 116) doBlock = false; // User pressed F5 - don't prompt!
}
keys.reverse(); // Un-reverse the array in case we need to use it again. (Easier to read...)
return doBlock;
}
window.onbeforeunload = function (e) {
var closewindowmessage=window.keys.join(" ");
var blockUnload = analyzeKeyPresses();
if(blockUnload){
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = closewindowmessage;
}
// For Safari
return closewindowmessage;
}
};
</script>
1 2

Categories

Resources