How to call javascript on F5 key press - javascript

I need to call a function when F5 is pressed. While researching this, I found this function, which works -- it shows a message in the console and pops up an alert window:
<script>
document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;
var wasPressed = false;
function fkey(e){
e = e || window.event;
if( wasPressed ) return;
if (e.keyCode == 116) {
console.log("f5 pressed");
alert("f5 pressed");
wasPressed = true; }
}
</script>
But I don't want the popup, I just want to call a function. When I comment out the line alert("f5 pressed"); the console.log doesn't show in the console any more. That means that without the alert message, I can't call another function.
I need to intercept F5 because my site is populated by Ajax and I want to repopulate the page as constructed by Ajax when F5 is pressed. As it is now it
does not reconstruct the page on F5, it just reloads the original page structure.
My question is: how can I call a function on the press of F5 without showing an alert box?
This question is not a duplicate of the duplicate proposed above because I am not looking to disable the F5 button, just intercept it. The two answers below are what I'm looking for.

F5 reloads the page in many browsers.
With the alert there, the alert pops up before the browser reloads, so you can see the log in the console until you close the popup.
Without the alert, the log gets written to the console, then immediately the browser reloads the page, clearing the log.
You could try blocked the default behavior:
function fkey(e) {
if (e.keyCode == 116) {
e.preventDefault();
// do stuff...
}
}
However, I would recommend against blocking a standard key like F5, as this may provide a poor user experience. Of course, this all depends on who is using it and what you are making. Use your judgement.

If you want to disable the refresh action from your F5 key, then, you need to use this:
const disableRefreshFunction = (e) => {
if (e.keyCode === 116) {
e.preventDefault();
}
};

NB you only need to listen on the keydown event which fires before the other key events. keypress and keyup will fire too late for some keys and the browser or host OS will have already consumed the event before it gets to your handler.
This should be everything you need to get started.
Click Run code snippet below to see how to capture every keystroke and prevent its default behavior -
const preventDefault = f => event =>
( event.preventDefault()
, f(event)
)
const logKeypress = event =>
console.log(event.which)
window.addEventListener('keydown', preventDefault(logKeypress))
h1 { font-family: sans-serif; }
<h1>click here, then press any keys...</h1>
This technique shows you how to separate event functions and them combine them in reusable ways. It is taken from my answer to this question.

Related

Trigger event when user clicks the browsers back button

Is it possible with jquery to trigger a function when the user clicks the browsers back button.
I have a lightbox/widget that when open fills the window when it is open. There is a close button etc but this would be good if this closed if a user hit the back button by mistake.
I have this so far but the function doesnt seem to run at all
$(window).on("navigate", function (event, data) {
event.preventDefault();
console.log('BACK PRESSED');
var direction = data.state.direction;
if (direction === 'back') {
if(widgets.full_active){
$('.close', widgets.active_widget).click();
event.preventDefault();
console.log('CLOSE THIS');
}
}
if (direction === 'forward') {
// do something else
}
});
By not running this line at the start of the function event.preventDefault(); should mean the page never changes
Usually, I do this using the native JavaScript API from the browser, like described here: Manipulating the Broser History.
With jQuery, I see people usually using this plugin: History.js, although I have no idea what is it's status.
The event you're looking for is onpopstate.
A popstate event is dispatched to the window every time the active
history entry changes between two history entries for the same
document.

Prevent double submission with prevent window event issue

I'm using the following function to prevent double submissions:
$("#form").submit(function () {
var form = $(this);
form.find("input[type=submit]").attr("disabled", "disabled")
form.find("input[type=submit]").attr("value", "Processing");
});
It works fine, but then I have the following code which triggers an alert to avoid accidentally leaving the page:
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = '¿DO YOU REALLY WANT TO LEAVE THIS PAGE?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
The problem is if the user clicks submit and the realizes he didnt want to leave the page and clicks on stay on this page instead, the submit button is still disabled.
How could I re-enable it upon clicking stay on this page?
Thanks!
The button problem
You want to disable and enable the submit button so you know you going to touch the same kind of function and object twice, it is better to make advantage out of this in a function
function disableSubmit(form, enabled){
var submit = form.find("input[type=submit]"),
dataVar = enabled !== true ? "processing-message" : "send-message",
message = submit.data(dataVar);
submit.prop('disabled', (enabled !== true) );
submit.val(message);
}
I could make it even more generic for using it on each form. But the message in the button will display whatever you put in the data-attribute.
Cancel Submit
There is a problem with cancellation of an onbeforeunload event; there is no callback for it. The solution I came with is using a timeout. Since you don't know if the person canceled or not, I think 2 seconds is enough for the page to submit.
You have to have 2 seconds patient to get the submit button enabled again. But you can adjust it all you want of course
if (e.stopPropagation) {
setTimeout(function () {
disableSubmit(formObject, true);
}, 2000);
e.stopPropagation();
e.preventDefault();
}
The JSFiddle example

Logout webpage when click on refresh button

