Blocking F5 refresh not working in Chrome - javascript

Here is the code that worked earlier, but now doesn't work anymore. Does anyone know why?
document.onkeydown = function()
{
if(event.keyCode==116) {
event.keyCode=0;
event.returnValue = false;
}
}
// To avoid refresh, using context menu of the browser
document.oncontextmenu = function() {event.returnValue = false;}

You refer to event in your functions, but you never actually pass it:
document.onkeydown = function(){ /* ... */ }
document.oncontextmenu = function() {event.returnValue = false; }
// should be
document.onkeydown = function(event){ /* ... */ }
document.oncontextmenu = function(event) {event.returnValue = false; }
In the first version of the oncontextmenu you set 'returnvalue' of object 'event' to false, but it doesnt exist because you never actually pass it on to the function.

Recieve the event in your function
document.onkeydown = function(event)
{
if(event.keyCode==116) {
event.keyCode=0;
event.returnValue = false;
}
}
Or Try preventing the action by that key
document.onkeydown = function(event)
{
if(event.keyCode==116) {
event.preventDefault();
}
}

try this
<script>
window.onload = function () {
document.onkeydown = function (e) {
return (e.which || e.keyCode) != 116;
};
}
</script>

Related

Javascript disabling a keyevent and enabling it back

I'm quite curious for keyup and keydown function.
I wanted to disable the keys for like 2 seconds then enabling back them.
I've set a function setTimeout to ensure to enable it back under this function continueExecution.
The issue is , i'm trying to figure out how to disable it.
I've tried e.preventDefault();
Tried sending false back still no luck.
Is there something I'm missing?
Event handler:
var keysDown = {},
ignore = false,tId;
addEventListener("keydown", function(e) {
if (ignore) return false;
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function(e) {
if (ignore) return false;
delete keysDown[e.keyCode];
}, false);
Function:
function doStuff() {
hero.y = 0;
ignore=true;
tId = setTimeout(function() { ignore=false; continueExecution() }, 2000) //wait two seconds before continuing
}
function continueExecution()
{
hero.y = -281;
}
Your eventListener functions must not be anonymous:
function keyDown(e) {
keysDown[e.keyCode] = true;
}
addEventListener("keydown",keyDown,false);
function keyUp (e) {
delete keysDown[e.keyCode];
}
addEventListener("keyup",keyUp,false);
Now you can remove the Listeners:
removeEventListener("keyup",keyUp,false);
Alltogether:
function keyDown(e) {
keysDown[e.keyCode] = true;
}
function keyUp (e) {
delete keysDown[e.keyCode];
}
function setEvents(){
addEventListener("keyup",keyUp,false);
addEventListener("keydown",keyDown,false);
}
setEvents()
function yieldEvents(time){
removeEventListener("keyup",keyUp,false);
removeEventListener("keydown",keyDown,false);
setTimeout(setEvents,time);
}
yieldEvents(2000);//e.g.
Try setting a flag
// Handle keyboard controls
var keysDown = {},
ignore = false,tId;
addEventListener("keydown", function(e) {
if (ignore) return false;
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function(e) {
if (ignore) return false;
delete keysDown[e.keyCode];
}, false);
function doStuff() {
ignore = true;
tId = setTimeout(function() { ignore=false; continueExecution() }, 2000) //wait two seconds before continuing
}
if you use jquery you can write the code like this :
$("your_elem").on("keyup",function(){
$(this).off("keyup")
});
else if you want to return it back you can replace the off by the on .

How to trigger popup when browser tab closes in ReactJS?

I have a enrollment form with some customer related information. If user form is half filled and the user is going to close the tab, then I'll trigger the popup with option of save and exit, exit.
I have some jQuery solution. But nowadays it's not working in all browsers.
Jquery sample Code:
'use strict';
$(document).ready(function() {
$.fn.addEvent = function (obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent('on'+evType, fn);
return r;
} else {
return false;
}
};
$.fn.KeepOnPage = function (e) {
var doWarn = 1;
if (!e) {
e = window.event;
}
if (!e) {
return;
}
if (doWarn == 1) { // and condition whatever you want to add here
e.cancelBubble = true;
e.returnValue = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
}
if (e.stopPropagation) {
e.stopPropagation();
}
};
$.fn.addEvent(window, 'beforeunload', $.fn.KeepOnPage);
});
But we need solution in ReactJS. Is there any React library for the browser unload?
Thanks,
Thangadurai
You can add and remove an event listener for the 'beforeunload' event within your componentDidMount and componentWillUnmount lifecycle functions.
https://facebook.github.io/react/docs/component-specs.html
https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
Example:
...
componentDidMount() {
window.addEventListener('beforeunload', this.keepOnPage);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.keepOnPage);
}
keepOnPage(e) {
var message = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
e.returnValue = message;
return message;
}
....

