Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force a hard refresh on an iframe with JavaScript?

I've found many answers on Stack Overflow about how to refresh an iframe with JavaScript.

For example:

  • Iframe reload button

  • What's the best way to reload / refresh an iframe using JavaScript?

  • How to refresh an IFrame using Javascript?

They work fine. However, if the page in the iframe has changed recently, the refresh will not show this change. Is there any way I can force a hard refresh on the designated iframe so that the new version is shown?

like image 474
jkupczak Avatar asked Nov 20 '12 16:11

jkupczak


People also ask

Can you refresh an iframe?

Using self. location. reload() will reload the iframe. This works from JavaScript inside the current iFrame.

How do you refresh an iframe page?

How do you refresh iframes? reload() will reload the iframe. This works from JavaScript inside the current iFrame.

How do you refresh a page in JavaScript?

You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.

Can I edit iframe content?

To alter an iframe element within a variation, click the element in the Visual Editor. When the element is selected, a menu will appear that shows the actions you can take. Edit Element... > Edit iFrame: You can modify the iframe source ( src ) attribute when using Optimizely as an AB testing tool.


1 Answers

If the iframe is same-origin, you can force a full page reload using

iframe.contentWindow.location.reload(true);//The argument "true" will force all loaded resources, such as images, to be re-checked for expiry at the server

↪ View an example at jsFiddle

↪ More information at the Mozilla Developer wiki


If you have control over the HTTP headers sent for the page in the iframe, you can also instruct the browser not to cache it in the first place.
Furthermore, most web pages completely ignore parameters in the query string for which they have no handling code, so you could add a random value or a timestamp to the query string to make sure the browser sees it as a "new" page and does not use the cached copy:
if(iframe.src.indexOf('timestamp') > -1){ // Check if we still have a timestamp in the URL from a previous refresh
  iframe.src = iframe.src.replace(/timestamp=[^&]+/, 'timestamp=' + Date.now()); // And if so, replace it instead of appending so the URL doesn't grow too long.
}else{ // Else we will append the timestamp
  iframe.src += (iframe.src.indexOf('?') > -1 ? "&" : "?") + 'timestamp=' + Date.now();// If the URL contains a ?, append &timestamp=...; otherwise, append ?timestamp=...
}

Use new Date().getTime() instead of Date.now() if support for older browsers is important.

like image 144
user2428118 Avatar answered Sep 21 '22 11:09

user2428118