Open In App

What’s the best way to reload / refresh an iframe?

Suppose that a user creates a webpage. Now he has a webpage, which contains an IFrame and a Button. Once the user presses the button, he/she needs the IFrame to be reloaded/refreshed. How are we going to make this possible? We are going to be finding it in the article.

The following syntax is work for both cases, where the IFrame is provided & loaded from the same domain, and where the IFrame is not from the same domain.



Syntax:

document.getElementById('YOUR IFRAME').contentDocument.location.reload(true);

NOTE: In Firefox, if you are going to use window.frames[], it might not be indexed by id. So you have to index it by index or name.



Example 1:




<!DOCTYPE html>
<html>
  
<head>
    <style>
        iframe {
            width: 786px;
            height: 600px;
            border: 0;
            overflow: hidden;
        }
    </style>
</head>
  
<body>
    <center>
        <h2 style="color:green">GeeksforGeeks</h2>
        <h4 style="color:purple">Reload / Refresh an iframe</h4>
        <iframe id="iframeid"
                src="https://ide.geeksforgeeks.org/" 
                width="600" 
                height="450"
                frameborder="0" 
                style="border:0" 
                allowfullscreen>
      </iframe>
        <input type="button"
               id="btn" 
               value="Refresh" />
  
        <script>
            function reload() {
                document.getElementById('iframeid').src += '';
            }
            btn.onclick = reload;
        </script>
    </center>
  
</body>
  
</html>

Output:
Before Refresh:

After Refresh:

Example 2:




<!DOCTYPE html>
<html>
  
<head>
    <style>
        body {
            text-align: center;
        }
          
        iframe {
            width: 786px;
            height: 600px;
            border: 0;
            overflow: hidden;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <h4 style="color:purple">Reload / Refresh an iframe</h4>
    <iframe id="iframeid" 
            src="Map Source"
            width="600" 
            height="450" 
            frameborder="0"
            style="border:0" 
            allowfullscreen>
  </iframe>
    <input type="button" 
           id="btn" 
           value="Refresh" />
  
    <script>
        function reload() {
            document.getElementById('iframeid').src += '';
        }
        btn.onclick = reload;
    </script>
  
</body>
  
</html>

Output:
When we load the code:

The Working:


Article Tags :