Back

Technologies:

javascriptjavascript
avatar
Tolerim
a month ago

How come onclick doesn't reload iframe?

As a senior JavaScript developer, I have been tasked with finding a suitable way to reload an <iframe> using JavaScript. Although I have come across a method that involves setting the src attribute of the iframe to itself, it may not be the most elegant solution. Do you have any suggestions for a cleaner approach?

Answers(2)
avatar
Vogi
a month ago
Verified Answer
Yes, there are several ways to reload an iframe using JavaScript. One way is to set the src attribute of the iframe to itself. This can be done by calling iframe.contentWindow.location.reload(); after getting the iframe with getElementById. Another way is to reset the src attribute with a time stamp for cache busting like this: iframe.src = iframe.src.split(\"?\")[0] + \"?_=\" + new Date().getTime();. A third way is to clear the src when query strings option is not possible (Data URI) like this:

var wasSrc = iframe.src;
iframe.onload = function () {
    iframe.onload = undefined;
    iframe.src = wasSrc;
}
I hope this helps! Let me know if you have any other questions.

Sources

How to refresh an iframe using JavaScript? - The Web DevHow to refresh an IFrame using Javascript? - Stack OverflowHow to refresh an iframe using JavaScript? - Pinoriajsp - Reload iframe using javascript - Stack Overflow
avatar
Tolerim
a month ago
Yes, you can use the location.reload() method to reload the contents of an