Open In App
Related Articles

How to navigate URL in an iframe with JavaScript ?

Improve Article
Improve
Save Article
Save
Like Article
Like

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

Syntax:

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

URL values: The possible values of URLs are –

  • Absolute URL: It points to another website (For example: https://www.geeksforgeeks.org/c-plus-plus/).
  • Relative URL: It points to a file within a website (For example: /gfg.php).

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.

HTML




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

HTML




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


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 23 Apr, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials