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)
Related
I've been asked to have a pop-up when visitors leave the site asking them if they really want to leave. This pop-up will only show if their shopping cart has items in it.
I can easily limit the pop-up to when the cart has items, however the issue I'm having is that even clicking an internal link loads the pop-up - how can I have it so this only comes up when actually leaving the site.
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "some message about leaving";
}
</script>
If a link is clicked, it will tell you in e.target.activeElement. You can check if it's a link there:
window.onbeforeunload = confirmExit;
function confirmExit(e)
{
var $element = $(e.target.activeElement);
if ($element.prop("tagName") !== "A") {
return "some message about leaving";
}
}
Note: You can add additional conditions checking $element.attr("href") to make sure it displays the message for links that aren't your site.
Alright first of all: Don't do this. Please. It's super-annoying for users. Just make sure the shopping cart items are stored on the server or in a cookie so users can always go back to the site.
Looking at this related question: How can i get the destination url in javascript onbeforeunload event? it can't be done easily.
Instead of using onbeforeunload, either attach a click handler to external links on your site that shows the popup, or attach a click handler to all links that checks if the link is external or not.
Again, don't do this...
You could get the URL of a clicked link item, and check if it's on the same domain. Put this in an if not statement, with the current code inside.
you'll have to control it to enable and disable the behavior, something like this:
<script>
var beforeunload = function (event) {
var message = 'some message about leaving';
(event || window.event).returnValue = message; // Gecko + IE
return message; // Webkit, Safari, Chrome...
};
document.addEventListener('click', function(event) {
if (event.target.tagName === 'A') {
window.removeEventListener('beforeunload', beforeunload);
}
});
window.addEventListener('beforeunload', beforeunload);
</script>
this is going to remove the beforeunload event whenever a link is clicked on the page.
One way, and again, I wouldn't recommend doing this either - the user should be able to leave your site without receiving a warning - but you could unregister the event if a link has been clicked:
$('a').click(function() {
window.onbeforeunload = null;
return true; // continue
});
I know there are a lot of questions regarding this but nothing is answering me right. I want to show a confirmation dialog when user leaves the page. If the user press Cancel he will stay on page and if OK the changes that he has made will be rollback-ed by calling a method. I have done like this:
window.onbeforeunload = function () {
var r = confirm( "Do you want to leave?" );
if (r == true) {
//I will call my method
}
else {
return false;
}
};
The problem is that I am getting the browser default popup: "LeavePage / StayOnPage"
This page is asking you to confirm that you want to leave - data you
have entered may not be saved.
This message is shown in Firefox, in Chrome is a little different. I get this popup after I press OK on my first confirmation dialog.
Is there a way not to show this dialog? (the second one, that I did not create).
Or if there is any way to control this popup, does anyone know how to do that?
Thanks
Here's what I've done, modify to fit your needs:
// This default onbeforeunload event
window.onbeforeunload = function(){
return "Do you want to leave?"
}
// A jQuery event (I think), which is triggered after "onbeforeunload"
$(window).unload(function(){
//I will call my method
});
Note: it's tested to work in Google Chrome, IE8 and IE10.
This is simple. Just use
window.onbeforeunload = function(){
return '';
};
to prompt when the user reloads, and
window.close = function(){
return '';
};
to prompt when the user closes the page.
But the user have to click on the page once, or do anything on the page for the code to detect. You don't have to put anything the the return'';, because JavaScript interpreter would just ignore it.
window.onbeforeunload = function() {
if (data_needs_saving()) {
return "Do you really want to leave our brilliant application?";
} else {
return;
}
};
I realize this is likely a duplicate, but I've been googling/SOing for a day now and I can't find a satisfactory answer. If there is an answer already on SO, please send me there.
I have a client that insists on having an exit message popup confirming they want to exit the site, just like Gmail does. (I've already tried arguing against it. He is immovable, so no comments about how that is bad practice please.)
I've found this code:
<script>
window.onbeforeunload = function() {
return 'Are you sure you want to exit?';
}
<script>
But it runs no matter what I do - reloading the page, clicking on the nav, etc.
I just want the message to show up when the user closes the tab/browser. I suspect it's something simple I'm missing but I'm not a Javascript expert.
Any help would be greatly appreciated.
Thanks
EDIT
Here's what is working pretty good. Thanks to all!
var isLeavingSite = true;
//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
isLeavingSite = false;
});
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):
var isLeavingSite = true;
//This would be called on each link/button click that navigates
function GlobalLinkHandler()
{
isLeavingSite = false;
}
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
If you're using jQuery, you can use the code below to flip the isLeavingSite flag:
$('a, input[type="submit"]').click(function(){ isLeavingSite = false; });
What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the onbeforeunload event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.
You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the onbeforeunload event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.
If your using jQuery try this Confirm before exit
I have a handler for onbeforeunload
window.onbeforeunload = unloadMess;
function unloadMess(){
var conf = confirm("Wait! Before you go, please share your stories or experiences on the message forum.");
if(conf){
window.location.href = "http://www.domain.com/message-forum";
}
}
but I'm not sure how to know if the url they clicked on the page is within the site.
I just want them to alert them if they will leave the site.
It's not possible to do this 100% reliably, but if you detect when the user has clicked on a link on your page, you could use that as a mostly-correct signal. Something like this:
window.localLinkClicked = false;
$("a").live("click", function() {
var url = $(this).attr("href");
// check if the link is relative or to your domain
if (! /^https?:\/\/./.test(url) || /https?:\/\/yourdomain\.com/.test(url)) {
window.localLinkClicked = true;
}
});
window.onbeforeunload = function() {
if (window.localLinkClicked) {
// do stuff
} else {
// don't
}
}
I've got one idea, but I don't know if it's work. My suggestion is, add each link an onClick event with a function call. That function reads just the href attribute and store into a variable with global scope.
var clickedHrefAttrValue = "";
function getClickUrl(currentLink)
{
clickedHrefAttrValue = $(currentLink).attr("href");
return true;
}
The html for the a tags must be looks like following:
Linktext
and in your given function:
function getClickUrl()
{
if (clickedHrefAttrValue.indexOf("<your condition>" > -1)
{
//what ever you want do to
}
}
It is just an idea, but I think it is worth to try it.
If you are having issues because your website may have both absolute and relative local links, I have another solution (using jQuery):
Demo
/* EXTERNAL LINK WARNING
=========================================*/
$('a').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href'),
host = location.host;
if (url.indexOf(host) > -1 || url.indexOf('http','https') == -1){
/* If we find the host name within the URL,
OR if we do not find http or https,
meaning it is a relative internal link
*/
window.location.href = url;
} else {
var warn = confirm('You\'re leaving the domain.\n\nAre you sure?');
if(warn == true) {
window.location.href = url,'_blank';
} else {
e.preventDefault;
}
}
});
So I needed to do this so I could log a user out if they left the site from any page, but not if they navigate within the site. Here is my solution using JS and PHP
On every page where they need to remain logged in, set a session variable:
<?php
session_start();
$_SESSION["isInSession"] = true;
?>
Now create two scripts:
clear-in-session.php
<?php
session_start();
unset($_SESSION["isInSession"]);
?>
logout.php
<?php
session_start();
if(isset($_SESSION["isInSession"]) exit();
//do logout code here
?>
Now we set 2 events in JS:
window.addEventListener('beforeunload', function(event) {
$.ajax({
type: 'POST',
async: false,
url: 'clear-in-session.php'
});
});
window.addEventListener('unload', function(event) {
$.ajax({
type: 'POST',
async: false,
url: 'logout.php'
});
});
To explain the order of events when the user navigates to another page in the same site:
The user navigates away
beforeunload is triggered, calling clear-in-session.php which removes the isInSession variable
The new page is loaded, setting isInSession to true
unload is triggered, calling logout.php, but because isInSession has been set back to true, the logout code is never called
When the user navigates to a page outside of the site (or to any page on the site that doesn't set isInSession):
The user navigates away
beforeunload is triggered, calling clear-in-session.php which removes the isInSession variable
The new page is loaded
unload is triggered, calling logout.php, isInSession has been deleted, so the logout code is called
Sorry for necro but this thread still comes up when searching for the answer to this question
Note: This answer uses jQuery for post calls to the php. It is entirely possible to do this in pure JS, but it was easier to illustrate in jQuery
There is a good solution to this which I implemented in my website recently. Just imagine this, everything thats going to be in your website that navigates the user is either going to be a link (anchor tag), button, clickable image or something on these lines. Its definitely not going to be the body element.
Now what happens when a user leaves the website, he/she can either type in a url and press enter, click a bookmark or press the back/forward buttons.
When a user does do that, do this:
$(window).on('beforeunload', function(e)){
if(e.target.activeElement.nodeName.toLowerCase() == 'body'){
yourFunction();
});
What happens is that the body becomes the active element in the target in these cases (when user leaves the website) and this is not the case when the user clicks on internal website navigable elements.
This is a clean, easy solution. Let me know if you face any issues.
This sounded like something almost impossible to do when it was presented to me. I know you can display a dialog box to confirm when leaving a web page. But is it possible to display a dialog box when leaving a site?
I haven't been able to find/create anything that can read the address bar and know that you're leaving the site.
First off define which events can actually take your user away from your site?
A click of a link inside your web site content
A submit of a form to an outside action
A javascript from a child window that changes window.location on its parent
User starting a search in the search bar (FF and IE)
User entering a search/address in the browser address bar.
User hitting a back button (or backspace) when it just came to your site
User hitting a forward button (or shift-backspace) when they were off the site before but came back by getting there via Back button functionality
User closes the browser window
So. what can you do about all these?
These are easy. Check your anchors and if they do point outside, add some functionality in the onclick event
Similar to 1. Add your functionality for the onsubmit event of the form posting back outside of your site.
-> 8. don't really have an applicable solution that could be controlled. You can abuse onbeforeunload event as much as you want, but you won't have much success of knowing what's going on. And there are certain limitations related to onbeforeunload as well, so your hands will be tied most of the time.
The real question?
Why would you want to control this event anyway except for bothering your users not to leave you. Begging doesn't give much justice in the web world anyway. And when some site would bother me with messages or even worse prevent me from leaving I wouldn't want to get back anymore. It smells of bad bad bad usability and gives a hint of adware site.
Rather try to keep your users interested by providing them with valuable content.
Your best bet is listening on the non-standard beforeunload event. This is supported by almost all browsers, expect of Opera which is known to adhere the W3C standards extremely strictly.
Kickoff example:
window.onbeforeunload = function() {
return "You're leaving the site.";
};
This message will show up in kind of a confirmation dialogue.
In your specific case you need to turn it off (just set to null) whenever a navigational link is clicked or an internal form is submitted. You can do that by listening on the click event of the desired links and the submit event of the desired forms. jQuery may be of great help here:
window.onbeforeunload = function() {
return "You're leaving the site.";
};
$(document).ready(function() {
$('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
$('form').submit(function() { window.onbeforeunload = null; });
});
You only need to give all external links the defacto standard attribute rel="ext" to denote that those are external links.
Google
This may help
You need to check onclick event before attach initLocalLinkException();
Disclaimer: It's not tested.
HTML:
internal link
html anchor
external link
blank external link
<form action="test.html" method="post" >
<button type="submit">Post Button</button>
</form>
JavaScript:
$(document).ready(function () {
initLocalLinkException();
window.onbeforeunload = function () { confirmExit() };
$('form').submit(function () {
window.onbeforeunload = null;
});
});
function initLocalLinkException() {
$('a').click(function () {
if ($(this).attr('target') != '_blank') {
var link = $(this).attr('href');
if (link.substr(0, 4) == 'http') {
var LocalDomains = new Array('http://www.yourdomain.com',
'https://yourdomain.com',
'localhost', '127.0.0.1');
var matchCount = 0;
$.each(LocalDomains, function () {
if (this == link.substr(0, this.length)) {
matchCount++;
}
});
if (matchCount == '0') {
confirmExit();
} else {
window.onbeforeunload = null;
}
} else { window.onbeforeunload = null; }
}
});
}
function confirmExit() {
alert('Are you sure?'); // Do whatever u want.
}
Take a look at this thread.
One possible way to achieve this would be to use Javascript to examine all of the a tags on your page when it loads and check if they are linking to an external site. If so, you can add an onclick event to show a confirm/alert box or something more elegant. Of course, using jQuery will greatly simplify the Javascript you'll have to write, like in the above thread.
Using the expression from this question, you can do the following:
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$.expr[':'].internal = function(obj){
return obj.hostname == location.hostname;
};
$(function() {
var unloadMessage = function() {
return "Don't leave me!";
};
$('a:internal').click(function() {
window.onbeforeunload = null;
});
$('form').submit(function() {
window.onbeforeunload = null;
});
$('a:external').click(function() {
window.onbeforeunload = unloadMessage;
});
window.onbeforeunload = unloadMessage;
});
It's possible. Just try entering a question or answer to SO and then navigating away before submitting it. It doesn't matter whether you click on a link or type in the address bar, you get an "Are you sure?" alert. You might post over on SO Meta asking how they do this.
You can do that if you design your site as a one page web app.
It means, a single page is loaded, then other contents are loaded dynamically using ajax.
In that case the onbeforeunload is triggered when the user leave the page/site.