views:

23

answers:

2

My master web page contain JS code to override standard alerts with custom jQuery dialog boxes.

<script type="text/javascript" language="javascript">
        window.alert=function(alertMessage)
        {
          $.msgbox(alertMessage, {type: "info"});  
         }             
</script>

In default.aspx web page onLoad method I am trying to register and display alert script

 Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InvalidPassword",
                "alert(\"Your login attempt was not successful. Please try again.\");",
                true);

Unfortunately it does not work. If I remove JS code which override alert box everything works fine, alert box appears. The override JS is correct, it is working fine if I execute alert js in client side, but it does not work if I try to execute code from server side.

Could anyone explain where is the problem?

+1  A: 

I get the same problem when I try to run it from the page_load event of the aspx page, but when I run it from the body onload event it works. I think this is happening because the page_load event occurs before your window.alert override has a chance to be run.

Try this in the body tag:

<body onload="alert('Your login attempt was not successful. Please try again.');">  

And the jQuery:

$(function () {

        window.alert = function (message) {
            $('#dialog').text(message).dialog();
        }

 });

I used the jQuery UI dialog plugin by the way.

ryanulit
A: 

Ok, I found where is the problem. If code registered with RegisterClientScriptBlock refer to another JS code then we need to load web page in full. It seems that JS registered in RegisterClientScriptBlock executed immediate when it is loaded in browser no matter if web page loaded in full or not. So we need to execute code after web page loaded fully. We can use jQuery event below to find it

  $(document).ready(function() {



  });

The full code will look like

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InvalidPassword",
                    "$(document).ready(function() {alert(\"Your login attempt was not successful. Please try again.\");})",
                    true);
Tomas
@Tomas: Good solution but that behavior is not specific to RegisterClientBlockScript -- javascript is always executed as soon as the browser sees it, in fact all browsers block all further rendering and resource requesting while processing a <script>
Scott Stafford