0

Disclaimer - I should note that my JavaScript is pretty weak.

I'm in the process of inserting code into my website so it can cover a scenario when a user exits his browser, he gets prompted with a proverbial 'Are you sure you want to quit?' sort of confirmation messsage.

I'm in the process of trying to implement this piece of JavaScript on my website:

   <script language="JavaScript" type0"text/javascript">

var foo = true;

window.onbeforeunload = askBeforeExiting;

function askBeforeExiting() {
  if (foo)
    return "Are you sure you want to leave this page?";
}
</script>

The code not only throws a confirmation message when attempts to exit a browser are made. However, it also throws the confirmation when a link to another portion of the site is clicked and other related events.

Is there a way to modify this code to just capture the browser closing scenarios only? I get that scenario like killing the browser from the Task Manager or from a powershell command can't be captured. I just want the scenarios in the current user session where they may exit the browser.

I've been looking over various samples across the web and through code references and can't seem to track down exactly what I want to do. Is this even possible?

4

1 回答 1

2

I've done this before where a page has a form, and I only want to ask the user for confirmation when a change has been made to the form. You could do something similar, where you attach a click event to all links, for example, that would set foo to false. Something like:

var links = document.getElementsByTagName('a');
for(var i = 0, l = links.length; i < l; i++) {
    links[i].onclick = function () {
        foo = false;
    }
}

Edit: There are many other actions you might have to account for, depending upon your site, however with the information given, this should be a good start for you as there is no direct way to accomplish what you are after.

于 2013-05-14T18:21:41.907 回答