js-post-iframe

🧩 PostIframe

PostIframe is a lightweight JavaScript utility that simplifies working with iframes.
Load dynamic content using src or srcdoc, automatically send a postMessage to the iframe after it loads, and refresh iframe content on the fly β€” all with just a few lines of code.


πŸš€ Features


πŸ“¦ Installation

Include the script directly in your HTML:

<script src="post-iframe.min.js"></script>

πŸ§ͺ Basic Usage

πŸ”Ή Load iframe with src

<iframe id="myFrame" style="width:100%; height:300px;"></iframe>

<script>
  new PostIframe({
    element: document.getElementById('myFrame'),
    src: 'https://example.com',
    postMessageMessage: { type: 'hello', value: 'world' },
    onStart: function(frame) {
      console.log('Iframe initialization started!', frame);
    },
    onComplete: function(frame) {
      console.log('Iframe loaded!', frame);
    }
  });
</script>

πŸ”Ή Load iframe with srcdoc

<iframe id="doc-frame" style="width:100%; height:200px;"></iframe>

<script>
  new PostIframe({
    selector: '#doc-frame',
    srcdoc: '<h1>Hello from srcdoc!</h1>',
    onStart: function(frame) {
      console.log('Iframe initialization started!', frame);
    },
    onComplete: function(frame) {
      console.log('Iframe loaded!', frame);
    }
  });
</script>

πŸ”„ Refreshing an Existing Frame

Since PostIframe prevents duplicate instances on the same element, simply create a new instance with the same selector or element to refresh the iframe content:

// Initially load the iframe
new PostIframe({
  selector: '#myFrame',
  src: 'https://old-url.com'
});

// Later, refresh the iframe with a new URL by creating a new instance
new PostIframe({
  selector: '#myFrame',
  src: 'https://new-url.com'
});

πŸ“¬ postMessage Communication

πŸ”Ή Parent β†’ Iframe

new PostIframe({
  selector: '#myFrame',
  src: 'child.html',
  postMessageMessage: { type: 'greeting', message: 'Hello from parent!' }
});

🧠 Inside the Iframe (child.html)

You can handle communication in multiple ways:

βœ… 1. Receiving message from parent

<script>
  window.addEventListener('message', function(event) {
    console.log('Received from parent:', event.data);
  });
</script>

πŸ” 2. Auto-responding to parent when message is received

<script>
  window.addEventListener('message', function(event) {
    console.log('Received from parent:', event.data);
    // Respond back
    event.source.postMessage(
      { type: 'auto-reply', message: 'Hello from iframe!' },
      event.origin
    );
  });
</script>

πŸ–±οΈ 3. Sending message to parent on button click

<button id="sendBtn">Send message to parent</button>

<script>
  document.getElementById('sendBtn').addEventListener('click', function() {
    window.parent.postMessage(
      { type: 'click-reply', message: 'Button was clicked!' },
      '*' // In production, replace '*' with a specific origin
    );
  });
</script>

🧭 4. Parent listening for messages from iframe

window.addEventListener('message', function(event) {
  console.log('Received from iframe:', event.data);
});

πŸ” Security Tip: Always verify event.origin before trusting incoming messages.


To ensure secure communication between the iframe and the parent, always verify the message origin.

Here’s how to allow multiple trusted domains when listening for messages:

window.addEventListener('message', function (event) {
  const allowedOrigins = ['http://127.0.0.1:5500'];
  if (!allowedOrigins.includes(event.origin)) return;
  // Handle the message...
});

πŸ” Security Tip: Never trust data blindly β€” always validate the origin and structure of the message!


βš™οΈ Options Reference

Option Type Default Description
element HTMLElement undefined The target iframe element. Required if selector is not used.
selector string undefined CSS selector to find the iframe. Alternative to element.
src string undefined URL to load in the iframe. Required if srcdoc is not provided.
srcdoc string '' (empty string) Inline HTML to embed directly into the iframe.
sandbox string 'allow-forms allow-scripts allow-same-origin' Sandbox attribute for iframe security. Use '*' to completely remove the sandbox restrictions.
onStart function null Callback triggered immediately before iframe initialization starts.
onComplete function null Callback triggered after the iframe has loaded.
postMessageMessage object { type: 'referrer', referrer: window.location.origin + window.location.pathname } Message object sent to the iframe after load.
postMessageTargetOrigin string window.location.origin Target origin for postMessage.

🧠 How It Works

  1. Initialization: Create a PostIframe instance with either a src or srcdoc.
  2. Sandbox Handling:
    • If a src is provided, the iframe’s sandbox attribute is set based on the provided option.
    • If sandbox is set to '*', the sandbox attribute is completely removed, lifting all restrictions.
  3. onStart Callback: If provided, the onStart callback is executed immediately before initialization.
  4. Iframe Load & postMessage: Once the iframe loads, PostIframe automatically sends a postMessage to it, and the onComplete callback is executed.
  5. Communication: Inside the iframe, you can listen for the message and respond as needed.
  6. Refreshing Content: Create a new PostIframe instance targeting the same element to refresh the iframe content without duplicate instances.

πŸ“„ License

MIT License β€” free to use in personal and commercial projects.