cpave3

Iframe Communication - index.html

Oct 16th, 2020
1,565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 2.01 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <meta charset="UTF-8" />
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6.     <title>Parent Page</title>
  7.   </head>
  8.   <body>
  9.     <h2>Container</h2>
  10.     <textarea id="output" cols="30" rows="10" disabled>
  11. awaiting data...</textarea
  12.    >
  13.     <div>
  14.       <input type="text" id="field" value="type something fun here" />
  15.       <button id="send">Send</button>
  16.     </div>
  17.     <div>
  18.       <iframe
  19.        height="500px"
  20.        id="inner"
  21.        src="http://localhost:5000/inner.html"
  22.        frameborder="1"
  23.      ></iframe>
  24.     </div>
  25.  
  26.     <script>
  27.       // assign variables with references to the DOM nodes we will be interacting with
  28.       const output = document.getElementById("output");
  29.       const iframe = document.getElementById("inner");
  30.       const button = document.getElementById("send");
  31.       const field = document.getElementById("field");
  32.       // we will assign this value once the iframe is ready
  33.       let iWindow = null;
  34.  
  35.       // This event listener will run when we click the send button
  36.       button.addEventListener("click", () => {
  37.         // don't do anything if the iframe isn't ready yet
  38.         if (iWindow === null) {
  39.           return;
  40.         }
  41.  
  42.         // otherwise, get the value of our text input
  43.         const text = field.value;
  44.  
  45.         // and send it to the embedded page
  46.         iWindow.postMessage(text);
  47.       });
  48.  
  49.       // This event listener will run when the embedded page sends us a message
  50.       window.addEventListener("message", (event) => {
  51.         // extract the data from the message event
  52.         const { data } = event;
  53.  
  54.         // display it in our textarea as formatted JSON
  55.         output.value = JSON.stringify(data, null, 2);
  56.       });
  57.  
  58.       // Once the iframe is done loading, assign its window object to the variable we prepared earlier
  59.       iframe.addEventListener("load", () => {
  60.         iWindow = iframe.contentWindow;
  61.       });
  62.     </script>
  63.   </body>
  64. </html>
  65.  
Add Comment
Please, Sign In to add comment