Inject Javascript from a textarea into an Iframe

人盡茶涼 提交于 2019-12-11 05:26:29

问题


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'));


来源:https://stackoverflow.com/questions/11964910/inject-javascript-from-a-textarea-into-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!