Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
143023864X_HT5.pdf
Скачиваний:
8
Добавлен:
21.02.2016
Размер:
7.98 Mб
Скачать

CHAPTER 6 USING THE COMMUNICATION APIS

In some browsers, the limitations on JavaScript objects that can be sent with postMessage are the same as those for JSON data. In particular, data structures with cycles may not be allowed. An example of this is a list containing itself.

Framebusting

Framebusting is a technique for ensuring that your content is not loaded in an iframe. An application can detect that its window is not the outermost window (window.top) and subsequently break out of its containing frame, as shown in the following example.

if (window !== window.top) { window.top.location = location;

}

Browsers supporting the X-Frame-Options HTTP header will also prevent malicious framing for resources that set that header to DENY or SAMEORIGIN. However, there may be certain partner pages that you want to selectively allow to frame your content. One solution is to use postMessage to handshake between cooperating iframes and containing pages, as shown in the Listing 6-11.

Listing 6-11. Using postMessage in an iframe to Handshake with a Trusted Partner Page

var framebustTimer;

var timeout = 3000; // 3 second framebust timeout

if (window !== window.top) { framebustTimer = setTimeout(

function() {

window.top.location = location; }, timeout);

}

window.addEventListener(“message”, function(e) { switch(e.origin) {

case trustedFramer: clearTimeout(framebustTimer); break;

}

), true);

Summary

In this chapter, you have seen how HTML5 Cross Document Messaging and XMLHttpRequest Level 2 can be used to create compelling applications that can securely communicate cross-origin.

First, we discussed postMessage and the origin security concept—two key elements of HTML5 communication—and then we showed you how the postMessage API can be used to communicate between iframes, tabs, and windows.

Next, we discussed XMLHttpRequest Level 2—an improved version of XMLHttpRequest. We showed you in which areas XMLHttpRequest has been improved; most importantly in the readystatechange events area. We then showed you how you can use XMLHttpRequest to make crossorigin requests and how to use the new progress events.

156

CHAPTER 6 USING THE COMMUNICATION APIS

Finally, we wrapped up the chapter with a few practical examples. In the next chapter, we’ll demonstrate how HTML5 WebSockets enables you to stream real-time data to an application with incredible simplicity and minimal overhead.

157