简体   繁体   中英

iframe content disappears on Firefox

I am filling an empty iframe with basic HTML, using $iframe.contents().find('body').html(contentBody);

See: http://jsfiddle.net/UjT2b/2/

This works well on Chrome. On Firefox, I can see very briefly the content inside, but then it suddenly disappears. When I set a breakpoint on this line with Firebug, then continue running, the content stays inside. But if I set a breakpoint on the line after, it goes away.

Any clue on how to fix this?

I have encountered similar problem while attempting to fill dynamically created iframe. Using of iframe onload event solved the situation for me. As seen the onload solution does not work for other browsers than FF, hence the preserved standard way.

/**
 * Fills an iframe using data stored within textarea. Useful for creating email
 * template previews
 *
 * @param  {String} inputSelector
 * @param  {String} outputElemClasses
 * @return void
 */
function displayEmail(inputSelector, outputElemClasses)
{
    $(inputSelector).each(function(i) {
        var templateData = $(this).text();
        var $iframe = $('<iframe></iframe>');
        $iframe.addClass(outputElemClasses);
        $iframe.insertAfter(this);
        // non-firefox
        updateIframe($iframe, templateData);
        // firefox
        $iframe.load(function(e){
            updateIframe($iframe, templateData);
        })
    })
}


/**
 * Fills in target iframe using supplied data
 *
 * @param  {Object} $iframe
 * @param  {String} data
 * @return void
 */
function updateIframe($iframe, data)
{
    $iframe.contents().find('html').html(data);
}            

I cannot see your entire code, but have worked with what you gave me in a way that I would do it. There is a chance that you are not giving the script the chance to let the rest of the HTML load before it is executed and thus unpredictable things can happen. I find that if I do not wait for the window to load then the image will not show up. If you encase everything you did, like below, then you shouldn't have a problem:

$( window ).load( function() {

    var html = "<img src='http://www.google.fr/logos/2011/Louis_Daguerre-2011-hp.jpg' alt='image' />";


    $( "#myIframe" ).contents().find( 'body' ).html( html );

});

Just remember that jQuery.html() will replace all the HTML inside the element given.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM