cpave3

Iframe Communication - inner.html

Oct 16th, 2020
132
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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>Embedded Page</title>
  7.   </head>
  8.   <body>
  9.     <h2>Embedded</h2>
  10.     <textarea cols="30" rows="10" disabled id="output">waiting</textarea>
  11.     <input type="text" id="field" />
  12.     <button id="send">Send</button>
  13.     <script>
  14.       // set up references to DOM nodes
  15.       const output = document.getElementById("output");
  16.       const button = document.getElementById("send");
  17.       const field = document.getElementById("field");
  18.  
  19.       // create a variable for the parent window. We will assign it once we get the first message.
  20.       let parent = null;
  21.  
  22.       // add an event listener to send messages when the button is clicked
  23.       button.addEventListener("click", () => {
  24.         // don't do anything if there is no parent reference yet
  25.         if (parent === null) {
  26.           return;
  27.         }
  28.  
  29.         // otherwise get the field text, and send it to the parent
  30.         const text = field.value;
  31.         parent.postMessage(text);
  32.       });
  33.  
  34.       // add an event listener to run when a message is received
  35.       window.addEventListener("message", ({ data, source }) => {
  36.         // if we don't have a reference to the parent window yet, set it now
  37.         if (parent === null) {
  38.           parent = source;
  39.         }
  40.  
  41.         // now we can do whatever we want with the message data.
  42.         // in this case, displaying it, and then sending it back
  43.         // wrapped in an object
  44.         output.textContent = JSON.stringify(data);
  45.         const response = {
  46.           success: true,
  47.           request: { data },
  48.         };
  49.         parent.postMessage(response);
  50.       });
  51.     </script>
  52.   </body>
  53. </html>
  54.  
RAW Paste Data