Using JavaScript to refresh and reload an iframe on main page

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

8 thoughts on “Using JavaScript to refresh and reload an iframe on main page”

  1. 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!

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

Comments are closed.

Scroll to Top