I have a page that listens to messages from a page on another domain (via an iframe) using window.postMessage. My previous code works:
<script type="text/javascript">
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
if (event.data == "scrollTop"){
window.scrollTo(0,0);
}
}
</script>
Even though the above code works, I need to restrict it from executing except when the .postMessage is from a specific domain (http://origindomain.com), so I changed the above code to the following:
<script type="text/javascript">
window.addEventListener("message", receiveMessage, false);
$(function () {
$.receiveMessage(function(event){
if (event.data == "scrollTop") {
window.scrollTo(0, 0);
}
// An optional origin URL (Ignored where window.postMessage is unsupported).
}, 'http://origindomain.com' );
});
});
</script>
This second approach doesn't work. The error output in Firebug console is:
ReferenceError: receiveMessage is not defined
window.addEventListener("message", receiveMessage, false);
jQuery is not my first language, so if the solution is obvious I apologize. Why is the receiveMessage() callback undefined?
$.receiveMessage, but not areceiveMessage.receiveMessageby name, but you have not defined such a function.