23

I am creating a in browser HTML editor. I am using the syntax highlighter called Code Mirror which is very good.

My setup is an iframe that holds a view of the page which is being edited and a textarea which the plain text HTML sits which the user edits.

I am trying to insert the edited HTML from the textarea into the iframe which displays they rendered HTML.

Is this possible? I have tried the following:

HTML setup:

<iframe id="render">

</iframe>

<textarea id="code">
HTML WILL BE 

HERE
</textarea>
<input type="submit" id="edit_button" value="Edit" />

JQuery Setup:

$('#edit_button').click(function(){
    var code = editor.getCode(); // editor.getCode() is a codemirror function which gets the HTML from the text area
    var iframe = $('#render');
    iframe.html(code)
})

This does not seem to load the HTML into the iframe, is there a special method to insert HTML into a iframe or is this not possible?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
RailsSon
  • 19,897
  • 31
  • 82
  • 105
  • 3
    possible duplicate of [putting html inside an iframe (using javascript)](http://stackoverflow.com/questions/620881/putting-html-inside-an-iframe-using-javascript) – Vivek Kodira Jul 18 '14 at 06:28

4 Answers4

29

This problem bugged me too and finally found solution.

Its late but will add value to other visitors who might need proper fix.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>Iframe test</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(function() {
            var $frame = $('<iframe style="width:200px; height:100px;">');
            $('body').html( $frame );
            setTimeout( function() {
                var doc = $frame[0].contentWindow.document;
                var $body = $('body',doc);
                $body.html('<h1>Test</h1>');
            }, 1 );
        });
    </script>
</head>
<body>
</body>
</html>
OpenCode
  • 578
  • 1
  • 5
  • 12
14

You can do it all on one line with jquery

$("iframe").contents().find('html').html("Your new HTML");

See working demo here http://jsfiddle.net/dWpvf/972/

Replace "iframe" with "#render" for your example. I left in "iframe" so that other users can reference the answer.

Justin Levene
  • 1,630
  • 19
  • 17
3

try

iframe[0].documentElement.innerHTML = code;

Assuming that the url to the iframe is from the same domain as the webpage.

Marius
  • 57,995
  • 32
  • 132
  • 151
-4

Set the document.designMode property and then try adding the HTML.

See also: Rich-Text Editing in Mozilla

Community
  • 1
  • 1
rahul
  • 184,426
  • 49
  • 232
  • 263