将texta中的Javascript注入Iframe [英] Inject Javascript from a textarea into an Iframe

查看:120
本文介绍了将texta中的Javascript注入Iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个像 Tinkerbin 的代码游乐场。

I was trying to make a Code Playground like Tinkerbin.

它基本上从不同的Textareas中取出CSS / HTML / Javascript代码并将其注入到iframe中。它也应该立即更新Iframe。

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.

但是我注意到注入了Javascript。

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() );
        }
    });

})();

这会注入CSS和HTML,但不会注入Javascript。

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

我尝试添加

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

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

但它不起作用

有人可以帮帮我吗?

Somebody can help me out?

推荐答案

我认为您可能需要同时注入脚本标记和内容,因为插入< script> 标记将导致broswer运行脚本。如果稍后插入脚本内容,则可能无法运行,但我不确定。试试这样:

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

这篇关于将texta中的Javascript注入Iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