jQuery - sequence of page load(?) issue

2019-08-05 01:48发布

EDIT:

Fixed as follows, simply hide the iframe by setting height and width to zero:

<iframe frameborder="0" id="frm" height="0" width="0"></iframe>

var frmurl ='http://www.bbc.co.uk';

jQuery(function($){
        $('#frm').attr('src', frmurl);
        var doc = $('#frm')[0].contentDocument;
        $(doc.body).html('This text should replace the BBC website');  
});

My website relies on a third party system to update a record in a database and display a confirmation message. Access to the third party system is via an iFrame. I would like to replace the confirmation message with one of my own.

I use jQuery and I have the iFrame working correctly except that my replacement text is displayed very briefly before the confirmation message generated by the third party system overwrites it. You can see an example at this jsFiddle.

How can I ensure that my own text isn't overwritten? I think it has to do with the sequence of events in which the page is generated?

<iframe frameborder="0" id="frm" scrolling="no" width="100%"></iframe>

var frmurl ='http://www.bbc.co.uk';

jQuery(function($){
        $('#frm').attr('src', frmurl);
        var doc = $('#frm')[0].contentDocument;
        $(doc.body).html('This text should replace the BBC website');   
});

2条回答
Juvenile、少年°
2楼-- · 2019-08-05 02:36

Updating the <iframe> "src" property is basically an explicit request that the browser update the frame with the content fetched from the given URL. Thus, it doesn't really make sense to ask that the browser both do that and not do that :)

What you can do, however, is put your message somewhere else instead of in the <iframe>. The HTTP transaction will work whether the <iframe> is visible or not, so if you don't want your user to see the results you can just hide the <iframe> via CSS or whatever.

查看更多
不美不萌又怎样
3楼-- · 2019-08-05 02:45

Loading an IFRAME is asynchronous. You may be able to do what you want like this:

jQuery(function($){
        $('#frm').attr('src', frmurl).load(function() {
            var doc = $(this)[0].contentDocument;
            $(doc.body).html('This text should replace the BBC website');
        });  
});

This waits until the IFRAME is loaded, then tries to modify it.

However, I'm not sure this will be allowed -- you're not allowed to manipulate the contents of an IFRAME loaded from a different domain.

UPDATE:

I was right, it doesn't work. I tried this fiddle and the console logs:

Blocked a frame with origin "http://fiddle.jshell.net" from accessing a frame with origin "http://www.bbc.co.uk". Protocols, domains, and ports must match.

You're not allowed to do what you're trying to do.

查看更多
登录 后发表回答