views:

427

answers:

1

I have a Rich Text Editor in Javascript in which I want to be able to enter an embedded widget in a Javascript tag. I.e:

<script src="http://www.mydomain.com/script.aspx?id=123" type="text/javascript"></script>

Still using JS I move the html-content from the iframe into a DIV in the page:

<script>
    function copyRtfToDiv()
    {
        myiframe = document.getElementById('myiframe');
        postDiv = document.getElementById('blogPostDiv');
        content = myiframe.contentWindow.document.body.innerHTML;
        postDiv.innerHTML = content;
    }
</script>

When the content is copied into the DIV the script is not invoked. Is there a way to make this script run?

A: 

First off, you seem to be copying JavaScript code into a DIV tags. That shouldn't really work, since it'll just treat it like regular text. To illustrate, compare these two blocks of code. The first, is a DIV:

<div>alert('hello!');</div>

And it'll look on the page, like this:

alert('hello!');

The second block of code, is a script:

<script>alert('hello!');</script>

Which will open a message box with the text "hello!", and await a user-click on "OK". But other than that, won't display anything in the page.

You're aiming for the 2nd option - one that actually runs the JavaScript code that resides between the tags.

I'd recommend wrapping the script you want to invoke in a function, and invoking that function by name. So let's say you have within the IFRAME an HTML document whose body looks something like this:

<div id='jscode'>
   function mycode() {
       // This is some code!
       alert('Hello there!'); 
   }
</div>

You could then, in the IFRAME's parent document (the one containing the <iframe> tag), to use the following code in the parent to import it into the parent's DOM:

function copyRtfToDiv()
{
    myiframe = document.getElementById('myiframe');
    content = myiframe.contentWindow.document.GetElementById('jscode').innerHTML;
    newscripttag = document.createElement('script');
    newscripttag.innerHTML = content;
    mycode();
}

I have no clue why you would want to do something like this - which is basically re-parenting JavaScript code to live within you document's DOM; There are better ways to do this, not least of which is using a different editor that can be simply called externally. For example, tinyMCE and FCKEditor.

Good luck!

scraimer