ResponsiveIframeController
Purpose
To make seamless, responsive iframes that resize themselves to the size of their content.
This behaviour uses two controllers.
ResponsiveIframeWrapperController
ResponsiveIframeBodyController
Actions
Action | Purpose |
---|---|
- | - |
Targets
Target | Purpose | Default |
---|---|---|
- | - | - |
Classes
Class | Purpose | Default |
---|---|---|
- | - | - |
Values
Value | Type | Description | Default |
---|---|---|---|
- | - | - | - |
Events
Event | When | Dispatched on | event.detail |
---|---|---|---|
- | - | - | - |
Side Effects
ResponsiveIframeWrapperController
- Adds an event listener for
message
on thewindow
for messages posted on the iframe it is attached to.
ResponsiveIframeBodyController
- Uses a ResizeObserver to observe the inner iframe
window
size. - Passes
messages
to the iframe document'swindow.parent
to get messages from the iframe body, to the outer document.
How to Use
You need to have access to both the frame content, and the parent iframe.
On the parent iframe
HTML
<iframe src="/iframe/content/path" frameborder="0" data-controller="iframe--responsive-wrapper">
</iframe>
In the content page
HTML
<html lang="en">
<head>
<meta data-controller="iframe--responsive-body"/>
</head>
...
</html>
The responsive-body
controller then installs a resize observer that uses the message-passing ability of the browser to pass messages to the enclosing parent document. Every time the document inside the iframe gets resized, it will report the recalculated size to the parent scope.
The parent scope listens for messages from iframes, and when it receives a message with the name
iframe-body
, it will set the height
of the iframe to the value passed.
You can then set a max-height
on the <iframe>
to make sure it fits your design and never grows too large.
You can either fix the width, or let it be responsive - the ResizeObserver inside the <iframe>
will handle any size changes and adjust the height automatically to compensate.