Reload an iframe with jQuery

2019-01-01 05:26发布

I have two iframes on a page and one makes changes to the other but the other iframe doesn't show the change until I refresh. Is there an easy way to refresh this iframe with jQuery?

<div class="project">
  <iframe id="currentElement" class="myframe" name="myframe" src="http://somesite.com/something/new"></iframe>
</div>

17条回答
弹指情弦暗扣
2楼-- · 2019-01-01 06:13

If you are cross-domain, simply setting the src back to the same url will not always trigger a reload, even if the location hash changes.

Ran into this problem while manually constructing Twitter button iframes, which wouldn't refresh when I updated the urls.

Twitter like buttons have the form: .../tweet_button.html#&_version=2&count=none&etc=...

Since Twitter uses the document fragment for the url, changing the hash/fragment didn't reload the source, and the button targets didn't reflect my new ajax-loaded content.

You can append a query string parameter for force the reload (eg: "?_=" + Math.random() but that will waste bandwidth, especially in this example where Twitter's approach was specifically trying to enable caching.

To reload something which only changes with hash tags, you need to remove the element, or change the src, wait for the thread to exit, then assign it back. If the page is still cached, this shouldn't require a network hit, but does trigger the frame reload.

 var old = iframe.src;
 iframe.src = '';
 setTimeout( function () {
    iframe.src = old;
 }, 0);

Update: Using this approach creates unwanted history items. Instead, remove and recreate the iframe element each time, which keeps this back() button working as expected. Also nice not to have the timer.

查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 06:13

//refresh all iframes on page

var f_list = document.getElementsByTagName('iframe');

 for (var i = 0, f; f = f_list[i]; i++) {
                            f.src = f.src;
                        }
查看更多
皆成旧梦
4楼-- · 2019-01-01 06:14
$('IFRAME#currentElement').get(0).contentDocument.location.reload()
查看更多
素衣白纱
5楼-- · 2019-01-01 06:16
    ifrX =document.getElementById('id') //or 
    ifrX =frames['index'];

cross-browser solution is:

    ifrX.src = ifrX.contentWindow.location

this is useful especially when <iframe> is a the target of a <form>

查看更多
墨雨无痕
6楼-- · 2019-01-01 06:17
$( '#iframe' ).attr( 'src', function ( i, val ) { return val; });
查看更多
登录 后发表回答