How to Send Data From One IFrame to Another

So you are working with iframes and you want them to communicate with each other. Well then, check this out. Type something in the top iframe and then click the button.



The text was sent from the top iframe to the bottom. Yeah that just happened.

Now I am going to show you the steps on how to do that.

Step 1.

Create a main html document to hold the two iframes. Like this.

<!DOCTYPE HTML>

<html>

<head>

<meta charset="UTF-8">

<title>Main Web Page</title>

</head>

<body>


<iframe src="source.html" id="source" style="height:500px;"></iframe><br>

<iframe src="target.html" id="target" style="height:300px;"></iframe>


</body>

</html>

Step 2.

Create the Web page that goes in your first iframe. It will have a text area and a button. Like this.

<!DOCTYPE HTML>

<html>

<head>

<meta charset="UTF-8">

<title>Source Page</title>

</head>

<body>

<p>

<textarea id="sourcetext" rows="10" cols="50">

Type some text here.

</textarea>

<br>


<button>Test Button</button>

</p>

</body>

</html> 

Step 3.

Write a script function for your source page to send data and add the function call to the button. 

<!DOCTYPE HTML>

<html>

<head>

<meta charset="UTF-8">

<title>Source Page</title>

</head>

<body>

<p>

<textarea id="sourcetext" rows="10" cols="50">

test2

</textarea>

<br>


<button onclick="send()">Test Button</button>

</p>


<script>

function send() { 

   var note = document.getElementById("sourcetext").value;

   window.parent.postMessage(note, '*');

   return false;

}

</script>

</body>

</html>

Step 4.

Add a script function to your main Web page to receive the data and resend it to the target iframe.

<!DOCTYPE HTML>

<html>

<head>

<meta charset="UTF-8">

<title>Main Web Page</title>

</head>

<body>

<iframe src="source.html" id="source" style="height:500px;"></iframe><br>

<iframe src="target.html" id="target" style="height:300px;"></iframe>


<script>

    window.addEventListener('message', function(event) {

     

      target.contentWindow.postMessage(event.data, '*');

      return false;

    });

</script>

</body>

</html>

Step 5.

Create the target iframe Web page.

<!DOCTYPE HTML>

<html>

<head>

<meta charset="UTF-8">

<title>Target Page</title>

</head>

<body>

<div id="target">This is the target iframe.

</div>


</body>

</html>

Step 6.

Add a script in the target Web page that receives the data and displays it.

<!DOCTYPE HTML>

<html>

<head>

<meta charset="UTF-8">

<title>Target Page</title>

</head>

<body>

<div id="target">This is the target iframe.

</div>


<script>

    window.addEventListener('message', function(event) {

      document.getElementById("target").innerHTML = event.data;

    });

</script>

</body>

</html>

And that is all. Thank you for taking the time to read this. 

Comments

Popular Posts