How to capture browser close event? - javascript

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.

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 = '';
};

Execute a method upon clicking stay on page in confirmation dialog on browser close

I got to know how we can get a popup when the user tries to close the browser. Now my question how can we execute some piece of code if the user says 'Stay on page'? is there any click handler for that button?
Try using the onbeforeunload event.
(function () {
var oldMousemove = document.body.onmousemove,
onCancel = function () {
// Do something if the user stays.
document.body.onmousemove = oldMousemove;
};
window.onbeforeunload = function() {
document.body.onmousemove = onCancel;
return 'Do you really want to leave?';
};
})();
Note: Most browsers won't respect the custom prompt statement and will favor their own instead.
<script>
(function(){
window.onbeforeunload = function (e) {
if(!e) var e = window.event;
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
}());
</script>
Works in Firefox and IE 9

how to close a popup window when the focus is gone out from it

Requirement: A popup will be opened up from parent window, and it should get closed when the focus from the window is lost. (This should happen even when another application window is opened or came into focus).
Tried code:
<body onBlur='javascript:window.close();'>
Issue:
On click within the body of the popup makes the popup closed.
Compatibility: ie6 and above, firefox.
I got a workaround from http://pro-thoughts.blogspot.com/2006/10/incorrect-behavior-of-windowonblur.html
var active_element;
var bIsMSIE;
function initiateSelfClosing() {
if (navigator.appName == "Microsoft Internet Explorer") {
active_element = document.activeElement;
document.onfocusout = closeWnd;
bIsMSIE = true;
}
else { window.onblur = closeWnd; }
}
function closeWnd() {
if (window.opener != null) {
if (bIsMSIE && (active_element != document.activeElement)) {
active_element = document.activeElement;
}
else {
window.close();
}
}
}
<body onload="initiateSelfClosing()">
</body>
But here also one problem is there, if there is a print button in the page, and if am clicking on print > then cancelling the print job, the popup is getting closed.
Can some one help me pls...
Little corrections in sathishkumar's answer
1.we need to convert win to jquery object
2.Apply blur event on jqvariable and not on window
3.this.close is good enough in definition of onblur event
var win = window.open("URL");
var jqwin = $(win);
$(jqwin).blur(function() {
this.close();
});
Use document for blur event
var win = window.open("URL");
$(window).blur(function() {
win.close();
});
You cannot attach onblur event to BODY but
you Can attach a function on Onblur event of window.
<script type="text/javascript">
function closeme()
{
window.close();
}
window.onblur=closeme;
</script>
Since you have Edited your Question, You can get more help here

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!

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