Embedding an iframe
Embedding an iframe allows you to integrate external applications into your web application. Below is information on how to integrate an iframe and set up message communication using the postMessage
method.
Basic iframe integration
<!DOCTYPE html>
<html>
<head>
<style>
.container {
height: 100vh;
display: flex;
flex-direction: column;
}
iframe {
flex-grow: 1;
border: none;
}
</style>
</head>
<body>
<div class="container">
<!-- create iframe using js -->
<div class="controls">
<button id="openModalBtn">Open in modal window</button>
<span id="messageDisplay"></span>
</div>
<!-- or html -->
<iframe src="/app" width="100%" height="100%"></iframe>
</div>
</body>
</html>
Modal window integration
Creating a modal with an iframe
Copydocument.getElementById('openModalBtn').addEventListener('click', function() {
const modal = document.createElement('div');
modal.style.position = 'fixed';
modal.style.top = '0';
modal.style.left = '0';
modal.style.width = '100%';
modal.style.height = '100%';
modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
const iframe = document.createElement('iframe');
iframe.src = '/app';
iframe.style.width = '95%';
iframe.style.height = '95%';
modal.appendChild(iframe);
document.body.appendChild(modal);
});
Message types
MODAL_CLOSING
Allows closing the modal window safely preventing accidental data loss.
Parent application behavior
document.getElementById('closeBtn').addEventListener('click', function() {
iframe.contentWindow.postMessage({ type: 'MODAL_CLOSING' }, '*');
});
iframe application behavior
window.addEventListener('message', (event) => {
if (event.data.type === 'MODAL_CLOSING') {
// Check for unsaved changes
if (hasUnsavedChanges) {
const shouldClose = window.confirm('You have unsaved changes. Close anyway?');
window.parent.postMessage({
type: 'MODAL_CLOSE_RESPONSE',
canClose: shouldClose
}, '*');
} else {
window.parent.postMessage({
type: 'MODAL_CLOSE_RESPONSE',
canClose: true
}, '*');
}
}
});
SCHEMA_CHANGED
Allows the iframe to notify the parent application about data modifications.
iframe application behavior
// In a state management selector or change detection logic
if (window !== window.parent) {
window.parent.postMessage({
type: 'SCHEMA_CHANGED',
hasChanges: detectChanges(),
changedEntities: ['seats', 'rows', 'sections']
}, '*');
}
Parent application behavior
window.addEventListener('message', function (event) {
if (event.data.type === 'SCHEMA_CHANGED') {
console.log('Schema changed:', event.data.hasChanges);
// Update UI, trigger save prompts, etc.
updateSaveStatus(event.data.hasChanges);
}
});