HTML and CSS Reference
In-Depth Information
var t = document.getElementsByTagName('iframe')[0];
t.contentWindow.postMessage('favourite instrument?',
¬ '');
The target origin argument being passed to postMessage is
required. This must match the origin of your contentWindow object
(the target window, my document in this example) and it must be
supplied. If the origins don't match, a security error will be thrown,
stopping the script from continuing. If the origin isn't passed in,
the JavaScript will throw a syntax error—not helpful, but some-
thing to watch out for if you forget. One last tip: Remember to
wait for the target to flnish loading. The target is still a document
that needs to be parsed and loaded. If the browser hasn't loaded
the document and you try to send it a message, the JavaScript
will fail entirely with a similar syntax error.
My document is being referenced via an iframe on Bruce's page,
and it contains the following JavaScript:
window.addEventListener('message, function (event) {
if ( == 'favourite instrument?') {
if (event.origin == '') {
event.source.postMessage('brand new clarinet',
¬ event.origin);
} else if (event.origin == '') {
event.source.postMessage('rusty old trombone',
¬ event.origin);
}, false);
My script sets an event listener listening for messages being
passed to the window . Inside the event object is a data property
containing the message that was passed in. Along with the data
property, there are a number of other useful properties sitting
inside the event: origin and source .
The event.origin gives me the domain that the message came
from. I can use this, as I have in the previous code listing, to
determine whether I want to process the message. This is policy
control at a very rudimentary level.
The event.source points back to the window object making the
original call to my document, i.e., Bruce's document. This is use-
ful to be able to communicate back and forth. Of course your
onmessage event handler could do a lot more, like make an Ajax
request to the server on the same domain.
note The previous
code list uses
addEventListener rather
than onmessage because Fire-
fox doesn't appear to respond
to onmessage on the window
object. This is best practice
anyway, but it would mean we
also need to hook IE using
attachEvent , which I've not
included in my example.
Search WWH ::

Custom Search