Check which button clicked on page leave prompt?

So I have this code and I'm trying to find out how to check which button the user clicks on the prompt. I'd like to fire an event if they click stay or fire a different event if they leave. Is this possible?
var submitted = false;
$(document).ready(function () {
window.onbeforeunload = function (e) {
if (!submitted) {
var message = "Are you sure you want to leave?", e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
}
$("form").submit(function() {
submitted = true;
});
});
Actually there is no way to find that which button is clicked(in case of onbeforeunload confirm box) according to my knowledge.
But we can achieve the required functionality by following way:
window.onbeforeunload = function (e) {
if( $("table tbody.files tr.template-download.fade").length > 0 )
{
var message = "XYZ",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
}
}
And you can write the code for 'yes' button click inside following:
$( window ).unload(function() {
//--> Here
});
use Javascript "confirm" for that:
if(confirm("Are you sure you want to leave?"))
{
//True part
}
else
{
//False part
}

Alternative to Mozilla 'explicitOriginalTarget' for cross browser functionality

I have a fiddle at: http://jsfiddle.net/radi8/Nt556/1/
This class will bind a listener to all of the 'submit' buttons on a form. When the user clicks on one of the buttons, the class function will process it as necessary. I originally developed this class using FireFox and using the: var btnName = event.originalEvent.explicitOriginalTarget.defaultValue; works great therein, but I later found that this is a Mozilla only function.
Can anyone offer an alternative for IE and Chrome?
my class:
var RequiredField = {
init: function() {
var theForm = document.getElementsByTagName("form");
$(theForm).bind("submit", RequiredField.submitListener);
},
submitListener: function(event) {
event.preventDefault();
var btnName = event.originalEvent.explicitOriginalTarget.defaultValue;
if (btnName == 'Process Route') {
processType = 0;
alert('Process');
}
else if (btnName == 'Finalize Route') {
processType = 1;
alert('Finalize');
}
else {
processType = 99;
}
try {
}
catch (e) {
event.preventDefault();
}
}
};
RequiredField.init();
I'd just bind "click" for the form:
$('form').delegate(':submit', 'click', RequiredField.submitListener);
Then the target of the event will be the button directly.

Setting onbeforeunload on body element in Chrome and IE using jQuery

I have a system where I want to check with the user if they're sure they want to leave the page once a dirty flag is set.
I'm using the following code - In FireFox, I can look at the page source through FireBug and the tag correctly has the onbeforeunload attribute inserted in it.
In Chrome and FireFox, this doesn't happen though and I'm able to navigate away from the page without any warning at all. The jQuery line to update the body tag is definitely being executed, it just isn't performing it.
if ($("body").attr('onbeforeunload') == null) {
if (window.event) {
// IE and Chrome use this
$("body").attr('onbeforeunload', 'CatchLeavePage(event)');
}
else {
// Firefox uses this
$("body").attr('onbeforeunload', 'return false;CatchLeavePage(event)');
}
}
Any ideas how to proceed from here?
you cannot abort page unload by returning false. you must return string that will be shown to user in a message box, and he decides if he want to leave or stay on the page (by selecting either 'OK' or 'Cancel' button), so you need to write your code like this:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
};
try this
<script type=\"text/javascript\">
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
var leave_message = 'You sure you want to leave?'
function goodbye(e)
{
if(dont_confirm_leave!==1)
{
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = leave_message;
//e.stopPropagation works in Firefox.
if (e.stopPropagation)
{
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
return leave_message;
}
}
window.onbeforeunload=goodbye;
</script>
window.onbeforeunload = function () { return 'Are you sure?' };
Check this code :
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0;
var leave_message = "You sure you want to leave ?";
function goodbye(e) {
if (!validNavigation) {
if (dont_confirm_leave !== 1) {
if (!e) e = window.event;
e.cancelBubble = true;
e.returnValue = leave_message;
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
return leave_message;
}
}
}
window.onbeforeunload = goodbye;
document.onkeydown = function () {
switch (event.keyCode || e.which) {
case 116 : //F5 button
validNavigation = true;
case 114 : //F5 button
validNavigation = true;
case 82 : //R button
if (event.ctrlKey) {
validNavigation = true;
}
case 13 : //Press enter
validNavigation = true;
}
}
// Attach the event click for all links in the page
$("a").bind("click", function () {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function () {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function () {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function () {
wireUpEvents();
});
It's not pretty, but it did the trick.
var warnclose = true;
var warn = function(e) {
var warning = 'Your warning message.';
if (warnclose) {
// Disables multiple calls
warnclose = false;
// In case we still need warn to be called again
setTimeout(function(){
warnclose = true;
}, 500);
return warning;
}
};
window.onbeforeunload = warn;

Categories