2

Consider the following js code (to click an asp.net Button on load):

function doSomething()
{
    document.getElementById("<%= theButton.ClientID %>").click();
}
window.onload = doSomething;

When the page is loaded - the codebehind of the button is executed, and the page is loaded again (with new information). This should have introduced a bug of an infinite loop, but it doesn't. It is only called once, and ignored in the postback.

Why?

ispiro
  • 26,556
  • 38
  • 136
  • 291
  • how does the page reloads ?? what do you mean by this – Ekansh Rastogi Nov 06 '14 at 13:02
  • Why don't you use the `_doPostBack()` method from Javascript? – LcSalazar Nov 06 '14 at 13:08
  • @EkanshRastogi It's an asp.net thing - when codebehind is executed - the page gets a [postback](http://en.wikipedia.org/wiki/Postback). – ispiro Nov 06 '14 at 13:08
  • Does the page postback when you click the button manually? – Ian Nov 06 '14 at 13:09
  • @Ian Yes, if I remove the js, and click the button - there's a postback. – ispiro Nov 06 '14 at 13:12
  • @LcSalazar Looks interesting. I need to look into that. – ispiro Nov 06 '14 at 13:15
  • @ispiro Have you considered using `document.onload`? Of course the browser's window will only be loaded once – Matias Cicero Nov 06 '14 at 13:22
  • @MatiCicero [It doesn't look like that would make a difference](http://stackoverflow.com/questions/588040/window-onload-vs-document-onload). But anyway - I want to know if I can rely on this not creating an infinite loop, or whether I need to somehow confirm it isn't a postback before firing. – ispiro Nov 06 '14 at 13:56
  • 1
    @ispiro if you need to confirm it isn't a postback before clicking the button, why not just use `!Page.IsPostBack` to determine whether to execute that code? – David Sherret Nov 06 '14 at 14:46
  • Is it possible that your browser somehow prevents the infinite loop? – Stilgar Nov 06 '14 at 15:45

1 Answers1

0

Assuming you want the doSomething method to be called only the first time the page loads:

You should add your call to doSomething to the page using Page.RegisterStartupScript in the code behind, but wrap it in an if statement that checks if it is a postback. That way, your method will only be called the first time the page loads:

 if(!Page.IsPostBack)
 {
    Page.ClientScript.RegisterStartupScript(GetType(), "buttonClickScript" "window.onload = doSomething;", true);
 }
Keith
  • 718
  • 8
  • 12
  • 1
    He asks why there is no infinite loop not how to fix it. – Stilgar Nov 06 '14 at 15:44
  • I was basing this on the OPs comment: "I want to know if I can rely on this not creating an infinite loop". Doing it this way, you don't need to rely on it not creating an infinite loop. I would imagine the behaviour described is because the OPs script is executed before the asp.net generated _postback script is loaded and attached to the button. I wouldnt rely on it, I would control the page flow form the server side code. – Keith Nov 06 '14 at 15:57