What’s the best way to reload / refresh an iframe?
Asked Answered
I

24

321

I would like to reload an <iframe> using JavaScript. The best way I found until now was set the iframe’s src attribute to itself, but this isn’t very clean. Any ideas?

Isolda answered 17/9, 2008 at 19:0 Comment(3)
Is there a reason why setting the src attribute to itself isn't clean? It seems to be the only solution that works across browsers and across domainsChestonchest
Setting the src attribute to itself causes problems if you have a link elsewhere that targets the <iframe>. Then the frame will show the initial page as originally designed.Bulkhead
Setting the src attribute scrolls the iframe up to the top of the page, location.reload() does not. If you are reloading because e.g. the CSS underlying the iframe has changed, the latter would be preferable.Dished
G
301
document.getElementById('some_frame_id').contentWindow.location.reload();

be careful, in Firefox, window.frames[] cannot be indexed by id, but by name or index

Goeger answered 17/9, 2008 at 19:36 Comment(14)
Actually, this approach didn't work for me in Chrome. There was no 'contentWindow' property. Though it was possible to use document.getElementById('some_frame_id').location.reload(); The method that worked for both FF and Chrome was document.getElementById('iframeid').src = document.getElementById('iframeid').srcGrowing
@MikeBevz can location.reload is also accessible using Jquery selector?Strabismus
absolute it's work, but stuck with same domain origin policy ==aUndecided
frames[1].location.href.reload() and window.frames['some_frame_id'].location.href.reload() can also be usedLongawa
Hi does this working on ie ?? I try to used it on ie 10 it doesn't work for me.Audry
With Chrome 30, I can do cross-domain request from within an iframe. document.getElementById("iframeForCrossDomain").src="http://anotherdomain.com/index.html"Swaim
In IE if you use a frameset and the object returned by getElementById is a HTMLFrameElement you need to specify the rows attribute for every row for example if you have 3 frames and your rows="50%,25%" The third frame will return as a HTMLFrameElement, but if you change the rows to rows="50%,25%,25%" the third frame will return as a window object (in FF the third frame returns as a window object in both cases)Ostentation
If you can't access iframe window, you have to change src attribute of iframe tag.Estrade
Eventually, for me, the only solution that worked was setting the src of the iframe again (to the original one, in this case). Trying to access the "reload" function failed because of the well-known cross-domain issue... FYIAbebi
If the iframe source contains a submitted form, will reload cause it to resubmit (as if you hit the browser refresh button)? If so, that would be a significant difference between the two methods.Fated
I noticed this wasn't working when i tried to assign the same URL, i assume Chrome was doing some caching. So i appedned a simple date parameter "?d=" + Date.now() and that seemed to fix the issuePecten
I get Uncaught TypeError: Cannot read property 'location' of undefinedOverhand
To reach into an iframe, it has to be from the same origin as its parent, or you won't have access.Goeger
this approach is not working in google chrome or firefoxSynesthesia
V
257
document.getElementById('iframeid').src = document.getElementById('iframeid').src

It will reload the iframe, even across domains! Tested with IE7/8, Firefox and Chrome.

Note: As mentioned by @user85461, this approach doesn't work if the iframe src URL has a hash in it (e.g. http://example.com/#something).

Veda answered 31/10, 2010 at 6:27 Comment(10)
document.getElementById('iframeid').src += ''; also works: jsfiddle.net/Daniel_Hug/dWm5kTwofaced
And what exactly do you do if the iframe's source has changed since it was added to the page?Finical
Works for me on Chrome ver33! Strange that we can't simply use reload but this is allowed.Suspension
Note that if the iframe src has a hash in it (e.g. http://example.com/#something), this won't reload the frame. I've used the approach of adding a throwaway query parameter like ?v2 to the URL before the hash.Mychael
This causes the iframe to scroll back to the top.Stamps
@NiettheDarkAbsol It will still work as long as you haven't stored the source in a variableSoftener
@Stamps That's why it wouldn't be okay for me as well.Tractate
lol, this is crazy. It still works in 2022 :)Ornithorhynchus
To keep any hashes, use <iframe>.contentWindow.location.href += ""Gaudery
not working in google chromeSynesthesia
K
69

If using jQuery, this seems to work:

