filter messages in receiveMessage javascript





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







3















I'm establishing cross-domain communication with JS's postMessage method. An embedded iframe is sending the message and the parent window is receiving it. The issue is that even after checking for origin in receiveMessage (which reduced the number of messages received by a large amount), I'm still receiving two messages, one that I'm posting, and another which was written quite some time ago for a different purpose. So, I can't really modify this other (unwanted) message's postMessage method. Is there a way in the postMessage method or receiveMessage, for that matter, which can help in identifying which one is mine? Maybe some extra parameter or configuration I'm missing here?



Code for postMessage (in the embedded iframe):



window.parent.postMessage("Hello world!", "*");


Code for receiveMessage (in the parent window):



    window.addEventListener("message", receiveMessage, false);
function receiveMessage(e) {
var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
var secureHost = "https" + reliableHost;
var notSecureHost = "http" + reliableHost;
if (e.origin.indexOf(secureHost) != -1 || e.origin.indexOf(notSecureHost) != -1) {
var data = e.data;
console.log(data);
console.log(e.source);
// filter the other event
}
}









share|improve this question





























    3















    I'm establishing cross-domain communication with JS's postMessage method. An embedded iframe is sending the message and the parent window is receiving it. The issue is that even after checking for origin in receiveMessage (which reduced the number of messages received by a large amount), I'm still receiving two messages, one that I'm posting, and another which was written quite some time ago for a different purpose. So, I can't really modify this other (unwanted) message's postMessage method. Is there a way in the postMessage method or receiveMessage, for that matter, which can help in identifying which one is mine? Maybe some extra parameter or configuration I'm missing here?



    Code for postMessage (in the embedded iframe):



    window.parent.postMessage("Hello world!", "*");


    Code for receiveMessage (in the parent window):



        window.addEventListener("message", receiveMessage, false);
    function receiveMessage(e) {
    var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
    var secureHost = "https" + reliableHost;
    var notSecureHost = "http" + reliableHost;
    if (e.origin.indexOf(secureHost) != -1 || e.origin.indexOf(notSecureHost) != -1) {
    var data = e.data;
    console.log(data);
    console.log(e.source);
    // filter the other event
    }
    }









    share|improve this question

























      3












      3








      3








      I'm establishing cross-domain communication with JS's postMessage method. An embedded iframe is sending the message and the parent window is receiving it. The issue is that even after checking for origin in receiveMessage (which reduced the number of messages received by a large amount), I'm still receiving two messages, one that I'm posting, and another which was written quite some time ago for a different purpose. So, I can't really modify this other (unwanted) message's postMessage method. Is there a way in the postMessage method or receiveMessage, for that matter, which can help in identifying which one is mine? Maybe some extra parameter or configuration I'm missing here?



      Code for postMessage (in the embedded iframe):



      window.parent.postMessage("Hello world!", "*");


      Code for receiveMessage (in the parent window):



          window.addEventListener("message", receiveMessage, false);
      function receiveMessage(e) {
      var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
      var secureHost = "https" + reliableHost;
      var notSecureHost = "http" + reliableHost;
      if (e.origin.indexOf(secureHost) != -1 || e.origin.indexOf(notSecureHost) != -1) {
      var data = e.data;
      console.log(data);
      console.log(e.source);
      // filter the other event
      }
      }









      share|improve this question














      I'm establishing cross-domain communication with JS's postMessage method. An embedded iframe is sending the message and the parent window is receiving it. The issue is that even after checking for origin in receiveMessage (which reduced the number of messages received by a large amount), I'm still receiving two messages, one that I'm posting, and another which was written quite some time ago for a different purpose. So, I can't really modify this other (unwanted) message's postMessage method. Is there a way in the postMessage method or receiveMessage, for that matter, which can help in identifying which one is mine? Maybe some extra parameter or configuration I'm missing here?



      Code for postMessage (in the embedded iframe):



      window.parent.postMessage("Hello world!", "*");


      Code for receiveMessage (in the parent window):



          window.addEventListener("message", receiveMessage, false);
      function receiveMessage(e) {
      var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
      var secureHost = "https" + reliableHost;
      var notSecureHost = "http" + reliableHost;
      if (e.origin.indexOf(secureHost) != -1 || e.origin.indexOf(notSecureHost) != -1) {
      var data = e.data;
      console.log(data);
      console.log(e.source);
      // filter the other event
      }
      }






      javascript






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 3 at 13:15









      Sindhu ShreeSindhu Shree

      165




      165
























          2 Answers
          2






          active

          oldest

          votes


















          1














          Since the data parameter is entirely under your control and can be an object, you can use a convention within the data parameter to ensure you're only handling the messages you care about. Also note that indexOf(...) != -1 may not be quite right, you probably want indexOf(...) == 0 (or startsWith) instead, to avoid matches later in the string.



          So on receipt (see *** lines [you have to scroll right with SO's display]):



          window.addEventListener("message", receiveMessage, false);
          function receiveMessage(e) {
          var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
          var secureHost = "https" + reliableHost;
          var notSecureHost = "http" + reliableHost;
          if ( (e.origin.indexOf(secureHost) == 0 || e.origin.startsWith(notSecureHost) == 0) && // ***
          (e.data && e.data.type === "whatever") // ***
          ) { // ***
          var payload = e.data.payload; // ***
          console.log(payload); // ***
          console.log(e.source);
          // filter the other event
          }
          }


          on sending:



          postMessage({type: "whatever", payload: /*...*/});


          I always use this mechanism with distinct type values so that different channels of communication with the same overall page/app doing interfere with each other.






          share|improve this answer



















          • 1





            The other unwanted message actually was passing an object with type set to info. Looks like the perfect solution.

            – Sindhu Shree
            Jan 4 at 5:57



















          1














          Yes: instead of passing in a string, e.g. "Hello world!", pass in an object instead, and perform checks against that. You can first check if e.data is typeof object, and then check what properties the object has. You can set any kind of custom properties that allows you to identify the postMessage of interest. For example, the iframe can execute the following line:



          window.parent.postMessage({
          source: 'my-custom-app',
          message: 'Hello world!'
          }, '*');


          And then when receiving the post message, you can simply check if:




          1. The post message payload (i.e. the data parameter) is an object, and

          2. The post message payload contains the key source and its value is my-custom-app


          Example code on the parent page:



          window.addEventListener("message", receiveMessage, false);

          function receiveMessage(e) {
          var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
          var secureHost = "https" + reliableHost;
          var notSecureHost = "http" + reliableHost;

          // Guard clause to catch unwanted messages from other hosts
          if (e.origin.indexOf(secureHost) === -1 && e.origin.indexOf(notSecureHost) === -1)
          return;

          var data = e.data;
          if (typeof data === 'object' && data.source === 'my-custom-app') {
          // Filtered event handling here
          }
          }





          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54023052%2ffilter-messages-in-receivemessage-javascript%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Since the data parameter is entirely under your control and can be an object, you can use a convention within the data parameter to ensure you're only handling the messages you care about. Also note that indexOf(...) != -1 may not be quite right, you probably want indexOf(...) == 0 (or startsWith) instead, to avoid matches later in the string.



            So on receipt (see *** lines [you have to scroll right with SO's display]):



            window.addEventListener("message", receiveMessage, false);
            function receiveMessage(e) {
            var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
            var secureHost = "https" + reliableHost;
            var notSecureHost = "http" + reliableHost;
            if ( (e.origin.indexOf(secureHost) == 0 || e.origin.startsWith(notSecureHost) == 0) && // ***
            (e.data && e.data.type === "whatever") // ***
            ) { // ***
            var payload = e.data.payload; // ***
            console.log(payload); // ***
            console.log(e.source);
            // filter the other event
            }
            }


            on sending:



            postMessage({type: "whatever", payload: /*...*/});


            I always use this mechanism with distinct type values so that different channels of communication with the same overall page/app doing interfere with each other.






            share|improve this answer



















            • 1





              The other unwanted message actually was passing an object with type set to info. Looks like the perfect solution.

              – Sindhu Shree
              Jan 4 at 5:57
















            1














            Since the data parameter is entirely under your control and can be an object, you can use a convention within the data parameter to ensure you're only handling the messages you care about. Also note that indexOf(...) != -1 may not be quite right, you probably want indexOf(...) == 0 (or startsWith) instead, to avoid matches later in the string.



            So on receipt (see *** lines [you have to scroll right with SO's display]):



            window.addEventListener("message", receiveMessage, false);
            function receiveMessage(e) {
            var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
            var secureHost = "https" + reliableHost;
            var notSecureHost = "http" + reliableHost;
            if ( (e.origin.indexOf(secureHost) == 0 || e.origin.startsWith(notSecureHost) == 0) && // ***
            (e.data && e.data.type === "whatever") // ***
            ) { // ***
            var payload = e.data.payload; // ***
            console.log(payload); // ***
            console.log(e.source);
            // filter the other event
            }
            }


            on sending:



            postMessage({type: "whatever", payload: /*...*/});


            I always use this mechanism with distinct type values so that different channels of communication with the same overall page/app doing interfere with each other.






            share|improve this answer



















            • 1





              The other unwanted message actually was passing an object with type set to info. Looks like the perfect solution.

              – Sindhu Shree
              Jan 4 at 5:57














            1












            1








            1







            Since the data parameter is entirely under your control and can be an object, you can use a convention within the data parameter to ensure you're only handling the messages you care about. Also note that indexOf(...) != -1 may not be quite right, you probably want indexOf(...) == 0 (or startsWith) instead, to avoid matches later in the string.



            So on receipt (see *** lines [you have to scroll right with SO's display]):



            window.addEventListener("message", receiveMessage, false);
            function receiveMessage(e) {
            var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
            var secureHost = "https" + reliableHost;
            var notSecureHost = "http" + reliableHost;
            if ( (e.origin.indexOf(secureHost) == 0 || e.origin.startsWith(notSecureHost) == 0) && // ***
            (e.data && e.data.type === "whatever") // ***
            ) { // ***
            var payload = e.data.payload; // ***
            console.log(payload); // ***
            console.log(e.source);
            // filter the other event
            }
            }


            on sending:



            postMessage({type: "whatever", payload: /*...*/});


            I always use this mechanism with distinct type values so that different channels of communication with the same overall page/app doing interfere with each other.






            share|improve this answer













            Since the data parameter is entirely under your control and can be an object, you can use a convention within the data parameter to ensure you're only handling the messages you care about. Also note that indexOf(...) != -1 may not be quite right, you probably want indexOf(...) == 0 (or startsWith) instead, to avoid matches later in the string.



            So on receipt (see *** lines [you have to scroll right with SO's display]):



            window.addEventListener("message", receiveMessage, false);
            function receiveMessage(e) {
            var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
            var secureHost = "https" + reliableHost;
            var notSecureHost = "http" + reliableHost;
            if ( (e.origin.indexOf(secureHost) == 0 || e.origin.startsWith(notSecureHost) == 0) && // ***
            (e.data && e.data.type === "whatever") // ***
            ) { // ***
            var payload = e.data.payload; // ***
            console.log(payload); // ***
            console.log(e.source);
            // filter the other event
            }
            }


            on sending:



            postMessage({type: "whatever", payload: /*...*/});


            I always use this mechanism with distinct type values so that different channels of communication with the same overall page/app doing interfere with each other.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 3 at 13:20









            T.J. CrowderT.J. Crowder

            700k12412441341




            700k12412441341








            • 1





              The other unwanted message actually was passing an object with type set to info. Looks like the perfect solution.

              – Sindhu Shree
              Jan 4 at 5:57














            • 1





              The other unwanted message actually was passing an object with type set to info. Looks like the perfect solution.

              – Sindhu Shree
              Jan 4 at 5:57








            1




            1





            The other unwanted message actually was passing an object with type set to info. Looks like the perfect solution.

            – Sindhu Shree
            Jan 4 at 5:57





            The other unwanted message actually was passing an object with type set to info. Looks like the perfect solution.

            – Sindhu Shree
            Jan 4 at 5:57













            1














            Yes: instead of passing in a string, e.g. "Hello world!", pass in an object instead, and perform checks against that. You can first check if e.data is typeof object, and then check what properties the object has. You can set any kind of custom properties that allows you to identify the postMessage of interest. For example, the iframe can execute the following line:



            window.parent.postMessage({
            source: 'my-custom-app',
            message: 'Hello world!'
            }, '*');


            And then when receiving the post message, you can simply check if:




            1. The post message payload (i.e. the data parameter) is an object, and

            2. The post message payload contains the key source and its value is my-custom-app


            Example code on the parent page:



            window.addEventListener("message", receiveMessage, false);

            function receiveMessage(e) {
            var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
            var secureHost = "https" + reliableHost;
            var notSecureHost = "http" + reliableHost;

            // Guard clause to catch unwanted messages from other hosts
            if (e.origin.indexOf(secureHost) === -1 && e.origin.indexOf(notSecureHost) === -1)
            return;

            var data = e.data;
            if (typeof data === 'object' && data.source === 'my-custom-app') {
            // Filtered event handling here
            }
            }





            share|improve this answer




























              1














              Yes: instead of passing in a string, e.g. "Hello world!", pass in an object instead, and perform checks against that. You can first check if e.data is typeof object, and then check what properties the object has. You can set any kind of custom properties that allows you to identify the postMessage of interest. For example, the iframe can execute the following line:



              window.parent.postMessage({
              source: 'my-custom-app',
              message: 'Hello world!'
              }, '*');


              And then when receiving the post message, you can simply check if:




              1. The post message payload (i.e. the data parameter) is an object, and

              2. The post message payload contains the key source and its value is my-custom-app


              Example code on the parent page:



              window.addEventListener("message", receiveMessage, false);

              function receiveMessage(e) {
              var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
              var secureHost = "https" + reliableHost;
              var notSecureHost = "http" + reliableHost;

              // Guard clause to catch unwanted messages from other hosts
              if (e.origin.indexOf(secureHost) === -1 && e.origin.indexOf(notSecureHost) === -1)
              return;

              var data = e.data;
              if (typeof data === 'object' && data.source === 'my-custom-app') {
              // Filtered event handling here
              }
              }





              share|improve this answer


























                1












                1








                1







                Yes: instead of passing in a string, e.g. "Hello world!", pass in an object instead, and perform checks against that. You can first check if e.data is typeof object, and then check what properties the object has. You can set any kind of custom properties that allows you to identify the postMessage of interest. For example, the iframe can execute the following line:



                window.parent.postMessage({
                source: 'my-custom-app',
                message: 'Hello world!'
                }, '*');


                And then when receiving the post message, you can simply check if:




                1. The post message payload (i.e. the data parameter) is an object, and

                2. The post message payload contains the key source and its value is my-custom-app


                Example code on the parent page:



                window.addEventListener("message", receiveMessage, false);

                function receiveMessage(e) {
                var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
                var secureHost = "https" + reliableHost;
                var notSecureHost = "http" + reliableHost;

                // Guard clause to catch unwanted messages from other hosts
                if (e.origin.indexOf(secureHost) === -1 && e.origin.indexOf(notSecureHost) === -1)
                return;

                var data = e.data;
                if (typeof data === 'object' && data.source === 'my-custom-app') {
                // Filtered event handling here
                }
                }





                share|improve this answer













                Yes: instead of passing in a string, e.g. "Hello world!", pass in an object instead, and perform checks against that. You can first check if e.data is typeof object, and then check what properties the object has. You can set any kind of custom properties that allows you to identify the postMessage of interest. For example, the iframe can execute the following line:



                window.parent.postMessage({
                source: 'my-custom-app',
                message: 'Hello world!'
                }, '*');


                And then when receiving the post message, you can simply check if:




                1. The post message payload (i.e. the data parameter) is an object, and

                2. The post message payload contains the key source and its value is my-custom-app


                Example code on the parent page:



                window.addEventListener("message", receiveMessage, false);

                function receiveMessage(e) {
                var reliableHost = "://" + "<%= Site.current_site.internal_admin_host %>";
                var secureHost = "https" + reliableHost;
                var notSecureHost = "http" + reliableHost;

                // Guard clause to catch unwanted messages from other hosts
                if (e.origin.indexOf(secureHost) === -1 && e.origin.indexOf(notSecureHost) === -1)
                return;

                var data = e.data;
                if (typeof data === 'object' && data.source === 'my-custom-app') {
                // Filtered event handling here
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 3 at 13:22









                TerryTerry

                31k44469




                31k44469






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54023052%2ffilter-messages-in-receivemessage-javascript%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith