Jquery Show Popup only when window is closed - javascript

I am trying to display a confirmation message when the user closes the browser/tab and not when any of the links on page is clicked.
I have got the first part of displaying the message on window close working nicely but problem is that the message/alert is displayed also when user clicks on any link on the page.
I have got code from somewhere to prevent this behavior but still when ever any link is clicked the alert pops up.
Here is the code:
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/backfix-min.js"></script>
$(document).ready(function() {
$(window).bind('beforeunload', function(e){
$("#lead-gen-modal").dialog("open");
// This line only appears in alert boxes for IE
return "Wait\! Don\'t Go\! We have a special offer for you\. Stay on this page to receive big savings\!";
});
$("a").click(function() {
window.onbeforeunload=null;
});
});

just use a global variable
and set it to false when clicking a link.
var key = true;
$(window).bind('beforeunload', function(e){
if(key)
$("#lead-gen-modal").dialog("open");
});
update :
$(document).on("click","a",function() {
key=false;
});
or if you just want to prevent closing window you can do this :
window.onbeforeunload = function(e){
if(key)
return false;
}

I think you are looking for something like this.
$(window).unload(function() {
alert("bye");
});
If that does not work on Chrome try this
$(window).on('beforeunload', function() {
return "bye";
});
jQuery API: unload() http://api.jquery.com/unload/

Related

How to detect browser close event in MS Edge?

We are using jQuery v1.11.3
The requirement is to display a Confirmation dialog with Yes and No button. The Confirmation dialog needs to be displayed before closing the browser and when user click on close icon.
Below code tried to use but not working .
<script type="text/javascript">
$(document).ready(function(){
$(window).bind("beforeunload", function() {
return "Do you really want to close?";
});
});
window.onbeforeunload = function(e){
return 'Calling some alert messages here';
}
</script>

Jquery Exit Popup Confusion

I have the following code
<script type="text/javascript">
function PopIt() { return 'Are you sure you want to leave?'; }
function UnPopIt() { /* nothing to return */ }
$(document).ready(function() {
window.onbeforeunload = PopIt;
$('a').click(function(){ window.onbeforeunload = UnPopIt; });
});
</script>
This script works. But how do I alter it so it works like this;
1) User presses exit tab/page
2) page changes to one of my choice
3) exit popup displays with yes or no to leave
4) yes = close page, no = stay on current page
I'd like the page to change before the popup displays
Thanks.
Note: I do have control over the pages, I wish to redirect to another .php in the same folder.
Try using both onbeforeunload and onunload together like this...
function PopIt() {
return 'Are you sure you want to leave?';
}
function UnloadIt() {
window.opener.nowDoThisOpener("pass this variable along too");
}
$(document).ready(function() {
//set the function defining what should be done BEFORE unloading
window.onbeforeunload = PopIt;
//set the function defining what should be done ON unloading
window.onunload = UnloadIt;
//set all links to disable both of these on click
$('a').click(function(){
window.onbeforeunload = null;
window.onunload=null;
});
});
Note that nowDoThisOpener is a function that you can define (And obviously call whatever you want) on the parent page. And, like I've suggested, you can pass along information too.
Also, in your example you were setting an empty function UnPopIt to cancel the onbeforeunload. That's unnecessary, you can just set the onbeforeunload to null, as well as the onunload, as I've done in my example.
Previous Answer:
Could you put some kind of flag in the hash when you redirect? So instead of sending off to http://www.pageofmy.com/choice.php you sent to http://www.pageofmy.com/choice.php#1
Then on choice.php you could have...
<script>
if (location.hash=="#1") {
//show alert
}
</script>
This assumes that you have control over pageofmy.com/choice.php. If you're redirecting to some other site you don't have control over, I don't see how you can do this besides attempting to have a popup window come up (which will most likely be blocked by modern browsers)

Controlling the Back button using onhashchange or jquery

