获取动态更改的iframe内容

时间:2018-10-14 22:43:59

标签: javascript jquery iframe

动态更改iframe内容后,如何获取更新的内容?

    var target = document.getElementById('page_demo').contentWindow.document.body.innerHTML;

会给我一个副本,但它不反映我对此所做的任何更新。它将在进行任何更改之前返回内容!

编辑:

进一步说明我要做什么。我正在使用grapejs创建html页面。我想给它添加简码,以动态生成页面链接并将其插入。在grapejs中,简码由图标表示。一切正常,除了第二个更改将覆盖第一个更改。因此,我需要弄清楚如何进行两个(或所有,如果添加任何其他)更改!

$('#page_demo').contents().find("body").html( css + page_data );
$('#page_demo').contents().find("body").css( page_css );

//there are 2 shortcode items pre inserted in to a grapesjs editor
//<div id="insert_navbar"><span title="Navbar" id="iavph" class="fa fa-navicon text-white"></span></div>
//<div id="insert_sidenav"><span title="Sidebar Navigation" class="fa fa-navicon"></span></div>

// check if we need to insert a navbar at shortcode location!
if( document.getElementById( "page_demo" ).contentWindow.document.getElementById( "insert_navbar" ) ){
    var e = document.getElementById( "page_demo" ).contentWindow.document.getElementById( "insert_navbar" );
    // extract class part!!!
    var parts = e.innerHTML.split('class="');
    var thePart = parts[1];
    var nextparts = thePart.split('"');
    var the_class = nextparts[0];
    //remove place holder icon
    var final_class = the_class.replace('fa fa-navicon', '').trim();

    //generate navbar link items!
    $.post( "quicknav.php", { content_changed : 1, final_class : final_class }, function( data ){ 
        // update display
        e.innerHTML = data;
        //the navbar links have been inserted!
    });
}

// check if we need to insert a sidebar menu at shortcode location!
if( document.getElementById( "page_demo" ).contentWindow.document.getElementById( "insert_sidenav" ) ){
    var e = document.getElementById( "page_demo" ).contentWindow.document.getElementById( "insert_sidenav" );
    // extract class part!!!
    var parts = e.innerHTML.split('class="');
    var thePart = parts[1];
    var nextparts = thePart.split('"');
    var the_class = nextparts[0];
    //remove place holder icon
    var final_class = the_class.replace('fa fa-navicon', '').trim();

    //generate side nav link items!
    $.post( "quicknav.php", { content_changed : 2, final_class : final_class }, function( data2 ){ 
        // update display
        e.innerHTML = data2;
        //*** once we ger here, the final output has changed to reflect that the side nav links are present
        // but the navbar links have reverted back to the initial state before insertion
    });
}

编辑2: 我的代码有些奇怪的事情。作为实验,我将iframe的内容复制到了文本区域。然后,我一次只完成了一行。它表明部分更改都已进行,但是当我到达包含子字符串的行时,第一个更改被删除了,不知道从哪里开始。有谁知道为什么以下行会影响文本区域的内容?

 var res = new_content.substring( insert_sidenav + 16, insert_start + 9 );

请注意,变量new_content只是文本字符串!

1 个答案:

答案 0 :(得分:0)

.innerHTML以表示HTML文本树的字符串形式返回静态内容。

给出:相同的原始内容,然后

也许您应该考虑这样使用Live NodeList或HTMLCollection:

target = document.getElementById('page_demo').contentWindow
                           .document.getElementsByTagName('body')