Friday 17 April 2015

Cross-Domain Communication by iFrame Usinig javascript (onHashchangeEvent)

In iframe if we are on same domain then it's not to difficult to sending data between application and iFrame but what we do when both are different domain so there is something trick or a concept to sending data between different domain.

i Using javascript onhashchange event and first some code that will encode arbitrary data (as long as it’s JSON encodable) and put it into the hash value of the desired iframe.

function sendIFrameData( frame, data ){
    var idx = frame.src.indexOf('#'), url = frame.src;
    if ( idx > -1 ){
        url = url.substr(0, idx);
    }
   
    frame.src = url + '#' + window.btoa(JSON.stringify(data));
}

Now on the iframe side, let’s write a function to decode the data.

function getHashData(){
    var data;
    try {
        data = JSON.parse(window.atob(window.location.hash.substr(1)));
    } catch( e ){}
    return data;
}



In my application i add this code this is working for me ... !
iframe on my domain, and send it some messages.

// send arbitrary data to the iframe


sendIFrameData( frame, { text: "Hello world" } );
setTimeout(function(){
    sendIFrameData( frame, { text: "How are you today?" } );
}, 2000);





The iframe will listen to the hashchange event and log out what it hears.


var el = document.getElementById('log');
function showMsg(){
    var data = getHashData();
    if ( data && data.text ){
        el.innerHTML += "<br/>Received msg: " + data.text;
    }
}

// in case we sent data on first load.
showMsg();
// when the hash changes we check the new data and print it out
window.addEventListener('hashchange', function(){
    showMsg();
});

No comments:

Salesforce CRM vs. Zoho: A Comparative Analysis

Introduction: Selecting the right customer relationship management (CRM) software is crucial for businesses seeking to streamline their sal...