Geeks With Blogs
Sean's Blog My Development Blog
If you've ever attempted to programmatically add a DOM event to the <body> tag in your ASP.NET application, you have probably noticed that there isn't an easy way to do so.  The problem is that there is no way to get a reference to the body tag in the code behind.  A simple solution might be to add the ID and runat="server" attributes to the body tag.  This would be a nice little trick to get a reference to the <body> tag in the code behind of the current page, but what if, for example, a control you were writing required some client-side garbage collection when the user leaves the page?  The DOM onunload event would be a nice place to start, but this attribute is applied to the <body> tag.  Forcing anybody that uses your control to add the appropriate attributes to their body tag is asking a bit much, not to mention error prone.  A control should provide the implementation for everything that is required for it to operate so that the client need not worry about the details.

We obviously have the tools necessary register a startup script; however, there isn't anything available that will register a script that is run when the user leaves the page.  Or is there?  After a little bit of brainstorming, I came up with a simple solution that I think solves the problem.  The solution: Use JavaScript to programmatically wire up the DOM onunload event!

Page.ClientScript.RegisterStartupScript(typeof(MyControl), "Unload.js", "<script type=\"text/javascript\">window.onunload = function () { alert('Dont leave me!!!'); };</script>", false);

In short, this code snippet registers a startup script that configures the DOM onunload event.  When the browser loads the page, the JavaScript is executed, thereby registering the appropriate onunload event, which is run when the user leaves the page.

This code could easily be modified to be more friendly towards any other onunload events that might already be wired up; or, to add any other attribute to the <body> tag by using JavaScript.

Hope this helps... Posted on Wednesday, November 7, 2007 12:48 PM | Back to top

Comments on this post: Programmatically Wiring Up the DOM onunload Event in ASP.NET

# re: Programmatically Wiring Up the DOM onunload Event in ASP.NET
Requesting Gravatar...
please give the simple example which is helpful for the
new programmer.
Left by nilesh on Oct 29, 2010 6:29 AM

# re: Programmatically Wiring Up the DOM onunload Event in ASP.NET
Requesting Gravatar...
I'm not sure if I'm following you correctly. You could simply paste the above code in the page load event of a control and it should work for you. Could you please specify a little more what you're trying to do just to make sure we're on the same path?
Left by Sean on Oct 29, 2010 5:37 PM

Your comment:
 (will show your gravatar)

Copyright © Sean Fao | Powered by: