Web Analytics Made Easy -
StatCounter Dynamically filling a DIV with <script> tag. Script doesn't execute... - CodingForum

Announcement

Collapse
No announcement yet.

Dynamically filling a DIV with <script> tag. Script doesn't execute...

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Dynamically filling a DIV with <script> tag. Script doesn't execute...

    This is a simplified example of something an AJAX script of mine will have to encounter. Basically it fills a DIV on a page with HTML retrieved from the server. Sometimes that HTML is a form with script tags in it for validation and whatnot. However, the scripts get written into the .innerHTML property just fine (and the HTML renders) but it won't execute. Example:

    Code:
    	obj = document.createElement ('div');
    	document.body.appendChild (obj);
    
    	obj.innerHTML = '<'+'script type="text/javascript">alert (\'This will not be called.\');<'+'/script>';
    I figured I'd try instead to capture the text between the script tags and call eval () on it, but...

    Code:
    html_string.match (/[<]script[^>]+>(.*)<\/script>/g)
    ...just returns 'null'.

    Any suggestions?

    Thanks,
    Aaron
    offtone.com | offtonedesign.com

  • #2
    Hrm...this actually seems like expected behaviour.

    Calling alert() in script tags would only seem to work on browser load...as the page is parsed...

    have you tried doing something like.....

    Code:
    obj = document.createElement ('div');
    	document.body.appendChild (obj);
    
    	obj.innerHTML = '<'+'script type="text/javascript">function myAlert(){ alert(\'This will may be called.\'); }<'+'/script>';
    
    	myAlert();
    If that does work, perhaps you just need to rework your logic a bit so you know whats incoming...just a thought thou.
    Active PHP/MySQL application developer available for immediate work.
    syosoft.com mavieo.com - Remote Web Site Administration Suite - Reseller Ready

    Comment


    • #3
      The AJAX bit fills a DIV with server-fetched HTML (a form, in this case). Inside the form, there's something like this:

      Code:
      <form>
      	...
      	<input type="text" onblur="doSomething ()" />
      	...
      	<script>
      		function doSomething ()
      		{
      			alert ('Blah');
      		}
      	</script>
      </form>
      The error thrown is that "doSomething ()" does not exist. It never gets defined. The JS in the <script> tags isn't parsed at all.
      offtone.com | offtonedesign.com

      Comment


      • #4
        Ok... how about

        Code:
        doSomething = new function() { alert('Hi!'); }
        And then call doSomething....has to be someway to add new functions to the document.
        Active PHP/MySQL application developer available for immediate work.
        syosoft.com mavieo.com - Remote Web Site Administration Suite - Reseller Ready

        Comment


        • #5
          You may have to use DOM to create a new script element and then create a textNode within this new script element.
          Code:
          var scripttag = document.createElement('script');
          var scriptfunction = document.createTextNode('alert(\'Hi\')');
          scripttag.appendChild(scriptfunction);
          document.getElementsByTagName('head')[0].appendChild(scripttag);
          Code:
          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
          <html xmlns="http://www.w3.org/1999/xhtml">
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
          <title>Untitled Document</title>
          <script type="text/javascript">
          function doSomething()
          {
          var scripttag = document.createElement('script');
          var scriptfunction = document.createTextNode('alert(\'Hi\')');
          scripttag.appendChild(scriptfunction);
          document.getElementsByTagName('head')[0].appendChild(scripttag);
          }
          </script>
          </head>
          
          <body>
          <form>
          <input type="button" onclick="doSomething()" />
          </form>
          </body>
          </html>
          ||||If you are getting paid to do a job, don't ask for help on it!||||

          Comment


          • #6
            Nope, not working either. That still relies on JavaScript being parsed, as something has to initiate doSomething(), no?

            I think my best bet to extract the text between the <script> tags and eval () it, but I can't seem to get it with a regular expression. I'm pretty sure the one I used should work, though...

            I'll keep at it. Worse case scenario, I hack up something with an iFrame. Ha.
            offtone.com | offtonedesign.com

            Comment


            • #7
              Pretty sure I'm SOL. My ugly little routine here works for extracting the script and running eval () on it, but the methods are still inaccessible because (I'm assuming) eval () runs the script in the context of an object? Or something?

              Code:
              // Execute any code inside the HTML
              	var isolated_script = pure_html.replace (/<[s]cript[^>]+>((\s|.)*)<\/script>/g, 'SCRIPT$1SCRIPT').match (/SCRIPT((\s|.)*)SCRIPT/g).toString ();
              	eval (isolated_script.substr (6, isolated_script.lastIndexOf ('SCRIPT') - 6));
              This is really frustrating. Why the heck wouldn't the script just execute on its own when it's thrown into the document? Ugh.

              I'm off to think up some disgusting workaround. Feel free to post any of yours. Thanks Aero and syo for the effort.
              offtone.com | offtonedesign.com

              Comment


              • #8
                Sorry to spam my own thread but figured I'd try debugging one last time...

                Found this:

                Inside the HTML that gets eval ()-ed, there is a function definition for "setKeyword ()", which is set to be called onblur="" for an input field. Blurring the field causes an error saying "setKeyword is not defined". However, if I put alert (setKeyword); right after the eval () line, it shows that setKeyword is a function. What. The. Heck.

                I'm lost.

                Edit: Even if I put alert (typeof setKeyword) after the function definition in the form's HTML (the evaled code) it says "function". However, putting onfocus="alert (typeof setKeyword);" into the input, it gives me "undefined". This feels like a JS bug or something.

                Edit again: Despite the "bug" (and I'm almost sure it is one), I've gotten around it by attaching the event handlers through script. That is, I've removed the onblur="" and replaced it with a document.getElementById ('title').onblur = function () { setKeyword (); }. Works fine now And I guess it's actually semantically better.
                Last edited by AaronW; Sep 30, 2006, 10:11 PM.
                offtone.com | offtonedesign.com

                Comment


                • #9
                  Good to hear it, that last edit was going to be my next suggestion.
                  Active PHP/MySQL application developer available for immediate work.
                  syosoft.com mavieo.com - Remote Web Site Administration Suite - Reseller Ready

                  Comment

                  Working...
                  X