質問

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?

役に立ちましたか?

解決

You never defined receiveMessage, instead you tried to use $.receiveMessage. You're miss-using the jquery methods, you don't always need to wait for the dom to be ready. You also don't need jquery at all for this.

<script type="text/javascript">
    window.addEventListener("message", receiveMessage, false);

    //$(function () {
    function receiveMessage(event){  
        if (event.origin == "http://origindomain.com" && event.data == "scrollTop") {
            window.scrollTo(0, 0);
        }
    }
    //});
</script>

If you installed a jQuery plugin that defines $.receiveMessage, then you likely didn't need the first line at all because the plugin should take care of that. But, i'm not sure why a plugin would be needed for this functionality.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top