HTML and CSS Reference
In-Depth Information
The main web form contains jQuery code that handles the Send button's
click
event. This code is
shown in Listing 11-3.
Listing 11-3.
Sending Data to the Target Web Form
var targetOrigin = “http://localhost:1052”;
$(document).ready(function () {
if (!Modernizr.postmessage) {
alert(“This browser doesn't support the HTML5 postMessage API!”);
return;
}
var targetWindow = $(“#target”).get(0).contentWindow;
window.addEventListener(“message”, ReceiveMessage, false);
$(“#btnSend”).click(function () {
targetWindow.postMessage($(“#txtData”).val(), targetOrigin);
});
});
This code uses the Modernizr library to detect whether the browser supports the postMessage API.
This is done using the
postmessage
property of the
Modernizr
object. As mentioned earlier, you need a
handle to the target window in order to send data to the target web form. To get the
window
object attached
to the
<iframe>
element, you use the
contentWindow
property of the
<iframe>
DOM element.
If you're interested in receiving the return value sent by the target web form, you need to wire an event
handler for the
message
event. The
addEventListener()
method can wire an event-handler function—
ReceiveMessage
, in this example—to the main window's
message
event.
The Send button's
click
event handler calls the
postMessage()
method on the target
window
object.
The first parameter of the
postMessage()
method is the data you wish to pass to the target web form. The
second parameter is the origin of the target web form.
The
ReceiveMessage
() event-handler function is shown in Listing 11-4.
Listing 11-4.
Handling the
message
Event in the Main Web Form
function ReceiveMessage(evt) {
if (evt.origin != targetOrigin)
return;
$(“#divReceived”).append(evt.origin + “ : “ + evt.data + “<br/>”);
}
This code first checks whether the origin of the message being received is a permitted one. It does so
using the
origin
property of the event parameter. This way, the developer of the other web site (the web
site whose service is being consumed by your web site) can
white-list
only certain origins. If the origin
doesn't belong to the approved set, you can simply ignore it during further processing.
To access the data sent by the target web form, the code uses the
data
property of the event parameter.
The origin and the data are appended to the
<div>
element using the jQuery
append()
method.
The target web form contains jQuery code that receives the data sent by the main web form. This code
is shown in Listing 11-5.
Listing 11-5.
Receiving the Data Sent by the Main Web Form
var targetOrigin = “http://localhost:1050”;
$(document).ready(function () {
...