• 0

[JavaScript] onbeforeunload with exception


Question

I am working on a site that places orders and mgmt wants an alert when the user attempts to leave the site so that they don't lose their order. So of course the base answer is to use the "onbeforeunload" function. This is fine, except that there are "a href" tags that call JavaScript functions on the page (no way around this) So what I'm attempting to do is to find a way around. I have a variable (mbBeforeUnload) that is set when an item has been added to the order. But other than that I have not been able to find a way around this issue.

Code:

window.onbeforeunload = checkBeforeUnload;

function checkBeforeUnload(){

if (mbBeforeUnload){

return "The order will be lost if you navigate away from this page.";

}

}

Any thoughts?

10 answers to this question

Recommended Posts

  • 0

you are defining checkBeforeUnload after calling it...

chk out this example:

<HTML>
<head>
<script>
function closeIt()
{
  return "Any string value here forces a dialog box to \n" + 
		 "appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
  <a href="http://www.microsoft.com">Click to navigate to 
	  www.microsoft.com</a>;
&lt;/body&gt;
&lt;/html&gt;

  • 0

Thanks, but that's not it at all. The function works as it should, I would like to be able to avoid triggering the call in specific cases. The "onbeforeunload" function is called for any <a> link and I have a few links that are just JavaScript calls.

The code below is simply lines taken out of context to show everyone what is being done. The variable "mbBeforeUnload" is set to true when any item is added to the order. So when the user selects a link after an item has been added the variable is true and the call is made. I have tried to temporarily reset the variable in the called function such as:

function test():{

mbBeforeUnload=false;

//do some other code

mbBeforeUnload=true;

}

But this still causes onbeforeunload to fire.

Thanks kindly nihal for the input. Any other ideas? Anyone?

  • 0

Yes I am calling a function using the "onclick"

Code:

<a href="java script:void(0)" onclick="ShowReviewSubmit();">3. Review & Submit</a>

So by this time the user has added one or more items and they want to review before accepting the order. All that does is hide and show some divs.

Thanks again for the feedback. If you're ever in the VB world and need help, feel free to ask. I've used that for 16 years, but JavaScript is new to me.

  • 0

Try this:

&lt;html&gt;
&lt;head&gt;
&lt;script&gt;
var preventPrompt = false;

function closeIt() {
  if(needsPrompt) {
	return "You sure?";
  }
  preventPrompt = false;
}
window.onbeforeunload = closeIt;
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;a href="http://www.google.com" onclick="preventPrompt=true;"&gt;A link that will be allowed regardless.&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;

We're using the onclick event to set a variable. This variable is checked in the closeIt() method to see whether we should allow the request to go through unhindered. Regardless of the outcome, we then set this variable to false again, so other browser actions will be intercepted.

  • 0

Rob,

Thanks but I'm using the onclick to run a javascript function. There is no real href.

&lt;a href="java script:void(0)" onclick="ShowReviewSubmit();"&gt;3. Review &amp; Submit&lt;/a&gt;

The first post mentions that I already use a variable "mbBeforeUnload" so that the unload only activates if the user has added items to the order. But unfortunatly the "window.onbeforeunload" function is activated on any a href, even if there is no url. (arg) I have tried resetting the variable in the called function such as:

function test():{
mbBeforeUnload=false;
//do some other code
mbBeforeUnload=true;
}

But that doesn't work. (double arg) So again, thanks kindly, but I need a diff answer.

Have a great long weekend (if you're here in the US, if not, well, ditch work/school, have some fun!)

  • 0

&lt;html&gt;
&lt;head&gt;
&lt;script&gt;
var preventPrompt = false;
var careAboutPrompting = true;

function closeIt() {
  if(!preventPrompt &amp;&amp; careAboutPrompting) {
	return "You sure?";
  }
  preventPrompt = false;
}

function specialEvent() {
  alert("Our special event has been called, without triggering the closeIt() method.");
  return false;
}

window.onbeforeunload = closeIt;
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;a href="#" onclick="preventPrompt=true;specialEvent();"&gt;Do something special.&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;

This really seems to do what you're asking unless I'm really mistaken. The careAboutPrompting variable in this example is basically akin to your mbBeforeUnload variable, set to true when you actually give a damn about the user possibly navigating away. The 'Do Something Special' link calls a JavaScript event, but the beforeunload event isn't acted upon.

Edited by Rob
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Can't get a pic of the physical server as it's in a DC, but what i'm running on it is doable. All for my own use except one VM used by a friend to run her site and other things.
    • Immediately using a VPN that makes me appear to be in the EU.
    • That’s not how it works here. Another article will be created instead.
    • Free WinX DVD Ripper Platinum license (normally $69.95) offer ends today by Steven Parker Claim your full license (valued at $69.95) for free before the offer expires on July 25th, 2025. Grab your free licensed copy of WinX DVD Ripper Platinum (for Windows) or MacX DVD Ripper Pro (for macOS) and start backing up and digitizing your DVD collection today. Whether you’ve built a DVD library over the past decades or just want to preserve a few treasured discs, WinX DVD Ripper Platinum makes it easy to convert your physical DVDs into digital files — protecting them from scratches, damage, or loss. With just a few clicks, you can watch your favorite DVD movies on your smartphone, tablet, laptop, smart TV, or store them on an external drive or NAS for easy access anytime. This exclusive giveaway is available only for TradePub users! Get a free license for WinX DVD Ripper Platinum V8.22.2 (Windows) or MacX DVD Ripper Pro V6.8.2 (macOS) — no cost, no catch. Take this opportunity to preserve your movie collection and enjoy timeless classics wherever you go this holiday season. Main Features: Convert DVD to MP4, ISO, FLV, AVI, MOV, MP3, TV, NAS, computer, game console, iPhone, iPad, Android, etc. Supports any DVDs, including homemade DVDs, newly released DVDs, old DVDs, 99-title DVDs, non-standard DVDs, regional DVDs, workout DVDs, movie/TV Series DVDs, damaged DVDs, badly structured DVDs, etc. 1:1 DVD backup. Copy entire DVDs to ISO or VIDEO_TS folders to create complete backups, preserving the menu, movies, extras, and all other content without any changes. Fast DVD Ripping: Supports hardware acceleration, multi-core CPUs, and hyper-threading technology for quick conversions. Ripping a 2-hour DVD to MP4 (H.264/HEVC) can be completed in as little as 5 minutes. High-Quality Output: Use "Yadif Double Frames" De-interlacing Engine and High Quality Engine to ensure the good quality of the output video/audio. Edit DVD: cut, merge, crop video, add subtitle, and adjust parameters. This free license offer ends today, July 25, 2025! Download WinX DVD Ripper Platinum (worth $69.95) for free Offered by Digiarty, view other free resources The below offers are also available for free in exchange for your (work) email: Exclusive Giveaway - Get WinX DVD Ripper Platinum ($69.95 Value) FREE – Expires 7/25 Alice and Bob Learn Secure Coding ($30 Value) FREE – Expires 7/30 Building Agentic AI Systems: Create intelligent, autonomous AI agents that can reason, plan, and adapt ($38.99 Value) FREE – Expires 7/30 Aiarty Video Enhancer for PC & Mac ($49.5 Value) Free – Expires 7/31 The Ultimate Linux Newbie Guide – Featured Free content Python Notes for Professionals – Featured Free content Learn Linux in 5 Days – Featured Free content Quick Reference Guide for Cybersecurity – Featured Free content We post these because we earn commission on each lead so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin The above deal not doing it for you, but still want to help? Check out the links below. Check out our partner software in the Neowin Store Buy a T-shirt at Neowin's Threadsquad Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: An account at Neowin Deals is required to participate in any deals powered by our affiliate, StackCommerce. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through the branded deals site.
  • Recent Achievements

    • Very Popular
      d4l3d earned a badge
      Very Popular
    • Dedicated
      Stephen Leibowitz earned a badge
      Dedicated
    • Dedicated
      Snake Doc earned a badge
      Dedicated
    • One Month Later
      Philsl earned a badge
      One Month Later
    • One Month Later
      armandointerior640 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      627
    2. 2
      ATLien_0
      236
    3. 3
      Xenon
      162
    4. 4
      neufuse
      123
    5. 5
      +FloatingFatMan
      122
  • Tell a friend

    Love Neowin? Tell a friend!