Master Cross-Domain Communication with easyXDM: Full Guide & Code Samples

This article explains why switching iframe pages to HTTPS broke automatic resizing due to cross-origin restrictions, introduces the easyXDM library as a comprehensive solution, and provides step‑by‑step code examples for parent‑child communication, protocol selection, multi‑iframe handling, and debugging techniques.

Baixing.com Technical Team
Baixing.com Technical Team
Baixing.com Technical Team
Master Cross-Domain Communication with easyXDM: Full Guide & Code Samples

0. Background

Due to HTTP hijacking by some ISPs, important iframe popup pages were injected with third‑party ads, blocking content and harming user experience. The company switched these pages to HTTPS, which broke the automatic resizing of the iframe overlay because the parent page remained HTTP, causing a cross‑origin restriction.

1. Cross-Domain Issue

Cross‑origin occurs when protocol, host, or port differ between two URLs, preventing direct JavaScript access to the other page’s objects.

Various cross‑origin solutions exist; for details see “Deep Understanding of Front‑End Cross‑Domain Methods and Principles”. This article recommends easyXDM, which integrates multiple solutions and provides browser compatibility, parallel channels, whitelist, and response handling.

2. easyXDM Usage Example

Parent page ( index.html) core code:

<div id="container"></div>
<div id="output">
    <p>蓝色区域为主页面内容输出区</p>
</div>
<script src="easyXDM.min.js"></script>
<script>
    var showMsg = function(message) {
        document.getElementById('output').innerHTML += "<p>" + message + "</p>";
    };
    var rpc = new easyXDM.Rpc({
        isHost: true,
        remote: 'http://127.0.0.1/easyXDM/iframe.html',
        hash: true,
        protocol: '1',
        container: document.getElementById('container'),
        props: {
            frameBorder: 0,
            scrolling: 'no',
            style: {width: '100%', height: '100px'}
        }
    }, {
        local: {
            echo: function(message) {
                showMsg(message);
            }
        }
    });
</script>

Child page ( iframe.html) core code:

<p>实线框为子页面区域</p>
<button id="btn">点击给主页面发数据</button>
<div id="output"></div>
<script src="easyXDM.min.js"></script>
<script>
    var showMsg = function(message) {
        document.getElementById('output').innerHTML += "<p>" + message + "</p>";
    };
    window.rpc = new easyXDM.Rpc({
        isHost: false,
        protocol: '1',
        //acl: '^(https?:\/\/)?([a-zA-Z0-9\-]+\.)*baixing.com(\/.*)?$',
    }, {
        remote: { echo: {} }
    });
    document.getElementById('btn').onclick = function() {
        rpc.echo('echo from iframe');
    };
</script>

Access via http://localhost/easyXDM/index.html. Because the host of index.html and iframe.html differ, the child page’s manipulation of the parent is cross‑origin; easyXDM enables the communication.

3. easyXDM Principle Analysis

3.1 Principle Explanation

easyXDM wraps underlying mechanisms such as postMessage to achieve bidirectional communication.

3.1.1 Child to Parent Data Transfer

Methods are packaged and sent via postMessage; the parent’s message handler parses and invokes the method. Data fields include defaultXXX (channel identifier), id (request number), method, params (JSON), and jsonrpc (version).

3.1.2 Parent Response Data Transfer

Responses are sent back using postMessage with fields defaultXXX, id, result (JSON), and jsonrpc.

3.2 Parent Page Rpc Configuration

Key parameters: isHost:true (creates iframe), remote URL, container DOM element, props for iframe attributes, hash:true to store channel data in URL hash.

3.3 Child Page Rpc Configuration

Parameters: isHost:false (client), protocol (numeric), optional acl whitelist. The remote section defines methods the child can call on the parent.

3.4 Communication Protocols

easyXDM selects the first compatible protocol: 4 (same domain), 1 (postMessage), 6 (SWF/ActiveX), 5 (frameElement), 2 (remoteHelper), 0 (image fallback).

4. More Features

4.1 Request‑Response Handling

Adding a return value to the parent’s echo function and handling the callback in the child.

new easyXDM.Rpc({
    // ...
}, {
    local: {
        echo: function(message) {
            document.getElementById('output').innerHTML += "<p>" + message + "</p>";
            return {'msg': 'echo done from index'};
        }
    },
    remote: {}
});
document.getElementById('btn').onclick = function() {
    rpc.echo('echo from iframe', function(response) {
        showMsg(response.msg);
    }, function(errorObj) {
        alert('error');
    });
};

4.2 Parent Calls Child Method

Register pingIframe in the child’s local and invoke it from the parent via the remote configuration.

window.rpc = new easyXDM.Rpc({
    // ...
}, {
    local: {
        pingIframe: function(message) {
            showMsg(message);
            return {'msg': 'pong from iframe'};
        }
    },
    remote: { echo: {} }
});
document.getElementById('btn').onclick = function() {
    rpc.pingIframe('ping from index', function(response) {
        showMsg(response.msg);
    }, function(errorObj) {
        alert('error');
    });
};

4.3 Multiple Page Communication

Create separate RPC objects for each iframe and bind them to different buttons, allowing parallel cross‑origin interactions.

var generateRpc = function(url) {
    return new easyXDM.Rpc({
        isHost: true,
        remote: url,
        hash: true,
        protocol: '1',
        container: document.getElementById('container'),
        props: {frameBorder:0, scrolling:'no', style:{width:'100%', height:'100px'}}
    }, {
        local: { echo: function(message){ showMsg(message); return {'msg':'echo done from index'}; } },
        remote: { pingIframe: {} }
    });
};
var bindRpc = function(rpc, btnId) {
    document.getElementById(btnId).onclick = function() {
        rpc.pingIframe('ping from index', function(response){ showMsg(response.msg); }, function(){ alert('error'); });
    };
};
var rpc1 = generateRpc('http://127.0.0.1/easyXDM/iframe.html');
bindRpc(rpc1, 'btn');
var rpc2 = generateRpc('http://127.0.0.1/easyXDM/iframe2.html');
bindRpc(rpc2, 'btn2');

4.4 Preserve RPC After iframe Navigation

When hash is false, channel parameters are lost after navigation. The following jQuery snippet appends the current hash to form actions and link hrefs to retain the channel.

$(document).ready(function(){
    $('form.easyxdm').each(function(){
        var $form = $(this);
        var action = $form.attr('action');
        $form.attr('action', action + window.location.hash);
    });
    $('a.easyxdm').each(function(){
        var $link = $(this);
        var href = $link.attr('href');
        $link.attr('href', href + window.location.hash);
    });
});

5. Debugging easyXDM

Clone the full repository from GitHub, replace easyXDM.min.js with easyXDM.debug.js, and use Chrome DevTools for JavaScript debugging.

6. Conclusion

The easyXDM README is outdated; this article summarizes practical usage, code examples, and troubleshooting for developers needing cross‑origin iframe communication.

7. References

easyXDM official site

easyXDM GitHub repository

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptcross-domainiframepostMessageeasyXDM
Baixing.com Technical Team
Written by

Baixing.com Technical Team

A collection of the Baixing.com tech team's insights and learnings, featuring one weekly technical article worth following.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.