Disable F5 in Silverlight - javascript

Some of my users accidentally hit F5 when they are typing, and cause them to lose all the stuff they have typed. I do not need to prevent hitting Refresh button.
I tried to use the following javascript, but it only works when the user does not focus on the Silverlight app (i.e. it works when the user click on somewhere outside of the SL app, but the onkeydown event is not triggered when the user focus on the SL).
document.onkeydown=function(e) {
var event = window.event || e;
if (event.keyCode == 116) {
event.keyCode = 0;
alert("test");
return false;
}
}

Probably the best way of handling this situation would be to use the onbeforeunload event and ask the user for confirmation. This way you can root out the accidental refreshes or closed tabs from the legitimate ones without handling all possible shortcuts.
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave without saving your changes?';
};
You could even display the confirmation dialog only if there are some unsaved changes.

I'd say, something like this?
document.onkeydown = function()
{
switch (event.keyCode)
{
case 116 : //F5 button
event.returnValue = false;
event.keyCode = 0;
return false;
case 82 : //R button
if (event.ctrlKey)
{
event.returnValue = false;
event.keyCode = 0;
return false;
}
}
}
note: ctrl + r is a shortcut to refresh as well

Related

Cancel Backspace back in all dynamic iframe pages recursively

My asp.net application contains iframe element named "bodyFrm".
bodyFrm content changes dynamically, the content pages contains iframe and more html elements.
sometime the child page contains iframe with more child page.
I want to cancel the action go to previous page when user pressed the backspace.
I try to call CancelBackspace functoin in window.onkeydown event of main page,
but it's called sometimes,not for every key press,
how can I call the function for every key press in application ?
I can't use jquery.
in main page, works part time:
<script type="text/javascript">
document.onkeydown = CancelBackspace();
function CancelBackspace(e){
if(!e)
e = event;
if(e.keyCode == 8)
return false;
}
</script>
you can prevent the back space key operation with this
document.onkeydown=function(event){
switch (event.keyCode) {
case 8 :
{
if (!event)
event = window.event;
// FOR IE9 & Other Browsers
if (event. preventDefault) {
event. preventDefault();
}
//FOR IE8 and Lower
else {
event.returnValue = false;
event.keyCode = 0;
}
}
break;
}
};

How to keep the OS "Save As" dialog from poppng up when Ctrl S is entered

