> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dynamic.xyz/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Iframe Integration

<Card title="Recommended: JavaScript SDK with React Hooks" icon="react" color="#4779FE">
  For new React apps, we recommend the JavaScript SDK with React Hooks (`@dynamic-labs-sdk/react-hooks`) instead of the legacy React SDK documented here. The JS SDK comes with many benefits such as a much smaller bundle size and other optimizations. Use the [React quickstart (JavaScript SDK)](/javascript/reference/react-quickstart) to get started.
</Card>

## 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

```bash theme={"system"}
npm install @dynamic-labs/iframe-setup
```

## 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:

```tsx theme={"system"}
import { setupIframe } from '@dynamic-labs/iframe-setup';

const iframeURL = new URL('https://iframe.com');

if (typeof window !== 'undefined') {
  iframeURL.searchParams.set('initial-parent-url', window.location.href);
}

const App = () => {
  const iframeRef = useRef<HTMLIFrameElement>(null);

  useEffect(() => {
    const cleanUp = setupIframe(iframeRef.current!, iframeURL.origin);

    return () => {
      cleanUp();
    };
  }, []);

  return (
    <div>
      <iframe ref={iframeRef} src={iframeURL.toString()} />
    </div>
  );
};
```

### Iframe Application Setup

Inside your iframe application, initialize the SDK:

```tsx theme={"system"}
import { DynamicContextProvider } from '@dynamic-labs/sdk-react-core';
import { setupInsideIframe } from '@dynamic-labs/utils';

// Initialize as early as possible in your iframe application
setupInsideIframe();

const App = () => {
  return (
    <DynamicContextProvider>{/* Your application */}</DynamicContextProvider>
  );
};
```

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()](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) API.

The `setupIframe` function in the parent page sets up several event handlers:

1. **URL Update Handler**: Watches for URL changes in the parent page and communicates them to the iframe
2. **Open URL Handler**: Allows the iframe to request the parent page to open URLs
3. **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:

```tsx theme={"system"}
import { FC, useEffect, useMemo, useRef } from 'react';

import { setupIframe } from '@dynamic-labs/iframe-setup';

import { Button, Typography } from '../../components';

export const IFrameView: FC = () => {
  const iframeRef = useRef<HTMLIFrameElement>(null);

  const iframeUrl = useMemo(() => {
    const url = new URL(window.location.href);

    url.pathname = '';

    url.searchParams.set('initial-parent-url', window.location.href);

    return url;
  }, []);

  useEffect(() => {
    const iframe = iframeRef.current;

    if (!iframe) return;

    const teardown = setupIframe(iframe, iframeUrl.origin);

    return () => {
      teardown();
    };
  }, []);

  return (
    <div className='iframe-view'>
      <div className='iframe-view--header'>
        <Typography variant='title-3'>Iframe Example</Typography>
      </div>

      <iframe
        src={iframeUrl.toString()}
        className='iframe-view--iframe'
        title='Dynamic Demo'
        ref={iframeRef}
        sandbox='allow-scripts allow-same-origin allow-modals'
      />
    </div>
  );
};
```

## 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](https://www.npmjs.com/package/@dynamic-labs/iframe-setup).

## Troubleshooting

### Common Issues

1. **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`

2. **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

3. **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