$('#your_iframe').attr('src', $('#your_iframe').attr('src'));
Kaylakayle answered 18/10, 2011 at 15:29 Comment(4)
This, without jQuery: var iframe = document.getElementById("your_iframe"); iframe.src = src; Bidwell
Please note to any future people that this (and the plain js solution) are the best to use, as it's cross platform and works across domains.Chestonchest
@Bidwell I think you mean: var iframe = document.getElementById("your_iframe"); iframe.src = iframe.src;Jay
none of the above solutions working now.Synesthesia
E
51

Appending an empty string to the src attribute of the iFrame also reloads it automatically.

document.getElementById('id').src += '';
Equivocal answered 24/10, 2017 at 4:38 Comment(2)
This is the best answer because it works on all iframes, including cross-origin iframes. In contrast, the contentWindow.location.reload() approach only works on iframes from the same origin.Nicks
But the latter doesn't scroll to the top, so it depends on your priorities.Dished
S
20
window.frames['frameNameOrIndex'].location.reload();
Servant answered 17/9, 2008 at 19:1 Comment(0)
G
12

Because of the same origin policy, this won't work when modifying an iframe pointing to a different domain. If you can target newer browsers, consider using HTML5's Cross-document messaging. You view the browsers that support this feature here: http://caniuse.com/#feat=x-doc-messaging.

If you can't use HTML5 functionality, then you can follow the tricks outlined here: http://softwareas.com/cross-domain-communication-with-iframes. That blog entry also does a good job of defining the problem.

Gristede answered 8/10, 2010 at 0:2 Comment(0)
D
9

I've just come up against this in chrome and the only thing that worked was removing and replacing the iframe. Example:

$(".iframe_wrapper").find("iframe").remove();
var iframe = $('<iframe src="' + src + '" frameborder="0"></iframe>');
$.find(".iframe_wrapper").append(iframe);

Pretty simple, not covered in the other answers.

Disconnection answered 1/8, 2012 at 16:9 Comment(1)
yes this is the only solution that worked for me as well.Synesthesia
V
8

Simply replacing the src attribute of the iframe element was not satisfactory in my case because one would see the old content until the new page is loaded. This works better if you want to give instant visual feedback:

var url = iframeEl.src;
iframeEl.src = 'about:blank';
setTimeout(function() {
    iframeEl.src = url;
}, 10);
Virility answered 23/9, 2015 at 13:28 Comment(2)
I've just tested the same approach but without setTimeout - and it worked for me. actually, just iframe.setAttribute('src', iframe.getAttribute('src'))Commutual
can confirm what @Commutual said works for meBouffard
M
3

A refinement on yajra's post ... I like the thought, but hate the idea of browser detection.

I rather take ppk's view of using object detection instead of browser detection, (http://www.quirksmode.org/js/support.html), because then you're actually testing the capabilities of the browser and acting accordingly, rather than what you think the browser is capable of at that time. Also doesn't require so much ugly browser ID string parsing, and doesn't exclude perfectly capable browsers of which you know nothing about.

So, instead of looking at navigator.AppName, why not do something like this, actually testing for the elements you use? (You could use try {} blocks if you want to get even fancier, but this worked for me.)

function reload_message_frame() {
    var frame_id = 'live_message_frame';
    if(window.document.getElementById(frame_id).location ) {  
        window.document.getElementById(frame_id).location.reload(true);
    } else if (window.document.getElementById(frame_id).contentWindow.location ) {
        window.document.getElementById(frame_id).contentWindow.location.reload(true);
    } else if (window.document.getElementById(frame_id).src){
        window.document.getElementById(frame_id).src = window.document.getElementById(frame_id).src;
    } else {
        // fail condition, respond as appropriate, or do nothing
        alert("Sorry, unable to reload that frame!");
    }
}

This way, you can go try as many different permutations as you like or is necessary, without causing javascript errors, and do something sensible if all else fails. It's a little more work to test for your objects before using them, but, IMO, makes for better and more failsafe code.

Worked for me in IE8, Firefox (15.0.1), Chrome (21.0.1180.89 m), and Opera (12.0.2) on Windows.

Maybe I could do even better by actually testing for the reload function, but that's enough for me right now. :)

Multicolored answered 15/9, 2012 at 6:58 Comment(0)
R
3

Another solution.

const frame = document.getElementById("my-iframe");

