[SOLVED] How do I use the onBeforeUnload event with Script#?


I’m using the Script# library with ASP.NET. I want to listen and respond to the onBeforeUnload browser event.

I am currently intercepting the event like this:

Window.AttachEvent( "onbeforeunload", OnNavigateAway );
private void OnNavigateAway()
    Script.Alert("You're leaving.");

But the second parameter to Window.AttachEvent is a DOMEventHandler, which has a return type of void. To use the onBeforeUnload event, I need to be able to return a string value, which the browser uses as the confirmation message.

Is there any way to do this without emitting a script literal or hand coding JavaScript? I would really prefer to stay in the compiled C# -> JavaScript as much as possible.

In case it matters, I’m using version 0.5.5 of the Script# library, which isn’t the latest version, but I am restricted to this for now.

UPDATE: DuckMaestro answered my question perfectly, but it still didn’t work for me. It is the correct answer to my question in that the compiled JavaScript is exactly what I was expecting and wanting. But it doesn’t have the desired effect of causing the browser to issue a warning prompt.

I do have a work-around, though, in case someone else stumbles across this answer and wants to know how I initially hacked it into working. Instead of this:

public delegate string BeforeUnloadDelegate();
Window.AttachEvent( "onbeforeunload", (DOMEventHandler) (Object) 
    new BeforeUnloadDelegate(OnNavigateAway) );

I did this:

Script.Literal( "window.onbeforeunload = this._onNavigateAway" );

This is bad form for a number of reasons. This will only work on the .debug.js class that Script# generates; Script# changes the names in the release version, so the script emitted by the Script.Literal statement won’t match up. Also, it negates a lot of the benefits of using Script# in the first place. (For example, using Visual Studio’s refactoring tools to rename OnNavigateAway to something else will leave an orphaned reference in the string.) Also, the C# code declares the method as OnNavigateAway, whereas the Script.Literal has to refer to this._onNavigateAway.

Still, if, like me, you’re on a deadline and looking for a hack, this is a place to start. If I make any more progress on a more correct version, I’ll update this question with the details.

Thanks again to DuckMaestro for answering the question I asked.


I would declare a new delegate type

public delegate string BeforeUnloadCallback();

and then change your attachEvent code to

Window.AttachEvent( "onbeforeunload", (DOMEventHandler)(Object) new BeforeUnloadCallback(OnNavigateAway) );

I’m not positive that will work on 0.5.5, but it’s the kind of trick I use from time to time in 0.6.x.

Answered By – DuckMaestro

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *