将内容插入iFrame

时间:2014-02-15 09:32:03

标签: javascript jquery html iframe

我正在尝试将一些内容插入“空白”iFrame中,但是没有插入任何内容。

HTML:

<iframe id="iframe"></iframe>

JS:

$("#iframe").ready(function() {
    var $doc = $("#iframe").contentWindow.document;
    var $body = $("<body>").text("Test");
    $body.insertAfter($doc);
});

我正在调用ready函数,所以我不明白它为什么不插入。

5 个答案:

答案 0 :(得分:87)

你真的不需要jQuery:

var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write('Test');
doc.close();

jsFiddle Demo

如果您绝对必须使用jQuery,则应使用contents()

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append('Test');
});

jsFiddle Demo

请不要忘记,如果您使用的是jQuery,则需要按如下方式挂钩DOMReady函数:

$(function() {  
    var $iframe = $('#iframe');
    $iframe.ready(function() {
        $iframe.contents().find("body").append('Test');
    });
});

答案 1 :(得分:4)

这应该做你想要的:

$("#iframe").ready(function() {
    var body = $("#iframe").contents().find("body");
    body.append('Test');
});

检查此JSFiddle是否有工作演示。

编辑:您当然可以采用一种线型:

$("#iframe").contents().find("body").append('Test');

答案 2 :(得分:2)

您可以输入(例如)div中的文本到iFrame:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

和divs:

setInterval(
    function(){
      if(!navigator || !navigator.network) return; //if is undefined

      if(navigator.network.connection.type == Connection.NONE){
            alert("nocon");
        }else{
            alert("yescon");
        }
    }, 1000
);

和JSFiddle演示:link

答案 3 :(得分:2)

如果您想要CSS网页上的所有IFrame那个,请试试这个:

var headClone, iFrameHead;

// Create a clone of the web-page head
headClone = $('head').clone();

// Find the head of the the iFrame we are looking for
iFrameHead = $('#iframe').contents().find('head');

// Replace 'iFrameHead with your Web page 'head'
iFrameHead.replaceWith(headClone);

// You should now have all the Web page CSS in the Iframe

祝你好运。

答案 4 :(得分:1)

等等,您真的需要使用javascript渲染它吗?

请注意,HTML5中有srcdoc,可以为您做到这一点!(缺点是IE / EDGE尚不支持https://caniuse.com/#feat=iframe-srcdoc)< / p>

请参见[[srcdoc]:https://www.w3schools.com/tags/att_iframe_srcdoc.asp

要注意的另一件事是,如果要避免内部和外部js代码的干扰,则应考虑使用sandbox 模式。< / p>

请参见[[sandbox]:https://www.w3schools.com/tags/att_iframe_sandbox.asp

相关问题