NetTalk Central

Author Topic: how to use javascript to prevent user leaving a page.  (Read 3982 times)

JHojka

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
    • Email
how to use javascript to prevent user leaving a page.
« on: January 11, 2012, 10:35:48 AM »
I tried to use this javascript in a NETTALK web page and can not get it to work.

<script type="text/javascript">
function closeIt()
{
  return "Any string value here forces a dialog box to \n" +
          "appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>

If I move this code to before the </head> statement then it works.

Jeff Hojka
Marathon software Co.

bruce2

  • Full Member
  • ***
  • Posts: 108
    • View Profile
    • Email
Re: how to use javascript to prevent user leaving a page.
« Reply #1 on: January 11, 2012, 12:46:25 PM »
I'm at home so I can't try this out, but I expect at the very least you'll need to put brackets after the call to closeIt().

I'd be interested in the context though where you indent to use this.

Che's
Bruce

JHojka

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
    • Email
Re: how to use javascript to prevent user leaving a page.
« Reply #2 on: January 11, 2012, 01:28:55 PM »
When a user tries to use the back button are use a bookmark I want the user to be informed that they are leaving the page.

Jeff Hojka
Marathon Software Co.

Bruce

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 11250
    • View Profile
Re: how to use javascript to prevent user leaving a page.
« Reply #3 on: January 12, 2012, 05:08:30 AM »
I didn't have a lot of joy adding your code to anywhere on a page, however I tweaked it a bit to;

<script type="text/javascript">
function closeIt()
{
  alert( "Any string value here forces a dialog box to \n appear before closing the window.");
}
window.onbeforeunload = closeIt();
</script>

If I was doing this I'd probably use the jQuery syntax, for best cross-browser compatibility;
<script>
$(window).unload( function () { alert("Bye now!"); } );
</script>

that all said, I'm really not sure you're gonna be all that happy with the effect on the app. It occurs whenever the user navigates away from the page, not just on a Back or Cancel button. So I suspect it occurs a lot more than you really want it to.

Still, try it out and let us know how it turns out.

cheers
Bruce


JHojka

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
    • Email
Re: how to use javascript to prevent user leaving a page.
« Reply #4 on: January 12, 2012, 06:49:33 AM »
Thank you for taking a look at this. I understand that this script on its own is not very useful. The function would need to be sent an option that would allow the script to return a string or NULL. This has been dropped as a requirement from the project for now.

Jeff Hojka
Marathon Software Co.