I need some guidance on how to have very basic control in the use of the back button.
Basically, I need to warn the user that by clicking the back button, when on my checkout.asp page, they will lose the items already there. I need to instruct them to use the navigation buttons instead.
I've had a look around a have seen mention of the onhashchange event but I could not get it to work.
I also tried the plugin by Ben Alman:
<script type="text/javascript" src="jquery/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery.ba-hashchange.js"></script>
<script language="JavaScript" type="text/JavaScript">
$(function(){
// Bind the event.
$(window).hashchange( function(){
// Alerts every time the hash changes!
alert( location.hash );
})
// Trigger the event (useful on page load).
$(window).hashchange();
});
</script>
This only fires up the alert (with no value from the location.hash) when entering the page but I simply want to warn the user if they're leaving. If they choose to stay then let them press cancel to leave them on the same page.
Any help appreciated.
Use:
window.onbeforeunload = function() {
return confirm("you have unsaved data. ok to exit?")
})
In order to only show a warning when the back button is used, we have to eliminate the alert message when a valid source is clicked.
var showWarning = true;
window.onbeforeunload = function() {
if (showWarning) {
return confirm("you have unsaved data. ok to exit?");
}
}
function clearWarning() {
showWarning = false;
}
Now just make sure to call the clearWarning() function when an allowed button is clicked. Something like this should work:
referenceToElement.addEventListener('onClick', clearWarning(), false);
I have not tested this, but I would imagine that something like this is what you need.

JavaScript before leaving the page

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload
<script type="text/javascript">
function con() {
var answer = confirm("do you want to check our other products")
if (answer){
alert("bye");
}
else{
window.location = "http://www.example.com";
}
}
</script>
</head>
<body onunload="con();">
<h1 style="text-align:center">main page</h1>
</body>
</html>
But it confirm after page already closed? How to do it properly?
It would be even better if someone shows how to do it with jQuery?
onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.
If you want to show a prompt before the user leaves the page, use onbeforeunload:
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.
You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):
window.onunload = function() {
alert('Bye.');
}
Or with jQuery:
$(window).unload(function(){
alert('Bye.');
});
This code when you also detect form state changed or not.
$('#form').data('serialize',$('#form').serialize()); // On load save form current state
$(window).bind('beforeunload', function(e){
if($('#form').serialize()!=$('#form').data('serialize'))return true;
else e=null; // i.e; if form state change show warning box, else don't show it.
});
You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)
This what I did to show the confirmation message just when I have unsaved data
window.onbeforeunload = function() {
if (isDirty) {
return 'There is unsaved data.';
}
return undefined;
}
returning undefined will disable the confirmation
Note: returning null will not work with IE
Also you can use undefined to disable the confirmation
window.onbeforeunload = undefined;
This will alert on leaving current page
<script type='text/javascript'>
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
</script>
In order to have a popop with Chrome 14+, you need to do the following :
jQuery(window).bind('beforeunload', function(){
return 'my text';
});
The user will be asked if he want to stay or leave.
You can use the following one-liner to always ask the user before leaving the page.
window.onbeforeunload = s => "";
To ask the user when something on the page has been modified, see this answer.
Most of the solutions here did not work for me so I used the one found here
I also added a variable to allow the confirm box or not
window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
if (!hideWarning) {
event.preventDefault();
event.returnValue = '';
}
});
Normally you want to show this message, when the user has made changes in a form, but they are not saved.
Take this approach to show a message, only when the user has changed something
var form = $('#your-form'),
original = form.serialize()
form.submit(function(){
window.onbeforeunload = null
})
window.onbeforeunload = function(){
if (form.serialize() != original)
return 'Are you sure you want to leave?'
}
<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
Click here to go to w3schools.com
<script>
function myFunction() {
return "Write something clever here...";
}
</script>
</body>
</html>
https://www.w3schools.com/tags/ev_onbeforeunload.asp
Just a bit more helpful, enable and disable
$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');

Javascript alert when user closes the tab or the window [duplicate]

I want when a user closes the tab or window or when he tries to move to another location different from my site to pops a confirm box, and if he confirm to execute an ajax script and then to close or change the window. I don't know how to do that. PS: I'm using jQuery.
$(window).unload(function() {
var answer=confirm("Are you sure you want to leave?");
if(answer){
//ajax call here
}
});
Just add your own alert/dialogue code to the function.
<script language="JavaScript">
function unload() {
alert('window closed');
}
window.onunload = unload;
</script>

Categories