10

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.

tahdhaze09
  • 2,220
  • 1
  • 21
  • 36
  • So you want to determine when the user navigates to a page outside of the site or closes the window? – Justin Johnson Mar 02 '10 at 19:21
  • When a user actually leaves the site. I know that on government sites, the warning is activated on a link. But if you use the address bar, then technically you know you're leaving so no warning is needed. Which is why I don't understand why they need this to begin with. – tahdhaze09 Mar 02 '10 at 19:25
  • 5
    Clients sometimes request things that they think they need, but actually don't. It happens all the time. – Justin Johnson Mar 02 '10 at 19:31
  • 5
    I'd be tempted to argue against that spec. Clients often think they should **force** their users to behave one way or another. It's usually a bad idea. If the client is concerned that users will mistakenly leave their site, better branding is indicated. If the client is trying to keep users, they need to understand that this "feature" will just piss the user off. – dnagirl Mar 02 '10 at 19:33
  • @dnagirl - I agree. But as this a government intranet site, it means the user has no choice in the matter. And unfortunately, I have no choice but to at least research this. – tahdhaze09 Mar 02 '10 at 19:57

7 Answers7

16

First off define which events can actually take your user away from your site?

  1. A click of a link inside your web site content
  2. A submit of a form to an outside action
  3. A javascript from a child window that changes window.location on its parent
  4. User starting a search in the search bar (FF and IE)
  5. User entering a search/address in the browser address bar.
  6. User hitting a back button (or backspace) when it just came to your site
  7. 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
  8. User closes the browser window

So. what can you do about all these?

  1. These are easy. Check your anchors and if they do point outside, add some functionality in the onclick event
  2. Similar to 1. Add your functionality for the onsubmit event of the form posting back outside of your site.
  3. -> 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.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • 6
    This event is indeed often abused in terms of UX. But there are **certainly** real world cases wherein this event is considered mandatory. E.g. in lengthy forms and/or extremely confidental websites (i.e. banking). – BalusC Mar 02 '10 at 19:42
  • Well it's an intranet site for government. The network folks usually control access through the firewall. I don't know why they want this, too. – tahdhaze09 Mar 02 '10 at 19:54
  • 3
    This answer almost sounds like harassment. There are PLENTY of good reasons to warn the user before they leave the page - some mentioned by @BalusC. It's nice that you answered and everything, but geez. – Dave May 26 '11 at 14:34
  • 2
    @Dave: I'm sorry you feel my answer as harassment because I surely don't know why you got this conclusion. There are reasons to implement this yes, but are they implemented? I've seen more than just one banking site and none of them uses this event. And my answer was meant more to make the OP think of other interface issues they might have. And based on his other questions I'm pretty sure he's not working on a public facing banking site. Don't be offended that easily to just simply down-vote something that gives you good pointers to re-think your business process. – Robert Koritnik May 26 '11 at 15:00
  • @Robert - I'm not offended - just pointing out the obvious. Down-vote is due to "answer not being helpful." Unlike the answers below, you listed many things completely unrelated to the question, did not include any examples, and lacked in technical advise. – Dave May 26 '11 at 16:10
  • @Dave: My answer was obviously convincing enough for OP to accept as best answer. And it's also not that uncommon that people accept answers without a usable solution but rather an advice that seems to be the best answer. I can point you to [this one](http://stackoverflow.com/q/1732348/75642) that probably sticks out the most on Stackoverflow in terms of up-votes... No solution as per question but an advice of alternative approach. Similar to what I did. – Robert Koritnik May 26 '11 at 16:17
  • @Robert - It is also not uncommon for people to disagree with an "answer" selected by an OP. The question was a straight-forward technical question "is it possible to display a dialog box when leaving a site?". You did not answer that question. Don't be offended - I'm sure you have a ton of great answers throughout this site, and I mean nothing personal by down-voting your answer. But I stand by my decision that this answer is unhelpful and off-topic. It's just a vote. – Dave May 26 '11 at 16:19
  • @Dave: Fair enough. And don't worry about me being offended. I was just trying to clarify my answer to you (since you haven't been around here for too long). But never mind. You always have the right to downvote when you disagree with some answer being helpful. – Robert Koritnik May 26 '11 at 16:57
  • 1
    @Robert - glad we can agree to disagree. :) By the way - it appears Facebook uses onbeforeunload on every page where you're editing information. – Dave May 26 '11 at 18:11
14

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.

<a href="http://google.com" rel="ext">Google</a>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • This has negative side effect of firing if the user attempts to leave by way of typing something new (or on-site) into the address bar – GhostToast Oct 30 '13 at 20:41
3

This may help

  1. You need to check onclick event before attach initLocalLinkException();
  2. Disclaimer: It's not tested.

HTML:

<a href="test.html">internal link</a>
<a href="#test">html anchor</a>
<a href="http://www.google.com">external link</a>
<a href="http://www.google.com" target="_blank">blank external link</a>
<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.
}
KyleMit
  • 30,350
  • 66
  • 462
  • 664
senerdude
  • 98
  • 1
  • 7
1

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.

Community
  • 1
  • 1
wsanville
  • 37,158
  • 8
  • 76
  • 101
1

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;
});
Community
  • 1
  • 1
Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
1

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.

Community
  • 1
  • 1
dnagirl
  • 20,196
  • 13
  • 80
  • 123
1

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.

Mic
  • 24,812
  • 9
  • 57
  • 70