Using JavaScript to refresh and reload an iframe on main page

by Yang Yang on January 1, 2009

Share This Article:
Subscribe to Kavoir: blog feed

<iframe></iframe> is useful in many aspects. There are times when you want to refresh the content of an iframe and reload the page in it, without refreshing that of the main page, and it can be achieved with a tiny property of iframe, src.

Let’s say you have an iframe of captcha that enables the user to refresh it and serves different security code every time.

<iframe name="security-code" id="security-code" src="/gen-captcha-image.php"></iframe> 

<a href="javascript:refreshCaptcha();">Refresh for new code!</a> 

refreshCaptcha() looks like this:

<script type="text/javascript">
	function refreshCaptcha () {
		var code = document.getElementById('security-code');
		code.src = code.src; // that is the essence here
	}
</script>
Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 7 comments… read them below or add one }

Paul February 28, 2009 at 9:57 pm

Hi,

been looking all over for this, and finally found a clearly described working example – many thanks, superb description and the end of a very frustrating 20 minutes!

Reply

Jack April 14, 2009 at 9:14 am

Is there a way to do this without a “refresh button” Maybe something like a timer?

I’m trying to refresh an iframe containing anotehr html page that I’ve embedded on a wordpress page. I frequently upload new embedded pages and I want the reader to get the latest version not some cashed version.

I do have access to the meta on the embedded page if that would help

Reply

Yang Yang February 26, 2010 at 3:26 pm

It’s possible but hidden timer for stuff is far from user friendliness. Not recommended. You have to give the users the control.

Reply

Phil February 6, 2010 at 10:06 pm

THANKS SO MUCH! i’ve been searching for a good week or to looking for something like this.

Reply

AdrianN November 22, 2010 at 2:22 am

Thank you for this post. A simple and elegant solution. I am going to use it on my website to have a user requested iframe refresh.

Reply

Dan December 29, 2010 at 9:44 am

Great script, will put it to use!!! Thanks

Reply

Sam December 29, 2010 at 6:58 pm

How to refresh banner code without having to refresh the whole page ?

Reply

Leave a Comment

Previous post:

Next post: