JavaScript

How to copy the value to the caller by clicking text elements inside an iframe

In web development, dynamic data manipulation using modal windows is a common scenario.
In this article, we will explain in an easy-to-understand way how to use an iframe inside a modal to copy the data of a clicked element to the parent page, even for beginners.

In the previous article “How to Easily Display a Modal Screen Using Bootstrap“, we used Bootstrap to display an iframe page in a modal window.
Here, we will copy the text element of the iframe page to the value of the caller when clicked.

The following steps explain how to copy the value of the clicked element to the caller’s value.

Step 1: Create an iframe on the parent page

First, add an iframe to the parent page. Refer to the following code:

<iframe id="myIframe" src="iframe.html" width="100%" height="200"></iframe>

In the src attribute of this iframe tag, specify the URL of another page. We will create this page later.

Step 2: Build the modal window

Next, display the iframe inside a modal window using Bootstrap.
Load the bootstrap.min.css and bootstrap.bundle.min.js files, and add the following example code to the parent page:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Demo page - Copy text elements inside iframe displayed in modal to caller value</title>
<meta name="description" content="Demo page - Copy text elements inside iframe displayed in modal to caller value">
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/demo/inc/head.php'; ?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
  </head>
  <body>
<h1 class="text-center pt-5">When you click a text element inside the iframe displayed in the modal,<br>it will be copied to the textbox below.</h1>

<div class="text-center pt-5">
  <input type="text" id="myInput" value="" class="text-center" style="width:300px;">
</div>

<div class="text-center pt-5">
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Show Modal Window
</button>
</div>

<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticBackdropLabel">Modal Window</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
<iframe id="myIframe" src="iframe.html" width="100%" height="200"></iframe>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
  window.addEventListener('message', function(event) {
    var value = event.data;

    // Set value to the caller element
    document.getElementById('myInput').value = value;
  });

</script>

</body>
</html>

Step 3: Implement click event inside the iframe

In the iframe page (iframe.html), implement a process to send the value of the clicked element to the parent page.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>iframe page - Copy text elements to parent by click</title>
<meta name="description" content="iframe page - Copy text elements to parent by click">
<style>
html, body {
  margin: 0;
  text-align: center;
  font-size: 16px;
}
h1{
  font-size: 16px;
  padding: 0 0 20px 0;
  margin: 0;
}
.copy{
  width: 50%;
  margin: 15px auto;
}
</style>
</head>
<body>
<h1>Click on the text of the following div or input tag to copy it to the parent page.</h1>

<div class="copy">Copy text inside div tag</div>

<input type="text" class="copy" value="Copy input tag's value text" />

<script type="text/javascript">
var copy = document.getElementsByClassName("copy");
var copys = Array.from(copy);

copys.forEach(function(target) {
    target.addEventListener('click', function(event) {
      var targetElement = event.target;
      var valueToCopy = targetElement.textContent || targetElement.value;

      parent.postMessage(valueToCopy, '*');
    });

});
</script>

</body>
</html>

This code allows you to send the value of a clicked element inside the iframe to the parent page.

Step 4: Message receiving process on the parent page

Finally, receive the data sent from the iframe on the parent page and copy it to the specified form element.

<script type="text/javascript">
  window.addEventListener('message', function(event) {
    var value = event.data;

    // Set value to the caller element
    document.getElementById('myInput').value = value;
  });
</script>

This code receives the data sent from the iframe and sets it as the value of the element with the ID myInput.

Step 5: Implementation notes

  • The src of the iframe must be within the same domain. Pay attention to the same-origin policy.
  • If it’s a different domain, CORS (Cross-Origin Resource Sharing) settings are required.
  • For security reasons, only handle trusted data in messages between iframes.

Demo page: Copy the text element inside the iframe displayed in the modal to the caller’s value

You can check the working demo page from the link below.

Demo page – Copy text elements inside iframe displayed in modal to caller value

Conclusion

In this article, we explained how to implement data copying using an iframe inside a modal.
By applying this technique, you can create dynamic form inputs and build interactive UIs. Try it out!

*Please use this code at your own risk.
Do not reuse the Google Analytics tag in the head tag of the demo page.