Status

Location
Arlington, VA
Subscribe to GeoRSS Subscribe to KML


Does your browser evaluate the Javascript of innerHTML?

Published in Javascript, Programming, Web  |  4 Comments


While playing with some really slick asynchronous javascript stuff (no - not Ajax, there wasn’t any XML involved), I ran into an odd behavior that varied between the several browsers.

What I’m doing is passing back a table from an asynchronous call and placing it into a premade table elementId. The page supports interaction with either javascript, if enabled, or straight href links if javascript is not enabled.

The problem occurs when my Async call returns a table with a <script> tag containing document.write() calls.

Replace innerHTML with innerText and Safari renders the entire script source, Firefox & Camino ignore it.

Hrm - so how to dynamically fill in script into the DOM of a page and have it executed?

The DOM inspector in Firefox correctly shows the Javascript being part of the element, but since the parser has already gone through that element, evaluated the Javascript later in the page, then it doesn’t seem to be re-executed.
Update

It seems as though there is promise in the eval function of Javascript. However, nothing seems apparent yet.

Similar Posts


Responses

  1. ZildjianB says:

    November 7th, 2005 at 9:09 am (#)

    I’ve been wondering the samething…. ever come across the answer?

  2. christian says:

    December 9th, 2005 at 6:23 am (#)

    i have the same problem. it is very annoying and i don’t know how i should code a workaround. do you got the answer????
    please mail me back.
    THANKS

  3. Maulin Shah says:

    February 27th, 2006 at 12:22 am (#)

    say dynamicText is the text that is returned… peering into the prototype.js library, i figured out you can do:

    scriptFragment = ‘(?:)((\n|.)*?)(?:)’;
    match = new RegExp(scriptFragment, ‘im’);
    var matches = dynamicText.match(match);
    for(i=1; i

  4. Maulin Shah says:

    February 27th, 2006 at 12:27 am (#)

    woops, i mean:


    scriptFragment = '(?:)((\n|.)*?)(?:)';
    match = new RegExp(scriptFragment, 'im');
    //this will evaluate the first script in the returned text.
    // more than that won't work!
    var matches = dynamicText.match(match);
    if (matches.length >= 2)
    eval(matches[1]);

Leave a Response