iframe content disappears on Firefox

2020-08-22 06:18发布

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?

2条回答
疯言疯语
2楼-- · 2020-08-22 06:58

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.

查看更多
甜甜的少女心
3楼-- · 2020-08-22 07:08

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);
}            
查看更多
登录 后发表回答