I have some JavaScript that gets triggered by Ctrl + S and saves a local structure, call "group" below. But despite the last three lines of the code, the OS (Windows 7) "Save As" dialog pops up. Is there any way to keep the OS from popping up its Save As dialog?
Thanks
$(document).on('keydown',function(e) {
if ( e.ctrlKey && e.keyCode == 83 ) { // CTRL+S - save group
var raw_groupName = prompt("Group Name: ", g.last_groupName);
var groupName = raw_groupName.replace(/ /g,"_");
saveGroup(groupName);
e.stopPropagation();
e.preventDefault();
return (false);
};
}
I listened for the keydown event and attached the listener to the window object.
window.addEventListener('keydown', function (evt) {
if (evt.ctrlKey && evt.keyCode === 83) {
evt.preventDefault();
}
}, false);
Above code works for me: http://jsfiddle.net/s66JK/
You are probably listening to the onkeypress event which will always give you an e.keyCode equal to 0. Have you tried putting a breakpoint inside your if ? It's most likely always false. onkeypress uses e.charCode.
I tried your code and it works with the onkeydown event.

How to trigger F5 key and reload page manually with full cache use

We have a web page which is often reloaded by clicking F5 or Ctrl-R just for sake of looking if some new data arrived.
All images in this page have a cache forever header, so should never be reloaded by the browser.
But when a user presses F5 most browsers check every cache entry with a request and a if-modfied-since header. Our HTML page is never cached anyway but the images should be cached for a long time and there is no need to ask if the image was modified. It is a useless request and we want to get rid of it.
We have a reload icon on our page but users will still use the keyboard to reload (I would rather too).
So I tried to trigger F5 and Ctrl-R keys and do the reload manually like this (btw we are using jquery):
<img src="someimg.png" />
<a id="reload" href="mypage.html">Reload</a>
<script type="text/javascript">
function loading() {
window.location.href = $('#reload').attr("href");
return false;
}
function isF5(e) {
return e.which == 116;
}
function isCtrlR(e) {
return e.ctrlKey && e.which == 82;
}
function triggerReloadKeys(e) {
if (isF5(e) || isCtrlR(e)) {
$('#reload').click();
}
}
$(document).bind("keydown", triggerReloadKeys);
$('#reload').click(loading);
someimg.png is always delivered with a long lasting cache directive.
My first answer would be to tell me not taking over the users browser and let him refresh if he wants to. You are right, but we something up to 5000 pages/sec in peak time. And even more images because everybody is reloading the page all the time. We just want to scale down the amount of request, regardless of how fast they are. (and I know that I can't trigger the browser refresh button in the menu bar, but I don't care about it right now).
We were pretty successful with reducing the amount of requests in our App as we just don't have any reload button or F5 but everybody is forced to use our own HTML reload link.
What is possible is to disable the F5 key all together like this:
function triggerReloadKeys(e) {
if (isF5(e) || isCtrlR(e)) {
return false;
}
}
I don't know if it's even possible to trigger F5 and force a reload while still using the cache and mimic the behaviour of clicking another link on the page.
Any ideas?
I assume you did not get your answer yet.
This is what I am using on my website:
var ctrlDown = false;
var ctrlKey = 17, f5Key = 116, rKey = 82;
$(document).keydown(function( e ) {
if( e.keyCode == f5Key )
{
//F5 pressed. Copy your code here or try
//window.location = window.location;
//It will avoid if-modified-since requests.
e.preventDefault( );
}
if( e.keyCode == ctrlKey )
ctrlDown = true;
if( ctrlDown && ( e.keyCode == rKey ) )
{
//Ctrl + R pressed. Do whatever you want
//or copy the same code here that you did above
e.preventDefault( );
}
}).keyup(function(e) {
if (e.keyCode == ctrlKey)
ctrlDown = false;
});
Hope it works for you.
You are trying to solve this problem in the wrong place (i.e. on the client).
If your images truly never change, then add a far-future Expires http header on the server side to those images. This way the browser cache will not attempt to see if the image has been updated because the caching directive assures that it will not.
<body onload="JavaScript:document.body.focus();" onkeydown="return showKeyCode(event)">
</body>
<script src="<?php echo $this->webroot; ?>assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script>
var version = navigator.appVersion;
function showKeyCode(e) {
var keycode = (window.event) ? event.keyCode : e.keyCode;
if ((version.indexOf('MSIE') != -1)) {
if (keycode == 116) {
event.keyCode = 0;
event.returnValue = false;
return false;
}
if (keycode != 154) {
event.keyCode = 0;
event.returnValue = false;
return false;
}
if (keycode != 123) {
event.keyCode = 0;
event.returnValue = false;
return false;
}
}
else {
if ((keycode == 116)||(keycode != 123)||(keycode != 154)) {
return false;
}
}
}
</script>

Simulate multiple keypresses in javascript

I would like to simulate the user pressing tab then enter when they press enter. I know this sounds bad, but I have an asp.net web application that will only allow me to have one form with runat="server" on it so when the user hits return the main form gets submitted. I have another textbox on the page though (that ideally should have it's own form but can't because it is asp), and when enter is hit from there obviously the main form is submitted. The simplest way I could think is to simulate tab then enter using javascript, but I have been unsuccessful in that. I am welcome to any other solutions to this problem. So far I have simulated pressing tab, but I don't know how to simulate more than one keypress though.
Here is the code I have so far, I imagine return 9; needs to be replaced with something else. JQuery will also do.
function suppressEnter (e) {
var keyPressed;
if (window.event) { keyPressed = window.event.keyCode } // IE
else if (e) { keyPressed = e.which }; // Netscape
if (keyPressed == 13) {
return 9;
}
else {
return true;
}
}
EDIT: return 9 + 13; works in chrome, but not IE
Something like this would work:
function keyPress(e) {
if (e.which == 13) {
$(document).trigger(jQuery.Event('keydown', {which: 9}));
// do something
alert('Enter')
}
if (e.which == 9) {
// do something
alert('Tab');
}
};
$(document).bind("keydown", keyPress);
I've coded it up in a fiddle - http://jsfiddle.net/FAe6U/
Also With regards to #nnnnnn comment:
It seems to me you should just code that directly rather than trying
to simulate keystrokes.
Try this:
var tabPress;
function keyPress(e) {
if (e.which == 13) {
if (tabPress == 1){
e.preventDefault();
alert('tab and enter');
}
else{e.preventDefault(); alert('enter')}
}
else if (e.which == 9) {
e.preventDefault();
tabPress = 1;
};
};
function keyRelease(){tabPress = 0;}
$(document).bind("keydown", keyPress);
$(document).bind("keyup", keyRelease);
I've coded it up in a fiddle - http://jsfiddle.net/f4Ybn/

Understanding event bubbling in Javascript

I've been trying to understand even bubbling, and not quite sure I completely follow it. I started reading about it so that I could warn users when they were leaving a page on my website if they had started to enter data into a form (in a similar way to Stack Overflow does!).
The following code seems to work cross-browser:
var entereddata = false;
$(document).ready(function()
{
$('#contactform').bind('keypress',function(e) {
if((e.which > 96 && e.which < 123) || (e.which > 47 && e.which < 58)) {
entereddata = true;
//alert(e.which);
}
});
});
function confirmLeave(e, d)
{
if(!e) e = window.event;//window.event;
if(!d) d = entereddata;
var confirmationMessage = 'It appears you have started to enter information into the contact form, but have not yet submitted it';
if(!d)
{
e.cancelBubble = true;
} else
{
return confirmationMessage;
}
}
window.onbeforeunload=confirmLeave;
However, this also gets called when I click the submit button for the form, which I don't want. I've tried various additions to the code, such as adding:
if($('#submit').click()){
submitted=true;
} else {
submitted=false;
}
and then changing if(!d) to if(!d && submitted==false) to the main code; however, this (and every other combination of trying to get the page to fire only if the submit button isn't clicked) doesn't work, with the warning either still showing when I click the submit button, or no warning being shown when anything is clicked!
This might boil down to the fact I don't understand the event bubbling process - I don't know why I need the e.cancelBubble = true; in the place I have it.
So, my two main problems are:
how do I check if the submit button is clicked, and only show the warning if it isn't clicked
and to understand eventBubbling; for example: if enteredData is true, then I'm not affecting the bubbling process. Should I be? Should I have e.cancelBubble=false if enteredData is false and e.cancelBubble=true if enteredData is true? What effect does setting the value of e.cancelBubble actually have when closing a page?
Am I also correct in thinking I don't need the event e.stopPropagation
at all, because Firefox supports event bubbling?
What about having such code?
$('#submit').click(function() {
entereddata = false;
});
This should be called before the actual form submission i.e. before confirmLeave is running, so lowering the flag should do the trick.
Try removing the onbeforeunload "listener":
$('#submit').click(function() {
window.onbeforeunload=null;
});
I don't think you need to worry about bubbling in this example...
return null if you want the browser to move on without asking the user, or return a string if you want the browser to show an alert asking the user if he wants to move on or not...
function confirmLeave(e) {
e = e || window.event;//window.event;
var confirmationMessage = 'It appears you have started to enter information into the contact form, but have not yet submitted it';
if(entereddata) {
return confirmationMessage;
} else {
return null;
}
}
Bubbling and propagation only applies to event's that should notify it's children or it's parents, and as far as i know window.onbeforeunload is a global event that will not be propagated.
Unrelated to bubbling, but you could bypass detecting whether keys were pressed and check the form data instead:
function hasNonemptyTextInputs() {
var textInputs = $('#contactform :input').filter(':text, textarea');
// Check for any field with a nonempty value
// .is() returns true iff the function returns true on any element
return textInputs.is(function() {
return $(this).val().length > 0;
});
}

Categories