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...