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.
- Load iframe via
srcorsrcdoc - Secure sandboxing support with flexible options
- Automatically send a
postMessageto the iframe after load - Execute an
onStartcallback right when initialization begins - Callback on completion renamed to
onCompletefor clarity - Prevent duplicate instances on the same iframe element
- Easily refresh the iframe content by creating a new instance
Include the script directly in your HTML:
<script src="post-iframe.min.js"></script><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><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>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'
});new PostIframe({
selector: '#myFrame',
src: 'child.html',
postMessageMessage: { type: 'greeting', message: 'Hello from parent!' }
});You can handle communication in multiple ways:
<script>
window.addEventListener('message', function(event) {
console.log('Received from parent:', event.data);
});
</script><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><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>window.addEventListener('message', function(event) {
console.log('Received from iframe:', event.data);
});π Security Tip: Always verify
event.originbefore 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
originand structure of the message!
| 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. |
- Initialization: Create a PostIframe instance with either a
srcorsrcdoc. - Sandbox Handling:
- If a
srcis provided, the iframeβssandboxattribute is set based on the provided option. - If
sandboxis set to'*', the sandbox attribute is completely removed, lifting all restrictions.
- If a
- onStart Callback: If provided, the
onStartcallback is executed immediately before initialization. - Iframe Load & postMessage: Once the iframe loads, PostIframe automatically sends a
postMessageto it, and theonCompletecallback is executed. - Communication: Inside the iframe, you can listen for the message and respond as needed.
- Refreshing Content: Create a new PostIframe instance targeting the same element to refresh the iframe content without duplicate instances.
MIT License β free to use in personal and commercial projects.