Click here to Skip to main content
15,880,854 members
Articles / Web Development / ASP.NET

Save Changes on Close of Browser or When Exiting the Page

Rate me:
Please Sign up or sign in to vote.
4.36/5 (23 votes)
24 Sep 2007CPOL4 min read 265.6K   5.2K   115  
This article will show how to save changes on the close of the browser or when exiting a page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
   <link href="styles.css" rel="Stylesheet" type="text/css" />
</head>
<body topmargin="0" leftmargin="0">
    <table style="width: 100%">
        <tr>
            <td>
                <table style="width: 100%">
                    <tr>
                        <td bgcolor="#3333cc" class="special">
                            <h3>
                            Save Functionality upon the actions that navigate to pages within the site or to
                            other site?
                            </h3>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            The difference between the previously sent save functionality and the current POC is
                            <br />
                            <ul>
                                <li>Exception Handling (For the case if an error occurs while saving)</li>
                                <li>Including save on the events when the user navigates through the address bar or
                                    the favorites button.</li>
                            </ul>
                            <p>
                                <span style="text-decoration: underline">Note</span>: Since the events for the address
                                bar and the favorites button cannot be identified that is why this implementation
                                was done.</p>
                            <p>
                            Navigation in a site can happen in two ways. Following are the list of actions by
                            which users can navigate.</p>
                            <ul>
                                <li>Navigating to pages using controls provided within the site.</li>
                                <li>Navigating to pages using Browser Controls, shortcut keys or the right click options.
                            </li>
                            </ul>
                            <p>
                                Following are the ways through which the user can navigate away from the page. All
                                these are covered in this solution.</p>
                            <p>
                            </p>
                                <ul>
                                    <li>Back button on the Browser Toolbar</li>
                                    <li>Refresh button on the Browser Toolbar</li>
                                    <li>Close button on the Browser Toolbar</li>
                                    <li>Home button on the Browser Toolbar</li>
                                    <li>ALT + F4 to close the browser</li>
                                    <li>CTRL + F4 (for tabbed browsers)</li>
                                    <li>F5 or CTRL + R or Right click for refresh</li>
                                    <li>ALT + Home button (to navigate to client's Home page)</li>
                                    <li>Click backspace (alternative for Back button)</li>
                                    <li>Typing a URL and navigating to a different page</li>
                                    <li>Selecting a URL from the favorites button </li>
                                    <li>Right Click and select Refresh</li>
                                </ul>
                            <p>
                                Identifying the different actions and enabling save for each action is a tedious
                                process. The save functionality can be implemented in a simpler way using the javascript
                                event <strong><em>onbeforeunload.</em></strong>&nbsp;</p>
                            <p>
                                <span style="text-decoration: underline"></span>
                            </p>
                            <p>
                                <span style="text-decoration: underline">Reason to use onbeforeunload:<br />
                                    <br />
                                </span>The onbeforeunload event (which is called before unload event) is called when
                            </p>
                                <ul>
                                    <li>Navigating to another page (as mentioned above)</li>
                                    <li>Postback due to a control event</li>
                                    <li>Using controls on the Browser</li>
                                    <li>Closing the page.</li>
                                </ul>
                            Thus onbeforeunload is the appropriate event at which the save functionality can
                            be implemented. 
                            <br />
                            <br />
                            The save functionality is implemented in the following manner.<pre class="javascript">&lt;body onbeforeunload="HandleOnClose(event)" onkeydown="setKeyValue(event)"&gt; 
&lt;script&gt;
var keyPressed = ""; //Variable to store which key was pressed 
var dataChanged = false; <br />var currentElement = ""; 

//Function called when the browser is closed. 
function HandleOnClose(evt) { <br />&nbsp; if (currentElement == "" ||(!(currentElement.getAttribute("tag")=="DonotCallSaveonLoad"))){ <br />&nbsp; &nbsp; &nbsp; var objconfirm = confirm("Would you like to save changes made?") <br />&nbsp; &nbsp; &nbsp; if (objconfirm == true) { <br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FunctiontoCallSaveData(); <br />&nbsp; &nbsp; &nbsp; } <br />&nbsp; &nbsp;} <br />}  
&lt;/script&gt;</pre>
                            This handler works as follows:<br />
                            <br />
                            The onbeforeUnload event calls the HandleOnClose function which checks if the variable
                            <em>currentElement</em> has a value or not. The <em>currentElement </em>is set on
                            the onclick event of all the controls through which one can navigate within the
                            site or when a postback on the page happens.<br />
                            <br />
                            The <em>event.srcElement</em>
                            will set the object of the control to the
                            variable <em>currentElement</em> which initiated the postback. This is implemented
                            as follows&nbsp;<br />
                            <br />
                            <pre class="VB">LinkButton1.Attributes.Add("onClick", "currentElement = event.srcElement;") <br />Button1.Attributes.Add("onClick", "currentElement = event.srcElement;") <br />ImageButton1.Attributes.Add("onClick", "currentElement = event.srcElement;") <br />DropDownList2.Attributes.Add("onClick", "currentElement = event.srcElement;")</pre>
                            <span><span style="text-decoration: underline">Note</span>:
                            </span><em>onClick </em>
                            event is the only point where the Control object can be retrieved because the object
                            of the control is destroyed when the process reaches the <em>onbeforeUnload
                            </em>event.<br />
                            <br />
                            To differentiate between a user initiated event and a control initiated event an
                            attribute is being added named <em>tag </em>with a value "DonotCallSaveonLoad"
                            to all the known controls in the application using which the save method should
                            be called without prompting the user to save the page. 
                            <br />
                            <br />
                            <pre class="VB">LinkButton1.Attributes.Add("tag", "DonotCallSaveonLoad") <br />Button1.Attributes.Add("tag", "DonotCallSaveonLoad") <br />ImageButton1.Attributes.Add("tag", "DonotCallSaveonLoad") <br />DropDownList2.Attributes.Add("tag", "DonotCallSaveonLoad") </pre>
                            The attribute is added to the control at runtime as below:<pre class="javascript">&lt;a onclick="currentElement = event.srcElement;" id="LinkButton1" <br />&nbsp;tag="DonotCallSaveonLoad" href="javascript:__doPostBack('LinkButton1','')"&gt;Click Me&lt;/a&gt;</pre>
                            So the javascript function HandleOnClose checks for this attribute <em>tag of the currentElement
                                object.<br />
                            </em>If the currentElement is null or the attribute tag of the currentElement is
                            not DonotCallSaveonLoad then it calls the function FunctiontoCallSaveData, otherwise
                            the save functionality on the code behind is called.
                            <br />
                            <br />
                            The implementation of the function FunctiontoCallSaveData() is the same as previously
                            sent which is as follows.<br />
                            <br />
                            <pre class="javascript">
function FunctiontoCallSaveData() { <br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; document.getElementById("<%=hdtoSaveData.ClientID %>").value="PageClosed"; <br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; document.form1.submit(); <br />}</pre>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Spozzle
India India
A highly experienced and influential Technical Manager / Team Leader and Architect, an inspirational leader who has effectively managed, developed and motivated internal and external teams. Strong ability to quickly understand and analyze business strategies ensuring technology solutions meet business requirement, to quickly adapt to all new technologies and challenges.

My attention to detail, high technical aptitude and hands on approach together with a high degree of motivation and professionalism would make me an asset to any progressive organization or demanding position within IT industry.

What do I do?

I work at Spozzle(www.spozzle.me) as a Software Architect and currently working on the following technologies.

Web Technologies using

Java
PHP
XCode 4 and IPhone Development
HTML 5 and CSS
Android Development

My Experience

I have spent my last 7 years working on .NET Technology building application both on the Web and Windows.

I provide Technical consultations to people on

- .NET Development, Best Practices and Issues
- Best Practices on Web based Architecture and Hosting applications on Cloud.

I have not moved on to PHP, Java and Mobile Development. I now work at Spozzle developing really cool application for the Sports Fanatics on Facebook. Checkout http://apps.facebook.com/spozzle

Comments and Discussions