2

Looked at this Q & A, but it doesn't solve for my issue: PostMessage with multiple functions or custom callbacks

I need to use postMessage on load and then another within a click event, and the receiver for both would be on the same page (parent).

Is there a method to scope postMessage? or to send multiple postMessages? I can parse the message to trigger specific functions, but how to have multiple posts?

Thanks

Community
  • 1
  • 1
Jason
  • 7,612
  • 14
  • 77
  • 127
  • 1
    You can add an identifier to your message. I've implemented such in a method which uses `postMessage` for cross-domain `localStorage`. See [this answer](http://stackoverflow.com/a/10505907/938089?is-there-any-workaround-to-make-use-of-html5-localstorage-on-both-http-and-https) (full code included, go inspect it ;)) – Rob W Jun 28 '12 at 22:00
  • To send multiple `postMessage` you just call `postMessage` multiple times. What's not working for you? Please post your code. – robertc Jun 29 '12 at 00:29
  • @robertc - I have it fixed now, but the for some reason, initially, the second postMessage was not sending. All working now. – Jason Jun 29 '12 at 12:51
  • jason i have now your same problem. My listener is not catching my iframe postMessage because one is already being triggered. So how to u solve it ? – Simone Campagna Sep 24 '20 at 11:28

1 Answers1

1

My postMessage:

    $.postMessage(
        'layerTitle|'+ layerTitle +'',
        '*',
        parent
      );
...
var getDocHeight = $(document).height();
     $.postMessage(
        'iframeHeight|'+ getDocHeight +'',
        '*',
        parent
      );

and my receive:

$.receiveMessage(
  function(e){
    var message = e.data.split('|');
    if(message[0] == "layerTitle"){
    $('#ui-dialog-title-loginDialog').empty().append(message[1]);
    }
    if(message[0] == "iframeHeight"){
        $('#loginLayer').attr('height', message[1]);
    }

  }
);
Jason
  • 7,612
  • 14
  • 77
  • 127
  • Don't use `e.data.split`, a RegEx or a substring. Otherwise, you will loose data when the message contains the pipe character. – Rob W Jun 29 '12 at 12:59
  • 2
    @RobW - but I control what the message contains - we regularly use pipes for exactly this scenario, because they are not a common character across our work - other than a separator within a string. – Jason Jun 29 '12 at 13:49