Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 353
Clément Avatar asked Apr 01 '12 19:04

Clément


2 Answers

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);
}            
like image 144
helvete Avatar answered Nov 10 '22 13:11

helvete


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.

like image 29
user2933822 Avatar answered Nov 10 '22 13:11

user2933822