Capture browser close event - javascript

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>

Related

Prevent beforeunload function from executing if submit button is clicked

I have the following function that gives a warning to the user if they are exiting the page when the $('.article_div textarea') form field is populated.
$(window).on('beforeunload', function(event) {
var unsaved = "Are you sure you want to exit?";
var text = $('.article_div textarea').val();
if (text.length > 0){
return unsaved;
}
});
However, I would like to prevent this popup from executing when they click the submit button to the actual form.
How can I ammend the function to account for this? The element of the submit button is
$('button.submit_post').
You can create a boolean which gets positive when you click on submit Or remove the event of unload when clicked. The code will be as follows:
var isSubmitClicked = false;
$('button .submit_post').on("click",onClick);
function onClick(e){
isSubmitClicked = true;
}
$(window).on('beforeunload', function(event) {
if(isSubmitClicked){
isSubmitClicked = false;
return;
}
// Rest of your method.
}
How about binding a event handler to the submit event instead of the submit button element?
Maybe like this:
var submitted = false;
$('form').on("submit", function() {
submitted = true;
console.log('submitted');
});
$(window).on('beforeunload', function(event) {
if(submitted){
submitted = false;
console.log('aborted because of submit');
return;
}
console.log('rest of code');
// Rest of your method.
});

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

A confirmation popup in JS

I am looking into making a confirmation menu in JavaScript to where it will run a set of code depending if you select yes or no.
Now I want it to happen on the window.onbeforeunload event but only when the individual presses "yes" do I want the rest of the code to work. If they press "no" I want the window.onbeforeunload to be cancelled outright. I am wondering if it is at all possible and how. Here is what I have so far. The reason why I want this is because when I run the script the popup shows up on return but before someone would get to choose to stay or leave. The click(); feature starts up erasing the information. I want the .click(); to start up after someone presses "yes" on the return and only if they press "yes".
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0;
var leave_message = document.getElementById("kioskform:broswerCloseSubmit");
var leave_safari = document.getElementById("kioskform:broswerCloseSafari");
function goodbye(e) {
if (!validNavigation) {
function disp_confirm()
{
var leaveMessage=confirm("Are you sure you want to leave")
if (leaveMessage==true)
{ if (dont_confirm_leave!==1) {
if(!e) e = window.event;
//for IE
e.cancelBubble = true;
e.returnValue = leave_message.click();
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
leave_safari.click();
return '';
//add the code to delete the kiosk information here.
// this is what is to be done.
}
}
else
{
Alert("Returning to the page.")
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
jQuery('document').bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
jQuery("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
jQuery("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
jQuery("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function() {
wireUpEvents();
});
Why not just use window.confirm?

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

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!

Categories

Resources