Earlz
Earlz

Reputation: 63815

Best way of catching a postback in javascript?

I am needing a piece of javascript to be run whenever a postback occurs. Well, actually multiple pieces. This is to be done inside a custom control, so the javascript code that should be run may be used a lot of times.

I currently have it so that the custom control will create a chain of "overrides" for the __onPostBack function. I feel this is pretty messy and it also does not handle regular post backs caused by Buttons.

tl;dr: What is the best way of executing a piece of javascript code when a postback happens? (that is, execute the code before the postback hits the server)

(Also, aiming for IE 7+ and Firefox compatibility)

Upvotes: 1

Views: 2002

Answers (1)

asgerhallas
asgerhallas

Reputation: 17714

You could set the onSubmit event on the form:

ClientScript.RegisterOnSubmitStatement(this.GetType(), "MyScript", "alert('Hello')");

Old and new way is described here: http://weblogs.asp.net/vga/archive/2004/03/01/NoMoreHijackingOfDoPostBackInWhidbey.aspx

Upvotes: 2

Related Questions