Tuesday, September 11, 2012

iframe Communication

iFrame is used on web page to mashup content from same or different domains, same domain looks straightforward, but same-origin-policy prevents direct communication between iframe(s) or parent window if the origins are different.

Same domain:

1. child iframe calls parent window JS function:
window.parent.functionName()

2. parent window calls iframe JS function:
document.getElementById('frameName').contentWindow.functionName()
Other alternatives for above JS code 
window.frames['frameName'].contentWindow.functionName();

var el = document.getElementById('frameName');
if(el.contentWindow) {
    el.contentWindow.functionName();
}
else if(el.contentDocument) {
    //el.contentDocument.functionName();
    el.contentDocument.defaultView.functionName();
}


Cross domain:
HTML5 Web Messaging http://dev.w3.org/html5/postmsg/#web-messaging defines cross document messaging to address this issue, and as of writing, it is supported in most browsers (except for IE7 and below) for iFrame-to-parent-window communication (IE has not implemented cross window/tab messaging yet). The standard API is window.postMessage(message, targetOrigin [,transfer]).

However if we need support old browsers for cross domain messaging, we need look at other hacks or solutions.
  1. Hashchange of iframe or parent window. For instance, parent window change iframe window's fragment (hashchange), and iframe polling the change (or onhashchange event) to get passed fragment identifier
  2. hidden proxy iframe, hashchange based
  3. hidden proxy iframe, resize event based (see https://github.com/ternarylabs/porthole/)
  4. Flash (some library uses flash fallback)
Libraries using postMessage with fallbacks
Client to server cross domain:
  1. proxy server
  2. JSONP
  3. CORS (Cross origin resource sharing)
Reference
http://softwareas.com/cross-domain-communication-with-iframes
http://stackoverflow.com/questions/6309674/wrapping-postmessage-in-jquery


No comments:

Post a Comment