I have a button that uses
OnClientClick="document.forms[0].target = '_blank'; window.setTimeout(fixform, 500);"
to allow the OnClick event to Response.Redirect to a new window. "fixform" sets the target back to normal. This works great when everything goes according to plan. How do I stop it from opening a new window when an exception is thrown on the OnClick event? I've tried Thread.Sleep for 500ms for the form to fix itself, but it still opens the current page in a new window, with the exception.
You don't, because it doesn't execute that event until after the new window is opened. The client-side code and server-side code are executing at entirely different times on entirely different machines. The
Thread.Sleep()for example happens on the server, after the request has already been made. What's happening here is:Without knowing more about the overall structure and user experience being achieved here, it's hard to advise. What should happen in the event of an error? Can the error be more meaningfully handled so that at least something useful is presented in the new window? (That is, the exception itself shouldn't be visible in the new window, and should never be visible to a user, but rather some page which handles it.)
If you want the new window to close in the event of an error, then one possibility could be to emit some JavaScript like this to the page in the event of an error:
That way if there's no error, the window stays open. But if there is an error, the client-side code closes the window. (Since server-side code can't close the window, and indeed has no concept of a "window" in this case.)