Inject Javascript from a textarea into an Iframe

2019-08-14 04:02发布

问题:

I was trying to make a Code Playground like Tinkerbin.

It basicaly takes the CSS / HTML / Javascript Code out of different Textareas and injects it into an Iframe. It also should instantly update the Iframe.

However I'm a little bit stuck with injecting the Javascript.


See, what I have done thus far:

(function() {
    $('.grid').height( $(window).height() );    

    var contents = $('iframe').contents(),
        body = contents.find('body'),
        styleTag = $('<style></style>').appendTo(contents.find('head'));

    $('textarea').keyup(function() {
        var $this = $(this);
        if ( $this.attr('id') === 'html') {
            body.html( $this.val() );
        } 
        if ( $this.attr('id') === 'css') {
            styleTag.text( $this.val() );
        }
    });

})();

This does inject the CSS and HTML, but not the Javascript.

I tried adding

        scriptTag = $('<script></script>').appendTo(contents.find('head'));

and

        if ( $this.attr('id') === 'javascript') {
            scriptTag.text( $this.val() );
        }

But it didn't work


Somebody can help me out?

回答1:

I think you may need to inject the script tag and content at the same time, because inserting the <script> tag will cause the broswer to run the script. if the script content is inserted later, it may not be run, but I am not sure. try it like this:

$('<script></script>')
      .text($('theinputselectorhere').val())
      .appendTo(contents.find('head'));