Open In App

How to navigate URL in an iframe with JavaScript ?

To navigate the URL in an iframe with JavaScript, we have to set the src attribute or return the value of the src attribute in an iframe element. The src attribute defines the URL of the document that can be shown in an iframe.

Syntax:

document.getElementById("selector").src = "URL";

URL values:

Return value:

It returns the complete URL of the document that is embedded in the iframe.



Example 1: Below is the code that illustrates using Absolute URL.




<!DOCTYPE html>
<html>
 
<body style="text-align:center;">
    <iframe id="gfgFrame" src=""
        style="height: 50vh; width: 600px;">
    </iframe>
 
    <p>Click to visit GeeksForGeeks website</p>
 
    <button onclick="navigate()">
        Click it
    </button>
 
    <script>
        function navigate() {
            document.getElementById("gfgFrame").src
                = "https://www.geeksforgeeks.org/";
        }
    </script>
</body>
 
</html>

Output:



Example 2: Below is the code that illustrates the Relative URL.




<!DOCTYPE html>
<html>
 
<body style="text-align:center;">
    <iframe id="gfgFrame" src=""
        style="height: 50vh; width: 600px;">
    </iframe>
    <br>
 
    <button onclick="navigate()">
        Click it
    </button>
 
    <script>
        function navigate() {
            document.getElementById
                ("gfgFrame").src = "home.html";
        }
    </script>
</body>
 
</html>

Output:


Article Tags :