onbeforeunload event exception? - javascript

i am wondering if there is a way to make onbeforeunload event alert be triggered with any other case except a specific function induced page reload.
most of the previously answered questions are at best 3 years old.
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
document.getElementById("reload").addEventListener("click", myFunction);
function myFunction() {
location.reload();
} // I WANT TO EXCLUDE THIS FUNCTION FROM ONBEFOREUNLOAD EVENT ALERT
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
<button id="reload">RELOAD FROM HERE SHOULD NOT TRIGGER ONBEFOREUNLOAD ALERT</button>
</body>
</html>

A simple solution would be to set a flag, and check that flag in the beforeunload listener:
let beforeUnloadAlert = true;
window.addEventListener('beforeunload', function (e) {
if (!beforeUnloadAlert) return;
// etc
e.preventDefault();
e.returnValue = '';
});
function myFunction() {
beforeUnloadAlert = false;
location.reload();
}
Another approach would be to remove the listener just before calling .reload, by putting the listener in a named function:
window.addEventListener('beforeunload', unloadHandler);
function myFunction() {
window.removeEventListener('beforeunload', unloadHandler);
location.reload();
}

Related

Javascript: call function inside another function

I have a simple code which calls a function func1() when the user presses "A". Inside func1() I would like that, if a certain condition is satisfied, another function func2() is called and func1() is stopped.(A short example of what I am doing is shown below). How can I do this? Thank you!
<html>
<head>
</head>
<body>
<script>
$(document).ready(function() {
document.addEventListener("keydown", function (e) {
else if (e.keyCode === 83) { // If "S" is pressed the game starts
func1();
}
});
})
function func1(){
$(document).ready(function() {
document.addEventListener("click", function(e) {
var myVar = Math.floor( Math.random() *6);
if (myVar>3){
func2();
}
}, false);
});
}
function func2(){
/////
}
</script>
You need to refactor your code and remove the unnecessary call to $(document).ready(). I'm assuming it's the click event you want to disable...
Let me know if it's the keypress you want to disable.
EDIT:
I edited the code to remove the func2 event listener when 's' key is pressed, and add click event listener to document when func2 is called.
$(document).ready(function() {
document.addEventListener("keydown", function(e) {
var keyCode = e.which || e.keyCode;
$('.keypressed').html(String.fromCharCode(keyCode));
if (keyCode === 83) { // If "S" is pressed the game starts
document.removeEventListener('click', helper2);
func1();
}
});
});
//refactored the handler function to stand on its own
function helper(e) {
var myVar = Math.floor(Math.random() * 6);
console.log('myVar in func1() = ', myVar);
if (myVar > 3) {
func2(e);
return;
}
}
function helper2(e) {
console.log('func2() click event called!')
}
function func1() {
document.addEventListener("click", helper, false);
}
function func2(e) {
//disable the click event listener
document.removeEventListener('click', helper);
document.addEventListener('click', helper2)
console.log('called func2()');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<div class="keypressed"></div>
<body>
</body>
</html>
You can use .off() to remove event listener attached to jQuery object. .ready() call within func1 is not necessary.
else..if should be if, unless there is if statement not included at javascript at Question.
$(document).on("keydown", function() {
if (/* condition */) {
$(this).off("keydown");
func1();
}
});
function func1() {
$(document).on("click", function() {
if (/* condition */) {
$(this).off("click");
func2();
}
})
}

how to use window.onbeforeunload?

I have a small webpage. i need to activate my ajax function when browser is closed
I using below JavaScript for that in the <head>
<script language="JavaScript" type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
my ajax_function();
return "";
}
</script>
But this function works all in the Back button, Forward button, ALT+f5, CTL+f5, Submit etc... But i need this function only when browser is closed
But i try like below in my webpage to block the events like Back button, Forward button, ALT+f5, CTL+f5, Submit etc...
<script type="text/javascript">
$(function () {
$('a').click(function(){window.onbeforeunload = null;});
$(window).keydown(function(event) {
if (event.keyCode == 116) { // User presses F5 to refresh
window.onbeforeunload = null;
}});
$('form').submit(function() {
window.onbeforeunload = null;
});
});
</script>
But this only for hyperlink, refresh, and submit.
What i need is, window.onbeforeunload function only works when browser is closed
JavaScript doesn't distinguish between these events, they are all triggered because the user is leaving the page.

How to capture browser close event?