frame.parentNode.replaceChild(frame.cloneNode(), frame);
Rochus answered 7/1, 2018 at 17:2 Comment(1)
A disadvantage of that is modifies the root document DOM tree and will cause a repaint. I used var url = ifr.src; ifr.src = null; ifr.src = url;Pontiff
N
3

Now to make this work on chrome 66, try this:

const reloadIframe = (iframeId) => {
    const el = document.getElementById(iframeId)
    const src = el.src
    el.src = ''
    setTimeout(() => {
        el.src = src
    })
}
Numerical answered 24/5, 2018 at 13:57 Comment(0)
B
2

for new url

location.assign("http:google.com");

The assign() method loads a new document.

reload

location.reload();

The reload() method is used to reload the current document.

Brendabrendan answered 28/1, 2014 at 18:25 Comment(0)
L
1

In IE8 using .Net, setting the iframe.src for the first time is ok, but setting the iframe.src for the second time is not raising the page_load of the iframed page. To solve it i used iframe.contentDocument.location.href = "NewUrl.htm".

Discover it when used jQuery thickBox and tried to reopen same page in the thickbox iframe. Then it just showed the earlier page that was opened.

Lownecked answered 1/2, 2010 at 9:43 Comment(0)
S
1

Use reload for IE and set src for other browsers. (reload does not work on FF) tested on IE 7,8,9 and Firefox

if(navigator.appName == "Microsoft Internet Explorer"){
    window.document.getElementById('iframeId').contentWindow.location.reload(true);
}else {
    window.document.getElementById('iframeId').src = window.document.getElementById('iframeId').src;
}
Stomodaeum answered 29/11, 2011 at 1:23 Comment(0)
C
1

If you using Jquery then there is one line code.

$('#iframeID',window.parent.document).attr('src',$('#iframeID',window.parent.document).attr('src'));

and if you are working with same parent then

$('#iframeID',parent.document).attr('src',$('#iframeID',parent.document).attr('src'));
Chavez answered 9/5, 2014 at 6:51 Comment(0)
E
1

Using self.location.reload() will reload the iframe.

<iframe src="https://vivekkumar11432.wordpress.com/" width="300" height="300"></iframe>
<br><br>
<input type='button' value="Reload"  onclick="self.location.reload();" />
Elledge answered 1/5, 2017 at 8:17 Comment(2)
that reload the whole main windowKaine
This works from JavaScript inside the current iFrame.Townie
O
0
<script type="text/javascript">
  top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script> 
Octillion answered 22/5, 2012 at 19:6 Comment(1)
Not the choice I would use but I guess it would do. With some additional code that you could have added in.Landgraviate
S
0

If all of the above doesn't work for you:

window.location.reload();

This for some reason refreshed my iframe instead of the whole script. Maybe because it is placed in the frame itself, while all those getElemntById solutions work when you try to refresh a frame from another frame?

Or I don't understand this fully and talk gibberish, anyways this worked for me like a charm :)

Sturdivant answered 23/7, 2013 at 11:8 Comment(0)
B
0

Have you considered appending to the url a meaningless query string parameter?

<iframe src="myBaseURL.com/something/" />

<script>
var i = document.getElementsById("iframe")[0],
    src = i.src,
    number = 1;

//For an update
i.src = src + "?ignoreMe=" + number;
number++;
</script>

It won't be seen & if you are aware of the parameter being safe then it should be fine.

Belia answered 7/2, 2014 at 22:2 Comment(0)
T
0

If you tried all of the other suggestions, and couldn't get any of them to work (like I couldn't), here's something you can try that may be useful.

HTML

<a class="refresh-this-frame" rel="#iframe-id-0">Refresh</a>
<iframe src="" id="iframe-id-0"></iframe>

JS

$('.refresh-this-frame').click(function() {
    var thisIframe = $(this).attr('rel');
    var currentState = $(thisIframe).attr('src');
    function removeSrc() {
        $(thisIframe).attr('src', '');
    }
    setTimeout (removeSrc, 100);
    function replaceSrc() {
        $(thisIframe).attr('src', currentState);
    }
    setTimeout (replaceSrc, 200);
});

I initially set out to try and save some time with RWD and cross-browser testing. I wanted to create a quick page that housed a bunch of iframes, organized into groups that I would show/hide at will. Logically you'd want to be able to easily and quickly refresh any given frame.

