How do I disable Default Browser Shortcuts in Flutter Web? - javascript

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.

Related

How do I use a custom confirmation method when window.onbeforeunload happens [duplicate]

I need to warn users about unsaved changes before they leave a page (a pretty common problem).
window.onbeforeunload = handler
This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.
So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?
Javascript in my page:
<script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
The closeIt() function:
function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):
$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
which also doesn't work - I cannot seem to bind to the beforeunload event.
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue.
It will then parse the return value as a string (unless it is null).
Since false is parsed as a string, the dialogue box will fire, which will then pass an appropriate true/false.
The result is, there doesn't seem to be a way of assigning false to onbeforeunload to prevent it from the default dialogue.
Additional notes on jQuery:
Setting the event in jQuery may be problematic, as that allows other onbeforeunload events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.
jQuery doesn't have a shortcut for onbeforeunload so you'd have to use the generic bind syntax.
$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)
What worked for me, using jQuery and tested in IE8, Chrome and Firefox, is:
$(window).bind("beforeunload",function(event) {
if(hasChanged) return "You have unsaved changes";
});
It is important not to return anything if no prompt is required as there are differences between IE and other browser behaviours here.
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
1) Use onbeforeunload, not onunload.
2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.
3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.
This can't be done in chrome now to avoid spamming, refer to javascript onbeforeunload not showing custom message for more details.
Angular 9 approach:
constructor() {
window.addEventListener('beforeunload', (event: BeforeUnloadEvent) => {
if (this.generatedBarcodeIndex) {
event.preventDefault(); // for Firefox
event.returnValue = ''; // for Chrome
return '';
}
return false;
});
}
Browsers support and the removal of the custom message:
Chrome removed support for the custom message in ver 51 min
Opera removed support for the custom message in ver 38 min
Firefox removed support for the custom message in ver 44.0 min
Safari removed support for the custom message in ver 9.1 min
Try placing a return; instead of a message.. this is working most browsers for me.
(This only really prevents dialog's presents)
window.onbeforeunload = function(evt) {
//Your Extra Code
return;
}
You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.
function onunload = (){
window.open('logout.php');
}
This code called when user leave the page or close the active window and user logged out by 'logout.php'.
The new window close immediately when logout php consist of code:
window.close();
I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was :
1) It was giving message on all navigations I want it only for close click.
2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.
Following is the solutions code I found, which I wrote on my Master page.
function closeMe(evt) {
if (typeof evt == 'undefined') {
evt = window.event; }
if (evt && evt.clientX >= (window.event.screenX - 150) &&
evt.clientY >= -150 && evt.clientY <= 0) {
return "Do you want to log out of your current session?";
}
}
window.onbeforeunload = closeMe;
<script type="text/javascript">
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
</script>
refer from http://www.codeprojectdownload.com
What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.
$(window).one("beforeunload", BeforeUnload);
Try this
$(window).bind('beforeunload', function (event) {
setTimeout(function () {
var retVal = confirm("Do you want to continue ?");
if (retVal == true) {
alert("User wants to continue!");
return true;
}
else {
window.stop();
return false;
}
});
return;
});

How to stop Webpage from coming out of fullscreen in React?

I'm trying to create an online exam portal, Here in the exam window, I want My users to force into fullscreen, and not get out of it until the exam is complete.
I've used the Fullscreen API here to achieve the Fullscreen.
goFullScreen = () => {
if(document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen(); // W3C spec
}
else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen(); // Firefox
}
else if (document.documentElement.webkitRequestFullscreen) {
document.documentElement.webkitRequestFullscreen(); // Safari
}
else if(document.documentElement.msRequestFullscreen) {
document.documentElement.msRequestFullscreen(); // IE/Edge
}
}
I've basically copied the code from W3schools.
I want to know how to prevent them to get out of fullscreen? I can return false on 'Esc' Keypress, but there are other ways. Also, I don't want them to open developer window (i.e the console).
What methods should I approach ??
P.S. I'm using React, if that matters.
You cannot prevent exit from fullscreen until you make an electron app or you have access to their computer.
Something which you want to do is against the privacy of the user. You can catch the esc key but, you cannot override the browser. You can do one thing, catch the esc key and end the test if the esc key is pressed.
(I used JQuery, you can use vanilla JS also)
if(document.fullscreenEnabled) {
// browser is almost certainly fullscreen
//Execute end test code here
}
Request to accept if this answer helps...

beforeunload() event to be triggered only when window/tab closed but not on any other condition [duplicate]

I need to warn users about unsaved changes before they leave a page (a pretty common problem).
window.onbeforeunload = handler
This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.
So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?
Javascript in my page:
<script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
The closeIt() function:
function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):
$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
which also doesn't work - I cannot seem to bind to the beforeunload event.
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue.
It will then parse the return value as a string (unless it is null).
Since false is parsed as a string, the dialogue box will fire, which will then pass an appropriate true/false.
The result is, there doesn't seem to be a way of assigning false to onbeforeunload to prevent it from the default dialogue.
Additional notes on jQuery:
Setting the event in jQuery may be problematic, as that allows other onbeforeunload events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.
jQuery doesn't have a shortcut for onbeforeunload so you'd have to use the generic bind syntax.
$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)
What worked for me, using jQuery and tested in IE8, Chrome and Firefox, is:
$(window).bind("beforeunload",function(event) {
if(hasChanged) return "You have unsaved changes";
});
It is important not to return anything if no prompt is required as there are differences between IE and other browser behaviours here.
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
1) Use onbeforeunload, not onunload.
2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.
3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.
This can't be done in chrome now to avoid spamming, refer to javascript onbeforeunload not showing custom message for more details.
Angular 9 approach:
constructor() {
window.addEventListener('beforeunload', (event: BeforeUnloadEvent) => {
if (this.generatedBarcodeIndex) {
event.preventDefault(); // for Firefox
event.returnValue = ''; // for Chrome
return '';
}
return false;
});
}
Browsers support and the removal of the custom message:
Chrome removed support for the custom message in ver 51 min
Opera removed support for the custom message in ver 38 min
Firefox removed support for the custom message in ver 44.0 min
Safari removed support for the custom message in ver 9.1 min
Try placing a return; instead of a message.. this is working most browsers for me.
(This only really prevents dialog's presents)
window.onbeforeunload = function(evt) {
//Your Extra Code
return;
}
You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.
function onunload = (){
window.open('logout.php');
}
This code called when user leave the page or close the active window and user logged out by 'logout.php'.
The new window close immediately when logout php consist of code:
window.close();
I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was :
1) It was giving message on all navigations I want it only for close click.
2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.
Following is the solutions code I found, which I wrote on my Master page.
function closeMe(evt) {
if (typeof evt == 'undefined') {
evt = window.event; }
if (evt && evt.clientX >= (window.event.screenX - 150) &&
evt.clientY >= -150 && evt.clientY <= 0) {
return "Do you want to log out of your current session?";
}
}
window.onbeforeunload = closeMe;
<script type="text/javascript">
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
</script>
refer from http://www.codeprojectdownload.com
What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.
$(window).one("beforeunload", BeforeUnload);
Try this
$(window).bind('beforeunload', function (event) {
setTimeout(function () {
var retVal = confirm("Do you want to continue ?");
if (retVal == true) {
alert("User wants to continue!");
return true;
}
else {
window.stop();
return false;
}
});
return;
});

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

Web page: detect and block certain keyboard shortcuts

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)

Categories

Resources