Cross-Domain Cross-Document Communication

Elsewhere in the Iframes Tutorial, we demonstrate and describe how to communicate between documents when both containing document and iframed document are on the same domain. Here we show how you can accomplish the same tasks cross-domain.

Even though you can't directly access objects or invoke functions in documents on other domains, you can ask the document on the other domain to do it for you. We present two examples:

How It Works

Both examples use an object literal with a property that specifies the task the other document is to perform:

// Send message with object specifying task
win.postMessage( {'task': 'val'}, 'http://www.example.com' );

The receiving document contains a message handler with a switch case that branches based on the task type sent in postMessage:

// message handler
window.addEventListener('message', function(e) {
    var task = e.data['task']; // task received in postMessage
    switch ( task ) { // postMessage tasks
        case 'height' :
            // Perform 'height' tasks here
            break;
            
        case 'val' :
            // Perform 'val' tasks here
            break;
            
        // more tasks and code ...

Browser Support

Our other postMessage examples include support for Internet Explorer 8. These examples do not. If you want to support Internet Explorer 8, you would just need to include attachEvent when setting up event handling and apply JSON.stringify and JSON.parse when sending and receiving data, as the other examples demonstrate.