473,856 Members | 1,646 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using the OnBeforeUnload JavaScript Event

9,735 Recognized Expert Moderator Expert
I've seen many questions asked about how to disable the browser's back button and in the past I've replied with "it's simply not possible". It's not a good idea to disable the back button anyways, if the user ventures away from your page then they wouldn't have this button at their disposal.

The main reason people ask how to control or disable the back button is because they have a need to control sensitive (and/or) dynamic web content. For example, they may be trying to ensure that once a user is logged out hitting the browser's back button wont display any sensitive data; or maybe they are trying to make sure that the user's work is not lost when the user hit's the back button.

Please note that, at this time, the Opera web browser does not support the OnBeforeUnload event

The window.onbefore unload() Event

The JavaScript window.onbefore load() event is fired just before the web page is unloaded. This gives us the ability to make sure that the user is certain about leaving the page that they are viewing.

The unique thing about this event is that if function that handles it returns anything ("true","false" ,"null"...a string...anythi ng) a confirm prompt window will be displayed by the browser stating:

Are you sure you want to navigate away from this page?
Press Ok to continue or Cancel to remain on the current page.
So, for example, if you wanted to just display a confirm box asking the user if they really want to leave your page you would add:
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.      window.onbeforeunload = function(){ return;}
  3. </script>
If you return a string from the function handling the onbeforeload event, then it will be inserted into the prompt as such:
Are you sure you want to navigate away from this page?
Your Returned String Goes Here
Press Ok to continue or Cancel to remain on the current page.
In this case you would have the javascript:
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.      window.onbeforeunload = function(){ return 'Your Returned String Goes Here';}
  3. </script>
If the user clicks the Cancel button, the unload event is not executed and they remain on the page, otherwise they are permitted to leave and their cache is cleared.

To prevent the confirm box from appearing simply do not add a "return" to your function.
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.      window.onbeforeunload = function(){}
  3. </script>
Please remember that the window.onbefore unload event is fired every time the page is about to unload. This means that if the user clicks a button on your page, and your page posts back to the server, the window.onbefore unload event will fire. Please take this into consideration when developing the function that handles the window.onbefore unload event.


The window.onbefore unload event is a great way to ensure that the user is certain about the consequences of leaving your web page.

An important thing to remember is that if the JavaScript function handling the onbeforeunload event returns anything at all a confirm box is displayed automatically no matter what is returned. To prevent the confirm box from appearing simply do not add a "return" to your function.

Also, another important thing to note is that the onbeforeunload event is fired every time the page is about to unload.

In the JavaScript function that handles this event you can do anything you want to. For instance, if they navigate away, you could put in an Ajax call to indicate to the server that the user should be logged out...or that resources should be cleaned up....or record anything you'd like really.

Please note that, at this time, the Opera web browser does not support the OnBeforeUnload event

I hope this little article was helpful to you. Happy Coding!

Mar 17 '08 #1
1 108806
Well, it seems like this doesn't work as posted :(
Nov 7 '10 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Dan | last post by:
In response to... DSAsteve@aol.com 6/20/2003 post wc_fl@NOSPAM.hotmail.com 3/26/2003 post ....The javascript event calendar found at http://www.scriptcalendar.com satsifies both your needs for an event calendar. For SAsteve@aol.com, it's the newest version of the calendar once found http://www.geocities.com/dshipe.
by: ritskits | last post by:
I have the dropdownlist that is populated when the form is loaded. I have the button that opens search child window using the modalwindowdialog and it returns the value that I want to add to the dropdownlist on the parent window using the javascript as there will not be any event fired when the childwindow is closed. function GetMeds() { var MedsString = window.showModalDialog("SearchColor.aspx", window, "dialogHeight: 700px;...
by: Sjaakie Helderhorst | last post by:
Hello, I need to add a Javascript event (onClick) to a servercontrol (asp:checkbox). Checkbox is named 'cbDoMail'. Assumed that 'cbDoMail.Attributes.Add("onClick", "doJavascriptThing()") would do the job, unfortunately it didn't. Can anyone point me in the right direction? Thanks!
by: Neven Klofutar | last post by:
Hi, How can I acomplish following: I want to create a file on server using onClick server event, and then I want to open that file in new window using Javascript window.open(). How can I do it ? Thanx, Neven
by: Nathan Sokalski | last post by:
I add a JavaScript event handler to some of my Webcontrols using the Attributes.Add() method as follows: Dim jscode as String = "return (event.keyCode>=65&&event.keyCode<=90);" TextBox2.Attributes.Add("onKeyPress", jscode) You will notice that jscode contains the JavaScript Logical And operator (&&). However, ASP.NET renders this as &amp;&amp; in the code that is
by: sshan | last post by:
I need to invoke javascript event onKeyDown, which should get invoked when we press any key from anywhere of the page. currently I am callin like this: <head> <script type="text/javascript"> //document.onKeyDown=isBack(event); function isBack(event) { alert('hit a key'); }
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.