I am developing a website. Where I need to logout the page when one try to refresh the page.
I got the code for logout when one click on f5 for refresh and also I got the code for disable right click on the page. but I dont know how to prevent the refresh button of browser or logout when I press refresh button. I searched many sites. But didn't get an answer.
The code I gor for F5 key is
function fkey(e){
e = e || window.event;
if( wasPressed ) return;
if (e.keyCode == 116) {
alert("f5 pressed");
wasPressed = true;
}else {
alert("Window closed");
}
}
Can anyone please help me for the issue with refresh button?
I think it will work
$("*").keypress(function(e)
{
if (e.keyCode == 116) {
e.preventDefault();
}
});
Try this:
window.onbeforeunload = function(e){
//call logout process here
}
onbeforeunload is an event that fires when a window is about to unload its resources. The document is still visible and the event is still cancelable, in other words, whenever you refresh or close a page it fires an event 'onbeforeunload'. When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog.
Reference: https://developer.mozilla.org/en-US/docs/WindowEventHandlers.onbeforeunload
window.onbeforeunload = function(e){
//call logout process here
}
Any custom declaration on OnBeforeUnload will not be executed as the support is removed from the code. So, the above solution will not work for Chrome.
Instead, use HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

JavaScript confirm to fire when user clicks to close their browser (but not when they click the refresh button)

There are several similar questions on here already but none of them provide a solution to what I'm looking for here.
When a user clicks the close button on their browser I need to pop up an alert to confirm that they really want to close their browser. This is easy enough to write:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to close your browser?';
});
The problem with this is that it also fires when you do things like refresh your browser, click on buttons and links, etc.
Most of these can be prevented by detecting the key presses and checking the keyCodes like this:
if (e.keyCode == 114 || e.keyCode == 116 || e.keyCode == 0 || e.keyCode == 17 ||(e.ctrlKey && e.keyCode == 114)){
confirmBrowserClose = false;
}
$("a").bind("click", function() {
confirmBrowserClose = false;
});
$("form").bind("submit", function() {
confirmBrowserClose = false;
});
$("input[type=submit]").bind("click", function() {
confirmBrowserClose = false;
});
These things prevent most of them but one thing it doesn't work for is refresh. I can prevent it from firing when the user refreshes using the keyboard (like F5) but I need to know how to prevent my confirmation alert from firing when the user clicks the refresh button or enter in the URL window.
Most of what I've found scattered around the internet says that it either can't be done or they talk about things like using the keyCodes and F5 refresh. I know this can be done because there are many sites that have this functionality working. A couple sites that are using it are Facebook and JSFiddle.net. In Facebook, if you start typing a status update and then try to close your browser, it will popup a confirmation. In JSFiddle, if you make changes to your fiddle and then try to close your browser it will pop up a warning alert that your changes will be lost if you close.
Does anyone know how to do this?
This is not possible. If you observe properly, even Facebook.com and JSFiddle.net do not have this feature.
beforeunload is the only event that gets triggered on leaving the page.(either by page refresh [f5, ctrl+r], tab close, load another link[this also accounts to leaving the current page, hence triggering beforeunload])

Capturing result of window.onbeforeunload confirmation dialog

Is there a way to capture to result of the window.onbeforeunload confirmation dialog like the one below from Stack Overflow (this happens when leaving the 'Ask Question' page without posting the question)?
This is how it appears in Chrome, I believe it's slightly different in other browsers, but you always have some form of yes/no buttons.
Presumably if they're still on the offending page after the event has been triggered they chose to stay and you could probably figure this out by watching the sequence of js. However I would like to know how to determine if they clicked "Leave this page"?
I've implemented this like below:
// concept taken from SO implementation
function setConfirmUnload(showMessage, message) {
window.onbeforeunload = showMessage ? (message ? message : "this is a default message") : null;
}
// pseudo code
listen to changes on inputs
if any inputs fire a change event
call setConfirmUnload(true, 'My warning message')
note I'm using jQuery within my site.
I'm essentially trying to implement a Gmail like drafting implementation, wherein if a user leaves a page with a form they've made changes to without saving they're warmed with a similar dialog. If they choose to discard they're changes and leave the page, I need to clean up some temporary records from the database (I'm thinking an AJAX call, or simply submitting the form with a delete flag) then sending them on their way.
My question also relates to:
jQuery AJAX call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?
You can have the exit confirmation using window.onbeforeunload but there isn't a way to find out which button the user clicked on.
To quote an earlier response from jvenema from this thread:
The primary purpose for the
beforeunload is for things like
allowing the users the option to save
changes before their changes are lost.
Besides, if your users are leaving,
it's already too late [...]
How about this:
$( window ).bind( 'beforeunload' , function( event ) {
setTimeout( function() {
alert( 'Hi againe!' );
} );
return '';
} ).bind( 'unload', function( event ) {
alert( 'Goodby!' );
} );
Late to the party, but I found the following code (in TypeScript) to be a decent way to detect if the person clicked on 'Ok' on that confirmation dialogue window.
public listenToUnloadEvents(): void {
window.addEventListener('beforeunload', (e) => {
const confirmationMessage = '\o/';
(e || window.event).returnValue = confirmationMessage; // Gecko + IE
return confirmationMessage; // Webkit, Safari, Chrome etc.
});
window.addEventListener('unload', () => {
this.sendNotification(Action.LEFT)
});
}
I'm not sure how much time you have to run code in the unload event, but in this instance, I am sending a notification through Socket.io, so it's very quick at completing.
As for detecting the cancel on that notification, as someone else mentioned, creating a global variable like let didEnterBeforeUnload = false could be set to true when the beforeunload event fires. After this, by creating the third event, like so (again, in TypeScript), you can infer the user pressing cancel
window.addEventListener('focus', (e) => {
if (didEnterBeforeUnload) {
console.log('pressed cancel')
}
didEnterBeforeUnload = false
});
As a side-note though, these events won't (iirc) fire unless you have interacted with the page. So make sure to click or tap into the page before trying to navigate away during your testing.
I hope this helps anyone else out there!

Categories

Resources