how to use window.onbeforeunload? - javascript

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.

Related

show alert message when closing a window? Not Working

I want to show alert before closing a prticluar tab. I have tried different codes over here but couldn't suceeded somwhow.. could somebody guide me where I am going wrong..
My Last try was :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" />
</head>
<body>
<script>
window.onbeforeunload = function (event) {
var message = 'Sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
</script>
</body>
</html>
Depending on your browser your code works. I've updated the snippet below so it always sets a returnValue which is required by some browsers. If you click the Run code snippet button below and attempt to close the tab you'll get an alert asking if you're sure you want to leave.
However what's important to know is that most browsers have removed the ability to serve custom messages on these alerts for security purposes.
window.onbeforeunload = function (event) {
event.preventDefault();
event.returnValue = '';
};

Capture browser close event

I want to capture browser close event using javascript. I googled but I am not getting any solution anywhere,below is my code where I have handled anchor, Form Submit and Submit button on onbeforeunload.
<script>
var validNavigation = false;
function wireUpEvents() {
window.onbeforeunload = function() {
if (!validNavigation) {
// invalidate session
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keydown', function(e) {
if (e.keyCode == 116){
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();
});
</script>
Is there any way I can capture browser close button event, I have seen developers using X and Y axis but that is not recommended most of developers.
Thanks..
You can try this .. prompting user to confirm before closing tab. and you can do some thing you need
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>

Notify user on browser close only

I am trying to implement notifying when the user closes or reloades the page.Crrently i am using the following code
function unloadPage(){
return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;
This works fine.But the problem is this happens whenever a navigation takes place.That is either a page refresh or a form submission or a hyperlink click or whatever navigation takes place..I just want to work this code only for browser refreshing and closing.I knew about setting a flag and checking it.
But i have to integrate this in a big application.So it will be difficult to add the code in every page.So is there an easy way.
Is there a way to catch the refresh or browser cosing so that can use it.
Note that in your code, you're using onbeforeclose, but the event name is beforeunload, so property is onbeforeunload, not onbeforeclose.
I just want to work this code only for browser refreshing and closing. Is there a way to catch the refresh or browser cosing so that can use it.
No. Instead, you'll have to capture each link and form submission and either set a flag telling your onbeforeunload handler not to return a string, or removing your onbeforeunload handler (probably the flag is cleaner).
For example:
var warnBeforeClose = true;
function unloadPage(){
if (warnBeforeClose) {
return "Your changes will not be saved.";
}
}
window.onbeforeunload = unloadPage;
// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
// Don't warn
warnBeforeClose = false;
// ...but if we're still on the page a second later, set the flag again
setTimeout(function() {
warnBeforeClose = true;
}, 1000);
}
Or without setTimeout (but still with a timeout):
var warningSuppressionTime = 0;
function unloadPage(){
if (+new Date() - warningSuppressionTime > 1000) { // More than a second
return "Your changes will not be saved.";
}
}
window.onbeforeunload = unloadPage;
// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
// Don't warn for the next second
warningSuppressionTime = +new Date();
}
Update in 2017: Also note that as of at least a couple of years ago, browsers don't show the message you return; they just use the fact you returned something other than null as a flag to show their own, built-in message instead.
One of the simple solutions to your problem is to have a flag and then call your function only if the flag is valid. In this case , you can bind the anchor tags, F5 key and form submit button click to events that set the flag as false. So your alert bar will be visible only if the above cases don't happen :)
Here's the script:
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
alert("bye");
}
function wireUpEvents() {
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
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();
});
Check this link
It gives you information on how to handle onbeforeunload event.
The idea is to have a global flag on the page. When any change is done to the fields, this flag is set to true. When clicked on save button, then this flag needs to be set to false.
In the onbeforeunload event, check whether the flag is true, then show the message accordingly.
var needToConfirm = true;
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (needToConfirm)
{
// check on the elements whether any change has been done on the fields.
// If any change has been done, then set message here.
}
}
function saveClicked()
{
needToConfirm = false;
}
DEMO
(Run or refresh the fiddle to see the alert onbeforeunload() event message and click on the link "kk" ,it wont show onbeforeunload() event message. Try it in your webpage)
I have a solution for you, you don have to add onclick event to each tags and all.
Just add this to any where on your pages .
<input type="hidden" value="true" id="chk"/>
and add this code to your document head tag
<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
if(document.getElementById("chk").value=="true")
{
return "Your changes will not be saved.";
}
}
document.onclick = myClickHandler;
function myClickHandler() {
document.getElementById("chk").value="false";
}
<script>
Hope this helps
Thank you

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.

Handle refresh page event with JavaScript

Is it possible to use JavaScript to handle the event of refreshing page?
What I want is get notice if user do one of these behaviours:
refresh page by pressing F5
close tab or browser
enter a new url then press enter on
browser
to display a warning message?
You don't want the refresh, you want the onbeforeunload event.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
Sample code from article
<HTML>
<head>
<script>
function closeIt()
{
return "Any string value here forces a dialog box to \n" +
"appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
<a href="http://www.microsoft.com">Click here to navigate to
www.microsoft.com</a>
</body>
</html>
The closest you could get is the window.onbeforeunload event:
window.onbeforeunload = function (e) {
var e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = 'Leaving the page';
}
// For Safari
return 'Leaving the page';
};
It is important to note that you need to return a string from this function.

Categories

Resources