Cross domain HTML5 iframe issue

Cross-domain iframe communication is restricted by the Same-Origin Policy for security. The postMessage method provides a safe way to transfer data between different domains in HTML5.

The Cross-Domain Problem

When an iframe loads content from a different domain, direct JavaScript access is blocked:

// This will throw a security error
let iframeContent = document.getElementById('myIframe').contentDocument;
// Error: Blocked by CORS policy

Solution: Using postMessage

The postMessage API allows secure communication between different origins.

Syntax

targetWindow.postMessage(message, targetOrigin);

Parameters

  • message - Data to send (string, object, etc.)
  • targetOrigin - Target domain URL or '*' for any domain

Complete Example

Parent Page (domain-a.com):

<!DOCTYPE html>
<html>
<head>
    <title>Parent Page</title>
</head>
<body>
    <iframe id="childFrame" src="https://domain-b.com/child.html" width="400" height="200"></iframe>
    
    <script>
    // Listen for messages from iframe
    window.addEventListener('message', function(event) {
        // Verify origin for security
        if (event.origin !== 'https://domain-b.com') return;
        
        console.log('Received from iframe:', event.data);
        alert('Data from iframe: ' + event.data);
    });
    
    // Send message to iframe after it loads
    window.onload = function() {
        setTimeout(function() {
            let iframe = document.getElementById('childFrame');
            iframe.contentWindow.postMessage('Hello from parent!', 'https://domain-b.com');
        }, 1000);
    };
    </script>
</body>
</html>

Child Page (domain-b.com/child.html):

<!DOCTYPE html>
<html>
<head>
    <title>Child Iframe</title>
</head>
<body>
    <h3>This is the iframe content</h3>
    <button onclick="sendToParent()">Send to Parent</button>
    
    <script>
    // Listen for messages from parent
    window.addEventListener('message', function(event) {
        // Verify origin for security
        if (event.origin !== 'https://domain-a.com') return;
        
        console.log('Received from parent:', event.data);
        
        // Send response back to parent
        event.source.postMessage('Response from iframe: ' + event.data, event.origin);
    });
    
    function sendToParent() {
        // Send message to parent window
        window.parent.postMessage('Button clicked in iframe!', 'https://domain-a.com');
    }
    </script>
</body>
</html>

Key Points

  • Always verify origin - Check event.origin for security
  • Use specific domains - Avoid '*' in production
  • JSON data - Complex objects are automatically serialized
  • Bidirectional - Both parent and iframe can send messages

Security Best Practices

window.addEventListener('message', function(event) {
    // Always verify the origin
    let allowedOrigins = ['https://trusted-domain.com', 'https://another-domain.com'];
    
    if (!allowedOrigins.includes(event.origin)) {
        console.warn('Message from untrusted origin:', event.origin);
        return;
    }
    
    // Process the message safely
    console.log('Safe message:', event.data);
});

Conclusion

The postMessage API solves cross-domain iframe communication issues safely. Always verify origins and use specific domain targets for security in production applications.

Updated on: 2026-03-15T23:18:59+05:30

559 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements