簡體   English   中英

將JavaScript從文本區域注入到iframe中

[英]Inject Javascript from a textarea into an Iframe

我試圖建立像Tinkerbin這樣的Code Playground。

它基本上從不同的Textareas中提取CSS / HTML / Javascript代碼,並將其注入到iframe中。 它還應立即更新iframe。

但是,我有點堅持注入Javascript。


看,到目前為止我做了什么:

(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。

我嘗試添加

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

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

但這沒用


有人可以幫我嗎?

我認為您可能需要同時注入script標簽和內容,因為插入<script>標簽將導致瀏覽器運行腳本。 如果腳本內容稍后插入,則可能無法運行,但是我不確定。 嘗試這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM