473,738 Members | 5,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using the OnBeforeUnload JavaScript Event

Frinavale
9,735 Recognized Expert Moderator Expert
Introduction
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>
  4.  
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.
Eg.
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.      window.onbeforeunload = function(){}
  3. </script>
  4.  
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.

Conclusion

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!

-Frinny
Mar 17 '08 #1
1 108759
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

1
1974
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.
1
2401
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;...
19
2483
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!
3
1539
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
8
2815
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
1
2226
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'); }
0
8969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8788
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,...
0
9476
Oralloy
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...
0
9335
jinu1996
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...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6053
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();...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
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
3
2193
bsmnconsultancy
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.