A powerful web component for embedding and controlling iframe content
The preview-iframe
component is a custom web component that extends the functionality of standard iframes with additional features like lazy loading, zoom controls, fullscreen support, and loading states.
Load content only when needed using Intersection Observer
Built-in zoom in/out functionality
Toggle fullscreen mode with a single click
Visual feedback during content loading
Built-in URL sanitization and sandbox support
Adapts to different screen sizes
Include the component script in your HTML file:
<script type="module" src="preview-iframe.js"></script>
<preview-iframe
src="https://example.com"
width="100%"
height="600"
loading="lazy"
show-controls="true"
></preview-iframe>
Attribute | Type | Default | Description |
---|---|---|---|
src |
string | - | URL of the content to load in the iframe |
width |
string | 100% | Width of the component |
height |
string | 400px | Height of the component |
loading |
string | lazy | Loading behavior: "lazy" or "eager" |
sandbox |
string | - | Sandbox restrictions for the iframe |
allow |
string | - | Feature policy for the iframe |
show-controls |
boolean | false | Show/hide the control buttons |
<preview-iframe
src="https://codepen.io"
width="100%"
height="500"
show-controls="true"
sandbox="allow-scripts allow-same-origin allow-forms"
style="--background-color: #1e1e1e; border-radius: 12px;"
></preview-iframe>
<preview-iframe
src="https://example.com"
width="100%"
height="600"
loading="lazy"
show-controls="true"
></preview-iframe>
loading="lazy"
, the iframe content will only load when the component enters the viewport, improving page performance.
// Get reference to the component
const previewIframe = document.querySelector('preview-iframe');
// Set custom content
previewIframe.setContent('<h1>Hello World</h1><p>Custom content</p>');
// Listen for events
previewIframe.addEventListener('preview-loaded', () => {
console.log('Content loaded successfully');
});
previewIframe.addEventListener('preview-error', () => {
console.error('Error loading content');
});
Event | Description | When Fired |
---|---|---|
preview-loaded |
Fired when iframe content loads successfully | On iframe load event |
preview-error |
Fired when iframe content fails to load | On iframe error event |
Customize the appearance using CSS custom properties:
preview-iframe {
--background-color: #f8f9fa; /* Background color of the iframe */
}
/* Or inline */
<preview-iframe
style="--background-color: #1a1a1a;"
src="https://example.com"
></preview-iframe>
sandbox
attributes when loading external content to prevent security issues.
<!-- For static content -->
<preview-iframe
sandbox="allow-same-origin"
src="https://trusted-site.com"
></preview-iframe>
<!-- For interactive content -->
<preview-iframe
sandbox="allow-scripts allow-same-origin allow-forms"
src="https://trusted-interactive-site.com"
></preview-iframe>
This component uses modern web standards and requires: