2016-09-08 7 views
0

jqueryで要素を探すiframe内にスクリプトがありますが、iframe内の要素ではなくiframeの外側にある要素のみを検索します。スクリプトを隔離してiframeに隔離することはできません

スクリプトをiframe内でのみ実行するようにしてください。

私はここに例があります:my example

私の例を示し絵: enter image description here

を私のリンクの例ではshownedとして、私は、IFRAMEを作成する方法:

//Head to iframe: 
var head = '<meta charset="utf-8">' + 
    '<meta http-equiv="X-UA-Compatible" content="IE=edge">' + 
    '<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">' + 
    '<script src="http://code.jquery.com/jquery-1.10.2.js"><\/script>'; 

//Body to iframe that contains a script that I would like only to run inside the iframe: 
var body = '<code id="codeInside">code tag inside</code>' + 
    '<script>var codeTag = $("code").text("TAG FOUND!!");<\/script>'; 

//Insert the iframe: 
var iframe = $('<iframe src="javascript:\'\'">').appendTo($('body')); 
iframe.contents().find('head').html(head); //Append head til the iframe 
iframe.contents().find('body').html(body); //Append body to the iframe 
+0

はない別のサイトへのリンクとして、ここではあなたのコードを投稿してください。 – Barmar

+0

待って、何?あなたはJavaScriptを実行するjavascriptを追加するためにjavascriptを使用しています、なぜですか? – madalinivascu

答えて

0

私はそれを得た:a working solution

//Head to iframe: 
    var head = '<head><meta charset="utf-8">' + 
     '<meta http-equiv="X-UA-Compatible" content="IE=edge">' + 
     '<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">' + 
     '<script src="http://code.jquery.com/jquery-1.10.2.js"><\/script></head>'; 

    //Body to iframe that contains a script that I would like only to run inside the iframe: 
    var body = '<body><code id="codeInside">code tag inside</code>' + 
     '<script>var codeTag = $("code").text("TAG FOUND!!"); console.log("codeTag", codeTag);<\/script></body>'; 

    //Insert the iframe: 
    var iframe = $('<iframe src="javascript:\'\'">').appendTo($('body')); 

    var doc = iframe[0].contentWindow.document; 
    doc.open(); 
    doc.write(head); 
    doc.write(body); 
    doc.close(); 
0

はあなたを持っています通常のやり方で試してみた

var codeTag = iframe.contents().find("code").text("TAG FOUND!!"); console.log("codeTag", codeTag); 
+0

残念ながら、私の場合はそれが動作しません。私は説明されたセットアップを使用する必要があります。なぜなら、ユーザがいくつかのhtmlとjavascriptを記述し、挿入されたiframeに結果を表示する動的な方法を作っているからです.jsfiddle.netのようなものです。だから、ユーザーは、通常のJavaScriptを書くことができ、それがiframeでエクセキュートされるとは考えていないはずです。 –

+0

これは良いチュートリアルのようですhttp://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/ – madalinivascu

+0

もう1つの質問が役立ちますhttp://stackoverflow.com/questions/13247798/how-can-i外部サイトの-ifrevent-javascript-in-iframe-to-access-properties – madalinivascu

関連する問題