开发者

Wrapping postMessage in jQuery

开发者 https://www.devze.com 2023-03-12 06:08 出处:网络
I\'m trying to learn jQuery, I want to make a simple postMessage client. Is it possible to wrap it in jquery? The first alert works, but the second does not.

I'm trying to learn jQuery, I want to make a simple postMessage client. Is it possible to wrap it in jquery? The first alert works, but the second does not.

I'm trying to modify this code: http://austinchau.blogspot.com/2008/11/html5-cross-document-messaging.html

$(docu开发者_运维问答ment).ready(function() {

   $('#submit_button').click(function() {
      var data = $('#message').val();
      window.postMessage('1st' + data);
      alert(data);
   });

    var onmessage = function(e) {
      var data = e.data;
      var origin = e.origin;
      document.getElementById('display').innerHTML = data;
      alert('2nd' + data);
    };

    if (typeof window.addEventListener != 'undefined') {
      window.addEventListener('message', onmessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
      window.attachEvent('onmessage', onmessage);
    }
});

Edit: I know there are many plugins available to do this, but I'm doing this as a learning process.


postMessage is used to communicate between different pages or windows (or iframes). You are posting a message to the same window. As you've seen, nothing happens.

If you go back to the original blog post, the author creates and displays two iframes and then posts messages between them.


The second argument to postMessage is now required. Your code could be changed to this:

   window.postMessage('1st' + data, document.location);

Which works because you are posting to your own window. To post to another window, use this:

   popup = window.open('http://example.com/');
   popup.postMessage("Hi!", 'http://example.com/')

Further Reading:

  • http://ejohn.org/blog/postmessage-api-changes/

  • http://dev.w3.org/html5/postmsg/#web-messaging

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消