Open In App

How to specify the HTML content of the page to show in the iframe element HTML5 ?

In this article, we will learn how to specify the content of a webpage to <iframe> in a web browser statically and dynamically by using JavaScript with HTML. We need a web browser i.e., Chrome (recommended) or Electron Application. This article will explain the proper way to assign or embed any external webpage to another webpage or even change the content of that embedded page dynamically using JavaScript. So let’s begin!

Note: There are some websites that can not be shown in <iframe>, we will discuss this further in the article.



Syntax:

<iframe id="" src="" style=""></iframe>

The src member of the <iframe> object holds the source of the embedded webpage. We can statically assign the address to it, and dynamically change it on runtime as well as discussed below:



Dynamic-Assignment Approach:

Get the source from the input field.

let geeks = document.getElementById("<id name/class name>").value; 

Assign the input to the ‘src‘ member of the iframe.

document.getElementById("<id name/class name>").src = geeks;

Example: Below is the code that illustrates the use of iframe.




<!DOCTYPE html>
<html>
 
<body>
    <h1>The iframe element</h1>
    <iframe id="embed1"
            src="https://www.geeksforgeeks.org"
            style="border-style:1px;border-style: solid;
                   width:100%; height:400px;
                   margin-bottom: 40px;">
    </iframe>
    <input type="text"
           id="source"
           style="width: 60%"
           placeholder="Enter the link of source." />
    <button id="loadpage">
        Change Webpage
    </button>
    <script>
        document.getElementById("loadpage").onclick =
            function updatesource() {
                let newsource = document.getElementById("source").value;
                document.getElementById("embed1").src = newsource;
            };
    </script>
</body>
</html>

Output: 

If <iframe> is not working? 

Websites like google.com, facebook.com, messenger.com, and many more don’t support iframe due to some same origin conflicts. Here is the error you will get in the console if you tried to load those websites which don’t support iframe.

Note: 

  1. You will need to apply “http://” or “https://” before the website address otherwise it will give error.
  2. Keep in mind about those websites which doesn’t supports the iframe.

Article Tags :