Prevent user pressing f5 button in pop up window - javascript

I want to prevent users from pressing the F5 button because of running exam test in my project.
If I use a normal browser window, my code works fine, but now I want to use it in a popup windows - in the popup windows my code is not working. My code is:
document.onkeydown=function(e) {
var event = window.event || e;
if (event.keyCode == 116) {
event.keyCode = 0;
alert("This action is not allowed");
return false;
}
}

try this
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.focus();
myWindow.onkeydown=function(e) {
var event = window.event || e;
if (event.keyCode == 116) {
event.preventDefault();
alert("This action is not allowed");
}
}

document.onkeydown = function(e){
var event = (window.event || e);
if(event.keyCode==116){
event.preventDefault();
alert("This action is not allowed");
}
}
You don't need this part of code: event.keyCode = 0; - changing keyCode after key is pressed won't affect anything.

If what you are looking for is to supress refreshing of your web page then you should ask why you need this. If it is so as not to resend the data already sent then you should use a different php file for doing the proccessing of your data and a different to display them to your user. This way you can check whether anything is awry and redirect him accordingly.
If you for some specific reason trully need to prevent refreshing through F5 then what Cobra_Fast suggested e.preventDefault(); should do the trick.

Related

How to call javascript on F5 key press

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.

jQuery: preventDefault() not working on anchor link tag (tried many methods!)

I'm trying to prevent anchor link from sending to another page but it's not actually working, I don't even know whyyy. I used preventDefault before and it works every time but this time I don't know what's going on.
Yes i've seen this question on stackoverflow and tried all methods but it's still not working
HTML Code:
<h2><a id="donta" href="/services.html">Eco Ideas</a></h2>
jQuery Code:
$('#donta').on('click', function(event) {
event.preventDefault();
event.stopPropagation();
alert(event.target.tagName); //yes it alerts me 'A'
if(event.isDefaultPrevented()){
alert('Prevented!'); //yes it shows this alert but still send me to that link
event.stopImmediatePropagation();
event.returnValue = false;
}else{
// NOPE, it doesn't show this "ELSE" part...means the below alert doesn't show up...means according to browser or jQuery it is now PREVENTED
alert('Not prevented but trying to prevent now');
event.returnValue = false;
}
return false;
});
You can see I tried all methods, but still it send me to that damn link!
Thanks in advance, because I know you guys will find a way :)
There are lot of event-listeners on the link. And 2 of them are listening click event. It seems like while one prevent link, other one don't.
I think trouble may be in this function, because it triggers:
function end(e) {
clearTimeout(resetTimer);
resetTimer = setTimeout(function() {
w.tapHandling = false;
cancel = false;
}, 1000);
// make sure no modifiers are present. thx http://www.jacklmoore.com/notes/click-events/
if ((e.which && e.which > 1) || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey) {
return;
}
e.preventDefault();
// this part prevents a double callback from touch and mouse on the same tap
// if a scroll happened between touchstart and touchend
if (cancel || w.tapHandling && w.tapHandling !== e.type) {
cancel = false;
return;
}
w.tapHandling = e.type;
trigger(e);
}
I usually not set href attribute with value and just set href="javascript:void(0)" when I won't that link was redirected and will set action in that link.
Maybe will work for you too.

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);

prevent OnBeforeUnload() event from happening in refresh/F5

I'm using onbeforeunload event to perform operations during the closing page.
I do not want the event to happen in the case of Refresh / F5.
Is there a way or other event to do this?
Unfortunately onbeforeunload event listens the page state in the browser. Going to another page as well as refreshing will change the page state, meaning onbeforeunload will be triggered anyway.
So I think it is not possible to catch only refresh.
But, if you'll listen and prevent Keypress via JavaScript, then it can be achieved.
Refresh can be done via F5 and CtrlR keys, so your goal will be to prevent these actions.
using jQuery .keydown() you can detect these keycodes:
For CtrlR
$(document).keydown(function (e) {
if (e.keyCode == 65 && e.ctrlKey) {
e.preventDefault();
}
});
For F5
$(document).keydown(function (e) {
if (e.which || e.keyCode) == 116) {
e.preventDefault();
}
});
I would use the keydown listener to check for F5 and set a flag var.
http://api.jquery.com/keydown/
Detecting refresh with browser button is not that easy/possible.
I wanted to add a message alert onbeforeunload, so my solution was this one:
$(document).ready(function(){
window.onbeforeunload = PopIt;
$("a").click(function(){ window.onbeforeunload = UnPopIt; });
$(document).keydown(function(e){
if ((e.keyCode == 82 && e.ctrlKey) || (e.keyCode == 116)) {
window.onbeforeunload = UnPopIt;
}
});
});
function PopIt() { return "My message before leaving"; }
function UnPopIt() { /* nothing to return */ }
Third line ($("a").click...) is to avoid showing the alert when navigating between sections of the web.

How can I prevent default behavior on boxee back/menu button?

I have a boxee html application. I can handle all navigation keys on the remote control, except the big back/menu button. This one closes the app - I would like to use it to bring up my app menu instead.
Is there a way to prevent default behavior on this key?
you can trigger your back/menu button since the last api update from boxee. in your js-file where you set your keyboard mode you can catch your back button with:
boxee.onKeyboardKeyBack = function(){
browser.execute( "callYourShowMenuFunction()" );
}
browser.execute() delegates that to your htmlbrowser. now your backbutton should trigger your function in javascript!
remember back button usually should close the app, so don t forget to give your user an logout option ;) otherwise your app won t be published!
Backspace handling
document.body.onkeypress = function (e) {
if (!e)
var e = window.event;
/*backspace*/
if(e.keyCode == 4){
e.preventDefault();
/*Do your thing*/
}
}
On right click
document.onmousedown = function(e) {
if (!e)
var e = window.event;
/*right mouse*/
if (e.which == 3){
e.preventDefault();
/*Do your thing*/
}
}
Good article on similar event management http://www.quirksmode.org/js/events_properties.html
Edit: I'd recommend localising the onmousedown to the objects which you want to trigger the event on.

Categories

Resources