Rio
Rio

Reputation: 14882

Rerender Javascript code dynamically

I'm using a web-based tool that uses Javascript to draw pretty things, like maps. I'm making an editor for it and I've implemented a way for people to write JavaScript code and then update the rendering online (I know it's risky to have any sort of JavaScript eval thing, but forgive me for the moment).

What I've been able to do:

Using jQuery, replace the old JavaScript with the new:

<div id="renderarea">
<script type="text/javascript">
    /* Special code that actually needs to be here, not like in the head.
       Renders view with a function like render() */
</script>
</div>

After the magic I do, I get (seen with Firebug)

<div id="renderarea">
<script type="text/javascript">
    /* New code, but it doesn't run at all */
</script>
</div>

I tried running the "render()" function again but that didn't work either. I know there's some eval that has to take place, what am I missing?

Thanks once again!

Upvotes: 0

Views: 2053

Answers (3)

rob
rob

Reputation: 10119

I think you should modify your tool so that it, rather than executing a bunch of document.writes() (which your call to "render" presumably does)....it simply produces a string of html. If you want to call it "from within" a div on page load, fine...just document.write the string. But if you want to call it after the page is loaded, you need to get the div (via document.getElementById() or the like), then set its innerHTML to the string.

This way it will work in both contexts. I don't know if this is your own toolkit or what, but limiting something so that it must be executed from within the html of an element via document.write seems like it will limit its usefulness considerably.

Upvotes: 4

Zevan
Zevan

Reputation: 10235

You can do something like this I put a link on jsfiddle

take a look

Upvotes: 0

strager
strager

Reputation: 90012

Inline <script> injection does not execute the code. Use eval for that.

If you need to eval inside of an iframe, use:

iframeDomElement.contentWindow.eval(code);

Upvotes: 0

Related Questions