An Introduction to Cross-Document Messaging in Internet Explorer 8
As of December 2011, this topic has been archived. As a result, it is no longer actively maintained. For more information, see Archived Content. For information, recommendations, and guidance regarding the current version of Internet Explorer, see Internet Explorer Developer Center.
Program Manager, AJAX
This article provides an overview of HTML-5.0–compliant cross-document messaging in Internet Explorer 8. The article is intended for Web developers who are interested in exploring the AJAX feature set in more detail.
This topic contains the following sections:
- The Need for Powerful Custom Pages
- Browsers Can Make Cross-Frame Messaging Easier and Safer
- Cross-Document Messaging: A Functional Overview
Generic Web Portals Give Way to Custom Home Pages
Not long ago, Web users would have visited multiple sites to view all of the content that was of interest to them. This isolated content was soon followed by portal sites that were brimming with content, created in an attempt to satisfy the broadest set of user needs. But what about users interested in a more custom “one-stop shop” browsing experience?
Custom Home Pages Need to Communicate Third-Party Components
The need for custom home pages led to the creation of many personalized composite sites. Many of you probably use a few such as Facebook or the Windows Live home page. Such sites allow different modules or “gadgets” to be embedded in the main HTML. For example, consider Abby, a passionate social-networking user who wants to embed a gas-price gadget in her Live.com home page. That page knows her ZIP code, since she typed that in when signing up. She therefore expects that, when she drops the gadget into her home page, the gadget will show locations of the cheapest gas stations in her neighborhood, all without her having to enter the ZIP code again. That’s easier said than done with today’s service providers.
The preceding scenario is made possible by two techniques that are seeing increased adoption: Embedding a script-based application or gadget from another domain using inline scripts in personalized Web pages, and embedding the gadgets in IFRAME elements.
Inline Scripts: Powerful and Insecure
An embedded script application can access your cookies, keystrokes, passwords, debit-card numbers, and local store, among other personalized information on your home page. In addition, it can send this data back to its domain, crash your browser, and spoof a Web site, among other kinds of attacks. This is possible because a script-based application from a different domain, once embedded, can run in the context of the home-page domain.
Essentially, the script becomes part of the home page and has all of its privileges. This leaves the trust decision to service providers and users:
- Service providers may choose to shoulder the cost of ensuring that their users and sites are protected while letting third-party gadgets communicate with their pages. This is achieved at the cost of expensive service-level agreements maintained with trusted gadget owners and privacy policies. This is, of course, expensive: It comes at the cost of flexibility and scalability, and may require separate domains for the gadgets maintained by the service provider. Only so many gadgets can be supported. In the real world, this model has proven to have limited feasibility.
- Worse results come when users—who often don’t fully understand the power of cross-domain script-based gadgets—are expected to make a trust decision based on a dialog box with a warning.
IFRAME Elements: Secure and Isolated
The other commonly used option for embedding is based on IFRAME elements. In an article titled “Better IFrames Better Sandboxing,” The Open AJAX Alliance highlights the challenge developers face when using IFRAME elements to embed gadgets. An IFRAME element from a domain different from that containing the gadget cannot communicate with the parent page. In addition, IFRAME elements introduce a performance hit since they are essentially a whole new page.
Realizing that this mechanism provides a much tighter envelope for security, developers and service providers go to great lengths to accommodate their users while keeping them secure. Two current workarounds enable communication between an IFRAME-based gadget and its parent page.
With server-side proxying, the gadget sends its data to its domain, which then proxies the data to the personalized home page using a proxy server. The challenge here is that this model quickly becomes expensive; for instance, 100,000 users each with 10 IFRAME-based gadgets will collectively require 1 million proxying requests.
The common workaround of cross-frame messaging uses a URL fragment identifier to swap strings. A fragment identifier is the part of a URL that follows the number sign (#). In the example URL http://www.example.com/page.html#fragmentID, the fragement identifier is fragmentID.
The advantage to this approach is that browsing to a different fragment on the same page doesn’t reload the page and cause a state change. The disadvantage is that the approach violates the tenet, held by many Web developers, that both consistency and reliability are key to robust applications:
- Different browsers allow different URL lengths.
- Some browsers drop fragment identifiers.
- Internet Explorer 8 supports a feature called AJAX Navigation. For sites using the anchor-identifier technique for cross-frame communication, AJAX Navigation associates unintended entries with the browser back button, rendering the button non-functional.
Performance also suffers from the requirement that a proxy frame talk back to its parent, and from the need for the gadget to read a fragment by polling it.
For more information on this technique, see the article “CrossFrame: a Safe Communication Mechanism Across Documents and Across Domains.”
Browsers are late entrants to the game, since the demand for cross-frame messaging and workarounds have existed for a while now. Fortunately, efforts in this area have taken off with the cross-document messaging specification featuring prominently in the W3C HTML 5.0 draft. The draft goes a long way in making cross-frame communication easier for developers while improving user security. The Internet Explorer 8 implementation is based on this draft. We are providing feedback, and working with peers on the committee, to evolve the draft further. By our next beta release, we intend to resolve differences in our implementation and documentation that have arisen from recent updates of the HTML 5.0 draft.
This section is an overview of cross-document messaging and its benefits. You can find some code samples in our AJAX Hands-On Labs. Both the MSDN reference on the postMessage method and the HTML 5.0 draft describe the API in detail.
To illustrate how this feature works, we will revisit the scenario of Abby and her gas-price gadget. The gadget has been created by a developer and uploaded to the gadget site on Abby’s home page. Upon being added to the page, the gadget receives a message with Abby’s ZIP code. The gadget can then read the domain and data, and choose whether to allow or disallow it. The gadget can also respond to the home page with further data.
Here’s how it works.
Step 1: Script on the Origin Domain
An origin document calls the postMessage method on the window of the target document. The postMessage method contains the message—Abby’s ZIP code in this case—and (optionally) the target domain of the document it is trying to post a message to.
Step 2: The Internet Explorer 8 Process
If the target domain is specified but does not match the domain of the target-document window, the call fails.
Otherwise, the domains match, and Internet Explorer:
- Sets the domain attribute of the message event to the origin domain.
- Sets the data property of the message event to Abby’s ZIP code.
- Sets the source to the window of the origin document.
- Fires a message event to the target document.
Step 3: Script on the Target Domain
Target-domain script registers an onmessage event handler, and checks the domain attribute of the message to ensure that it’s allowed. In addition, the script may:
- Check the data to ensure that it’s expected.
- Update its content appropriately or take an action.
- Respond to the origin document through a handle to the window.
Note that when script invokes this method on a window object, the browser sends an onmessage event to the target document with the content of the message stored in the data property. When a target URI is passed into the method, the URI must specify at least a protocol and a host, since the message will be sent only if the target window has the same protocol and host as the specified target URI. The postMessage method call does not return until the event listeners of the target document have finished executing.
For the target site, authors should check the origin domain to ensure that messages are accepted from domains that they expect. Also note that the method provides no way for developers or browsers to match the origin domain with a list of allowable domains. This matching will need to be done by client-side script.
For the origin site, authors should use the optional target-domain argument in a confidential message. Internet Explorer 8 can then ensure that the message is delivered only to the intended recipient.
What Developers Can Expect with Cross-Document Messaging
- Security. The technique works for semi-trusted environments by letting developers choose to receive the message from the domain and discard it if the contents are not secure or expected.
- Reliability. The technique works consistently with no dropped messages, unlike the technique described previously for cross-frame communication.
- Performance. The technique allows duplex communication without relying on the gadget or parent page creating additional proxy IFRAME elements, and without polling the URL for data.
- Easy to deploy. Service providers are not expected to provide server-side proxies or to channel content from server to server. This saves on implementation and hardware as well as bandwidth costs. Also reduced is the need for service providers to maintain SLAs with gadget developers.
- Standardized. One solution will work across all browsers that support it.
- No legacy impact. Being a new feature and not a workaround, this technique should not have unanticipated interaction with legacy code and functionality.
Other Scenarios That This Feature Can Be Used For
- Authorization. Confidential information such as authorization tokens can be sent to components in the page.
- Sizing and positioning gadgets. An IFRAME element has dimensions set by its parent page. In scenarios with variable content, allowing an IFRAME element to request more dimensions will let the parent talk to other components. This will ensure that the parent can evaluate a potential request for a resize or relocation of the gadget.
- CSS Inheritance. Third-party content in an IFRAME element can receive the CSS sent using cross-document messaging and apply the properties.
Technologies That Enhance Cross-Document Messaging Scenarios
The postMessage method currently has no facility for passing structured data of any kind between documents. We believe that if HTML and CSS that is sent using this feature could be safely displayed, the lives of Web developers who want to create compelling applications with this method would be greatly simplified.
Other potential technologies that would work well with cross-document messaging include JSON, which could be parsed safely and natively.
I would like to acknowledge the contributions of the members of the HTML 5.0 committee and thank the Internet Explorer 8 AJAX development and testing teams for implementing the draft in Beta 1. More resources can be found on the Internet Explorer Developer Center.
The HTML 5.0 committee would love to hear feedback on the draft. You can send feedback directly to the Internet Explorer 8 feedback database on the Microsoft Connect Web site. Even better, send your thoughts to the HTML 5.0 alias at email@example.com.