By caffo


2008-09-17 19:00:21 8 Comments

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?

21 comments

@Northern 2018-05-24 13:57:04

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
    })
}

@Vivek Kumar 2017-05-01 08:17:16

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();" />

@pery mimon 2019-08-28 09:20:38

that reload the whole main window

@Vasile Alexandru Peşte 2018-01-07 17:02:04

Another solution.

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

frame.parentNode.replaceChild(frame.cloneNode(), frame);

@Pocketsand 2018-02-27 12:10:40

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;

@Vasile Alexandru Peşte 2018-03-04 21:45:07

I think that reloading an iframe will always cause a repaint no matter of the code used.

@Yohanes AI 2017-10-24 04:38:39

Add empty space also reload the iFrame automatically.

document.getElementById('id').src += '';

@h3dkandi 2017-09-13 14:00:06

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

@Patrick Rudolph 2015-09-23 13:28:29

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);

@bonbonez 2016-05-11 15:56:11

I've just tested the same approach but without setTimeout - and it worked for me. actually, just iframe.setAttribute('src', iframe.getAttribute('src'))

@Paresh3489227 2014-05-09 06:51:08

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'));

@Todd 2014-04-03 22:07:07

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);
    }
});

@user1212212 2014-02-07 22:02:48

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.

@user2675617 2014-01-28 18:25:50

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.

@lousygarua 2011-10-18 15:29:45

If using jQuery, this seems to work:

$('#your_iframe').attr('src', $('#your_iframe').attr('src'));

I hope it's not too ugly for stackoverflow.

@Seagrass 2014-07-14 19:20:48

This, without jQuery: var iframe = document.getElementById("your_iframe"); iframe.src = src;

@mirhagk 2015-09-22 18:18:17

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.

@maxisme 2016-02-14 01:33:36

@Seagrass I think you mean: var iframe = document.getElementById("your_iframe"); iframe.src = iframe.src;

@Marcin Janeczek 2013-07-23 11:08:14

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 :)

@Liam M 2012-08-01 16:09:38

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.

@Aaron Wallentine 2012-09-15 06:58:50

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. :)

@Sid 2012-05-22 19:06:35

<script type="text/javascript">
  top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script> 

@transilvlad 2012-10-21 13:11:06

Not the choice I would use but I guess it would do. With some additional code that you could have added in.

@yajra 2011-11-29 01:23:12

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;
}

@Shaulian 2010-02-01 09:43:08

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.

@evko 2010-10-31 06:27:52

document.getElementById('iframeid').src = document.getElementById('iframeid').src

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

@Web_Designer 2012-02-12 06:44:07

document.getElementById('iframeid').src += ''; also works: jsfiddle.net/Daniel_Hug/dWm5k

@Niet the Dark Absol 2012-10-11 15:17:55

And what exactly do you do if the iframe's source has changed since it was added to the page?

@Luke 2014-04-09 15:23:26

Works for me on Chrome ver33! Strange that we can't simply use reload but this is allowed.

@user85461 2015-02-19 04:21:11

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.

@MrTux 2017-03-29 13:40:03

This causes the iframe to scroll back to the top.

@Ian 2018-02-06 18:10:38

@NiettheDarkAbsol It will still work as long as you haven't stored the source in a variable

@scunliffe 2008-09-17 19:01:38

window.frames['frameNameOrIndex'].location.reload();

@Ed. 2008-09-17 19:36:42

document.getElementById('some_frame_id').contentWindow.location.reload();

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

@Mike Bevz 2011-08-11 13:09:54

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').src

@Jitender Mahlawat 2012-11-21 10:11:10

@MikeBevz can location.reload is also accessible using Jquery selector?

@Bobby Stenly 2013-03-19 06:32:47

absolute it's work, but stuck with same domain origin policy ==a

@Daniël W. Crompton 2013-09-28 08:53:57

frames[1].location.href.reload() and window.frames['some_frame_id'].location.href.reload() can also be used

@Coder 2013-11-27 05:09:09

Hi does this working on ie ?? I try to used it on ie 10 it doesn't work for me.

@ZJ Lyu 2013-11-29 07:46:15

With Chrome 30, I can do cross-domain request from within an iframe. document.getElementById("iframeForCrossDomain").src="http://‌​anotherdomain.com/in‌​dex.html"

@notzippy 2013-12-18 18:19:58

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)

@Maciej Krawczyk 2016-06-01 12:42:29

If you can't access iframe window, you have to change src attribute of iframe tag.

@TheCuBeMan 2017-07-20 15:21:51

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... FYI

@xr280xr 2018-02-28 18:29:31

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.

@migreva 2018-04-27 18:59:53

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 issue

@user5047085 2019-02-23 03:53:35

I get Uncaught TypeError: Cannot read property 'location' of undefined

@Ed. 2019-02-23 14:14:46

To reach into an iframe, it has to be from the same origin as its parent, or you won't have access.

@big lep 2010-10-08 00:02:34

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.

Related Questions

Sponsored Content

13 Answered Questions

[SOLVED] How can I add new array elements at the beginning of an array in Javascript?

  • 2011-11-10 00:35:22
  • Moon
  • 760731 View
  • 1503 Score
  • 13 Answer
  • Tags:   javascript arrays

64 Answered Questions

[SOLVED] How to format numbers as currency string?

50 Answered Questions

[SOLVED] How to force the browser to reload cached CSS/JS files?

68 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

52 Answered Questions

[SOLVED] What is the best way to detect a mobile device?

27 Answered Questions

[SOLVED] How can I refresh a page with jQuery?

13 Answered Questions

[SOLVED] jQuery document.createElement equivalent?

16 Answered Questions

[SOLVED] How do I find out which DOM element has the focus?

  • 2009-01-30 20:21:31
  • Tony Peterson
  • 634850 View
  • 1254 Score
  • 16 Answer
  • Tags:   javascript dom

Sponsored Content