How do I call javascript just before a response redirect

17,297

Solution 1

Your problem is that the Response.Redirect redirects the response (...) before anything is sent back to the client. So what the client gets is a response from Google rather than from your server.

In order to write some javascript on the page and have it execute before sending the client to Google, you'll need to do your redirect in javascript after the alert.

   Dim strscript As String = "<script>alert('hello');window.location.href='http://www.google.com'</script>"

   If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
       ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
   End If

Solution 2

The client isn't getting a chance to load. Try redirecting from the client side:

Dim strscript As String = "<script>alert('hello');window.location.href("http://www.google.com");</script>"

If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
   ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If

Solution 3

If you want to execute some javascript before redirecting, you will need to do the redirect in javascript and not in ASP.NET.

Dim strscript As String = "<script>alert('hello'); window.location.href='http://www.google.com';</script>"

If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
    ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If

Solution 4

Not Working:

string sScript = "<script language='javascript'>alert(\"" + Alertstr + "\");  alert('Record has been Updated Successfully'); </script>";
ClientScript.RegisterStartupScript(typeof(Page), "alert", sScript);
response.redirect("LandingPage.aspx");

Working:

string sScript = "<script language='javascript'>alert(\"" + Alertstr + "\");  alert('Record has been Updated Successfully'); window.location.href = 'LandingPage.aspx'; </script>";
ClientScript.RegisterStartupScript(typeof(Page), "alert", sScript);
Share:
17,297
TonyNeallon
Author by

TonyNeallon

Updated on June 04, 2022

Comments

  • TonyNeallon
    TonyNeallon almost 2 years

    I'm trying to run some java script just before a page redirect but it fails to run. When I comment out the Response.Redirect all works fine but this goes against the particular requirements. Any ideas on how to implement this functionality?

            Dim strscript As String = "<script>alert('hello');</script>"
    
            If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
                ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
            End If
    
            Response.Redirect("http://www.google.com")