HTML and CSS Reference
In-Depth Information
passed in, the JavaScript will throw a syntax error—not helpful,
but something to watch out for if you forget. One last tip: Remem-
ber to wait for the target to finish 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 (event.data == 'favourite instrument?') {
if (event.origin == 'http://remysharp.com') {
event.source.postMessage('brand new clarinet',
¬ event.origin);
} else if (event.origin == 'http://brucelawson.co.uk') {
event.source.postMessage('rusty old trombone',
¬ event.origin);
}
}
}, false);
My script sets an event listener for messages being passed to
the window . Inside the event object is a data property containing
the message that was sent. 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, that is, Bruce's document. This is
useful 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 This code list uses
addEventListener
rather than onmessage
because previous versions of
Firefox didn'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.
What about sending more than strings?
In the examples I've shown you so far, I've passed only strings in
messages back and forth. What if you want to send more than just
a string? What if you have an object with properties and values?
Well, the good news is the specification describes what's sup-
posed to happen when a browser has to safely send data from
 
Search WWH ::




Custom Search