I should note that the project I am working on currently, the one in use in this test-bed, is a one-page site with indexed locations (e.g. index.html#home). That may have had something to do with why I couldn't get any of the other solutions to refresh my particular frame.

Having said that, I know it's not the cleanest thing in the world, but it works for my purposes. Hope this helps someone. Now if only I could figure out how to keep the iframe from scrolling the parent page each time there's animation inside iframe...

EDIT: I realized that this doesn't "refresh" the iframe like I'd hoped it would. It will reload the iframe's initial source though. Still can't figure out why I couldn't get any of the other options to work..

UPDATE: The reason I couldn't get any of the other methods to work is because I was testing them in Chrome, and Chrome won't allow you to access an iframe's content (Explanation: Is it likely that future releases of Chrome support contentWindow/contentDocument when iFrame loads a local html file from local html file?) if it doesn't originate from the same location (so far as I understand it). Upon further testing, I can't access contentWindow in FF either.

AMENDED JS

$('.refresh-this-frame').click(function() {
    var targetID = $(this).attr('rel');
    var targetSrc = $(targetID).attr('src');
    var cleanID = targetID.replace("#","");     
    var chromeTest = ( navigator.userAgent.match(/Chrome/g) ? true : false );
    var FFTest = ( navigator.userAgent.match(/Firefox/g) ? true : false );      
    if (chromeTest == true) {
        function removeSrc() {
            $(targetID).attr('src', '');
        }
        setTimeout (removeSrc, 100);
        function replaceSrc() {
            $(targetID).attr('src', targetSrc);
        }
        setTimeout (replaceSrc, 200);
    }
    if (FFTest == true) {
        function removeSrc() {
            $(targetID).attr('src', '');
        }
        setTimeout (removeSrc, 100);
        function replaceSrc() {
            $(targetID).attr('src', targetSrc);
        }
        setTimeout (replaceSrc, 200);
    }       
    if (chromeTest == false && FFTest == false) {
        var targetLoc = (document.getElementById(cleanID).contentWindow.location).toString();
        function removeSrc() {
            $(targetID).attr('src', '');
        }
        setTimeout (removeSrc, 100);
        function replaceSrc2() {
            $(targetID).attr('src', targetLoc);
        }
        setTimeout (replaceSrc2, 200);
    }
});
Turgot answered 3/4, 2014 at 22:7 Comment(0)
A
0

For debugging purposes one could open the console, change the execution context to the frame that he wants refreshed, and do document.location.reload()

Ambrosane answered 13/9, 2017 at 14:0 Comment(0)
C
0

Reload from inside Iframe

If your app is inside an Iframe you can refresh it with replacing the location href:

document.location.href = document.location.href
Conto answered 2/9, 2021 at 9:58 Comment(0)
H
0

I had a problem with this because I didnt use a timeout to give the page time to update, I set the src to '', and then set it back to the original url, but nothing happened:

function reload() {
   document.getElementById('iframe').src = '';
   document.getElementById('iframe').src = url;
}

but it didnt reload the site, because it is single threaded, the first change doesnt do anything, because that function is still taking up the thread, and then it sets it back to the original url, and I guess chrome doesnt reload because preformance or whatever, so you need to do:

function setBack() {
   document.getElementById('iframe').src = url;
}
function reload() {
   document.getElementById('iframe').src = '';
   setTimeout(setBack,100);
}

if the setTimeout time is too short, it doesnt work, so if its not working, try set it to 500 or something and see if it works then.

this was in the latest version of chrome at the time of writing this.

Hidebound answered 26/7, 2022 at 1:18 Comment(1)
This can happen if you call the function before the page is fully loaded.Autograft
A
0

This way avoids adding history to some browsers (an unneeded overhead). In the body section put:

    <div id='IF'>
    <iframe src='https://www.wolframalpha.com/input?i=Memphis%20TN%20Temperature' 
        style="width:5in; height:6in"  // or whatever you want in your Iframe
        title'Temperature'></iframe>
    </div>

Then in some JAVASCRIPT you may have a function like:

    function    UPdate()    { // Iframe
    T1=document.getElementById('IF')
    T2=T1.innerHTML
    T1.innerHTML=T2
}
Almond answered 23/12, 2022 at 4:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.