HTML and CSS Reference
In-Depth Information
window.addEventListener(“message”, ReceiveMessage, false);
});
function ReceiveMessage(evt) {
if (evt.origin != targetOrigin)
return;
$(“#divReceived”).append(evt.origin + “ : “ + evt.data + “<br/>”);
evt.source.postMessage(“Data received successfully!”, evt.origin);
}
Earlier it was mentioned that the postMessage API offers a secure way to do cross-document
messaging. Here you can understand why. The author of the main page doesn't get direct access to the
target web page: everything is mediated by the code from the target web page.
The code in Listing 11-5 wires an event handler—
ReceiveMessage()
—to the target window's
message
event. The
ReceiveMessage()
event-handler function then performs checking on the
origin
property and,
if the data is being received from an expected origin, appends the data to a
<div>
element. A success
message is sent back to the main web form using the
source
property of the event parameter. The
source
property refers to the
window
object of the main web form.
n
Note
Unless you're developing a general-purpose service that is exposed for public consumption, it's a good
idea to include a white-listing mechanism in applications that use the postMessage API. In the absence of such a
white-list, any origin can send data to your web pages, and it will be processed by the message event handler. If
your white-list is small, you can store it in an array; otherwise an XML file or a database table is a better choice.
Using postMessage with the window Object
Using the postMessage API with the
window
object is similar to using it with the
<iframe>
element. The only
difference is that instead of the
contentWindow
property, you need to use the
window
reference returned by
the
window.open()
method. Listing 11-6 makes this clear.
Listing 11-6.
Using
postMessage()
with
window.open()
$(document).ready(function () {
...
var targetWindow = window.open(targetOrigin + “/Target.aspx”);
window.addEventListener(“message”, ReceiveMessage, false);
$(“#btnSend”).click(function () {
targetWindow.postMessage($(“#txtData”).val(), targetOrigin);
});
});
This code resides in the main web form. Notice that this time, instead of using an
<iframe>
to load the
target web form, you use the
window.open()
method. The
open()
method accepts the URL of the target web
form and returns a reference to the
window
object of the target web form. Once a reference to the target
window is obtained, it's used in exactly the same manner as in the
<iframe>
example discussed earlier.