Iframe Integration
Overview
When building web applications that incorporate the Dynamic SDK, there are scenarios where you might need to embed your application within an iframe. This could be for various reasons:
- Embedding your application in a third-party site
- Isolating the authentication flow in a separate domain
- Creating a secure environment for wallet operations
- Implementing a widget that can be embedded in multiple sites
The @dynamic-labs/iframe-setup
package enables the Dynamic SDK to work within iframe environments by establishing communication channels between the parent page and the iframe.
Installation
Implementation Guide
Parent Page Setup
Configure the parent page that will contain the iframe. You need to pass the parent URL to the iframe using the initial-parent-url
query parameter:
Iframe Application Setup
Inside your iframe application, initialize the SDK:
Once both steps are completed, the Dynamic SDK will be fully operational within your iframe environment.
Technical Details
The iframe integration works by establishing a communication channel between the parent page and the iframe using the Window.postMessage() API.
The setupIframe
function in the parent page sets up several event handlers:
- URL Update Handler: Watches for URL changes in the parent page and communicates them to the iframe
- Open URL Handler: Allows the iframe to request the parent page to open URLs
- App Focus Handler: Notifies the iframe when the parent page gains focus
Inside the iframe, the setupInsideIframe
function initializes the necessary platform services to communicate with the parent page.
This bidirectional communication ensures that:
- The iframe can navigate to external URLs through the parent page
- The iframe is aware of URL changes in the parent page
- The iframe can respond to focus events from the parent page
Demo
You can see a practical implementation of the iframe setup in the Dynamic Auth demo application:
Alternative Implementation
If you’re unable to install the package in the parent application, you can directly implement the setupIframe
functionality by copying the code from the package source.
Troubleshooting
Common Issues
-
Communication Issues Between Parent and Iframe
- Verify that both pages are using the same origin or you’ve properly configured CORS
- Ensure the
initial-parent-url
parameter is correctly set - Check that the iframe has the correct sandbox attributes:
allow-scripts allow-same-origin allow-modals
-
Authentication Problems in Iframe
- Some authentication methods may have restrictions in iframe environments due to security policies
- Ensure you’re using the latest version of the Dynamic SDK for the best iframe compatibility
-
Content Security Policy (CSP) Restrictions
- If your application enforces CSP, you’ll need to allow communication between the parent and iframe domains
- Add the iframe domain to your
connect-src
directive