• 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

    • Basically, they can hire someone with less skill for a lower wage, for example from India, and use AI to bring that employees output up to the level of someone more experienced and expensive. It’s a broad cost-cutting strategy, and plenty of companies are already doing it. With AI involved, the employee just needs to check that the AI's results aren’t complete junk. They don’t actually have to know how to produce the work themselves. You just get one high level employee to triple check who does. The workflow looks like this: AI generates the content, a low-skilled worker filters out anything clearly broken or wrong, and a high-skilled worker gives it a final pass. Instead of hiring a full team of experts, companies can rely on a few at the top while AI and cheaper labour handle the bulk of the process.
    • Aah, always the evil terrorist group. Why not just the Russians, they're worse than any terrorist organisation.
    • LG Electronics sees profit dip but boosts shareholder returns by Paul Hill LG Electronics (LGE) has reported consolidated sales of 20.74 trillion Korean Won (approximately $15.14 billion USD) and an operating profit of 639.4 billion Korean Won (approximately $466.75 million USD) for the second quarter of 2025. The firm saw both its revenue and operating profits decline year-over-year due to external factors such as US tariff policies, ongoing geopolitical issues in the Middle East, and a slowdown in consumer spending. While the company has faced challenges, the company is aiming for what it called qualitative growth by strengthening its subscription services, direct online sales, and business-to-business (B2B) segments. Key areas of growth for LGE include automotive electronics, heating, ventilation, and air conditioning (HVAC) systems, and the webOS platform. The US tariffs are a major headache for companies around the world, given the size of the market there and President Trump's demands for bringing manufacturing to the States. To combat the rising US tariffs, LGE is trying to optimize global production and refine its market-specific approaches for premium and mass-market products. While the company’s profits dipped, it announced an interim dividend of 500 Korean Won (approximately $0.37 USD) per share for both common and preferred, with another payout later in the year that should take the total for 2025 to at least 1,000 Korean Won (approximately $0.73 USD). You must be holding the stock on August 8, 2025, to get the payout on August 22, 2025. The firm also said it will cancel 761,427 common treasury shares on July 31, 2025, making shares more scarce which could increase the value of remaining shares for investors. In terms of LGE’s various business divisions, things were mixed. Its Home Appliance Solution (HS) business achieved year-over-year sales growth, maintaining profitability, thanks to a dual strategy for premium and volume segments and growth in online sales and subscriptions. Its Media Entertainment Solution (MS) business experienced declines in sales and operating profits with the latter turning negative due to market uncertainties and stiff competition. Its Vehicle Solution (VS) business showed growth in sales and operating profit thanks to increased orders from European automotive makers. Finally, its Eco Solution (ES) business saw domestic sales increase, but overseas sales growth was limited due to US tariffs. This led to a slight year-over-year drop in operating profit due to higher costs. Image via Depositphotos.com
    • "Microsoft plans to remove the MSN feed..." Yaaay, finally the horrible dumpster fire of badly translated tabloid trash is going away! Good riddance! "...and replace it with Copilot Discover..." Oh ffs...
    • Similar to how Nvidia stopped caring about the consumer market a while ago and now just pays lip service to it because it prints money.
  • Recent Achievements

    • Week One Done
      Itbob513626 earned a badge
      Week One Done
    • One Month Later
      Itbob513626 earned a badge
      One Month Later
    • Rookie
      EdwardFranciscoVilla went up a rank
      Rookie
    • Week One Done
      MoJo624 earned a badge
      Week One Done
    • Collaborator
      aeganwn earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      620
    2. 2
      ATLien_0
      243
    3. 3
      Xenon
      160
    4. 4
      Michael Scrip
      126
    5. 5
      +FloatingFatMan
      122
  • Tell a friend

    Love Neowin? Tell a friend!