Jump to content

Problem with self-modifying Javascript code

- - - - -

  • Please log in to reply
1 reply to this topic

#1
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
I've created a Javascript script that modifies its own code:



<html> 

<head> 

<title>paowhpn</title> 

 

<script id="js" type="text/javascript"> 

function modify(){

	document.getElementById('js').innerHTML += "function fun(){ alert( 'hello' ); }";

	document.getElementById('r').innerHTML = "<input type='button' value='Press' onclick='fun();' />"

}

</script> 

 

</head> 

<body> 

<form> 

<input type="button" value="Modify" onclick="modify();" /> 

<br /> 

<span id="r"> 

<input type="button" value="Press" /> 

</span> 

<div id="u"></div> 

</form> 

</body> 

</html> 


I know the self-modification part works because when I went to "inspect element" in Chrome, it showed that the HTML and Javascript code had indeed been modified. The problem is that it doesn't seem to do anything. The event handler doesn't work, and when I click on the press button, the function fun() doesn't execute.

Is there some technical detail I'm missing here?
Programming is a journey, not a destination.

#2
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
I have figured out what the problem is. Since the Javascript code is in the head of the document, it executes when the page loads, including the function declarations, meaning I can modify the code to declare more functions and variables, but the declarations will not execute. I have resolved to fix this problem by putting the Javascript code to be modified in a bookmarklet in an event handler, so it executes whenever the event handler is called.
Programming is a journey, not a destination.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users