I want to capture the browser close event in my application and show a confirm box to user.
I am using JSF 2.0 and richfaces 4.0.
window.onbeforeunload = function ()
{
var shallIAlertUser = Do_Whatever(); //get boolen value
if (shallIAlertUser) {
//this will alert user
return 'Are you sure?';
}
else {
//this wont
window.onbeforeunload = undefined;
}
};
Use the beforeunload event.
window.onbeforeunload = function(event) {
event = event || window.event;
var confirmClose = 'Are you sure?';
// For IE and Firefox prior to version 4
if (event) {
event.returnValue = confirmClose;
}
// For Safari
return confirmClose;
}
Keep in mind this will be fire for other events besides closing the window, such as reloading and form submission.
onbeforeunload
< body onbeforeunload="alert('Closing');">
Example :
<html>
<head>
<title>`onbeforeunload` Event Demo</title>
</head>
<body onbeforeunload="return 'Are you sure you want to exit ?';">
</body>
</html>
Attach a handler to the unload event.

href="#" appends # on end of page url

Let's say I have the following link:
Click Me!
When clicked this link will alert a message as well as appending a pound sign on the end of the page url. This doesn't look very pretty is there any way to avoid it besides using javascript in the url itself:
Click Me!
You have to prevent the default response from occurring.
The old-fashioned approach is to return false from it:
Click Me!
Or, better:
Click Me!
<script type="text/javascript">
window.onload = function() {
document.getElementById('myLink').onclick = function(event) {
alert('You clicked a link.');
return false;
};
};
</script>
The best approach nowadays is to call the proper method of the event property:
Click Me!
<script type="text/javascript">
window.onload = function() {
document.getElementById('myLink').onclick = function(event) {
alert('You clicked a link.');
event.preventDefault(); // <---
};
};
</script>
It's also best to replace that # with an URI to some proper page, for people not using JavaScript. In some jurisdictions, accessibility is in fact a legal requirement.
Edit Fixed for bleedin' IE:
function f() {
document.getElementById('myLink').onclick = function(e) {
alert('You clicked a link.');
if (!e) {
var e = window.event;
}
// e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;
// e.stopPropagation works only in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
};
window.onload = f;
The trick is return false on the event handler.
Click Me!

Keypress in javascript in IE

I have a Flex application. It running in a player on the HTML-page. I need catch the key press events and prevent IE browser from acting like it wants. Here's some code:
Actually, the part where player was layed ..
<html>
<head>
</head>
<body scroll="no" onkeydown=keypress(event)>
<noscript>
<object id="app" width="100%" height="100%" onkeydown="keypress(event)" onkeypress="keypress(event)">
//some params
</object>
</noscript>
</body>
</html>
And here's the one, where I'm trying in a different ways to catch key input:
<script language="JavaScript" type="text/javascript">
function keypress(e) {
alert("Hello from keypress");
}
function init() {
//index
alert("Init!!!");
document.getElementById('app').onkeydown = function() {
alert("Key Pressed - 1");
};
document.onkeydown = function() {
alert("Key Pressed - 2");
};
document.getElementById('app').onkeypress = function() {
alert("Key Pressed - 3")
};
document.onkeypress = function() {
alert("Key Pressed - 4")
};
window.onkeydown = function() {
alert("Key Pressed - 5");
};
window.onkeypress = function() {
alert("Key Pressed - 6");
};
document.body.onkeypress = function() {
alert("Key Pressed - 7")
};
document.body.onkeydown = function() {
alert("Key Pressed - 8")
};
if (window.addEventListener) {
window.addEventListener('keypress', keypress, false);
} else if (window.attachEvent) {
window.attachEvent('onkeypress', keypress);
} else {
window.onkeypress = keypress;
}
}
window.onload = init;
document.onload = init;
</script>
I wasn't going to use them all together, just gathered them all to show you that I've tried almost everything (also including all this with 1 parameter).
The problem is that the only Alert I'm getting is "Init!!!". What's wrong with it or what I'm doing wrong?
Any help would be greatly appreciated.
Edit: I get the "Init" message before the player loads it's content .. maybe the problem is somewhere there?
In Internet Explorer, events that occur within an embedded control in the <object> element do not fire equivalent events on the DOM object. They are consumed by the embedded control, and it is that control's responsibility to handle them accordingly.
This means, when your embedded Flex application is focussed, your JavaScript code will not be able to handle any key events.

Categories

Resources