Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6876041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T04:25:43+00:00 2026-05-27T04:25:43+00:00

I’ve been playing around with postMessage just to have a better understanding of how

  • 0

I’ve been playing around with postMessage just to have a better understanding of how it works, with the following example:

http://hashcollision.org/tmp/hello-iframe.html

It’s slightly elaborate: for each character in the message, this constructs an iframe sourced to http://hashcollision.org/tmp/hello-iframe-inner.html. I then use postMessage to communicate to each individual iframe, telling it what character to show. Also, the iframes communicate the geometry of the iframe back to the parent page via postMessage too. It’s all quite useless, but it’s a cute test page.

One of the things that’s currently awkward is, given the window of an iframe, to find the owning iframe.

I’m doing a for loop to walk all my iframes and check the window with ===, but that seems a bit silly. Are there better ways to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T04:25:44+00:00Added an answer on May 27, 2026 at 4:25 am

    The best solution I can come up with is this: generate a random identifier for each iframe. On all communication between the iframe and the parent window, the iframe will include its “self” identifier in the content of a postMessage. This allows quick-and-easy lookup by the parent when it receives messages.

    Here’s the amended example, with hello-iframe.html‘s content as:

    <html>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
    </script>
    <script>
    
    var run = function() {
        var msg = "Hello world, this is a test of the emergency broadcast system.";
        var i;
        document.body.appendChild(document.createElement("hr"));
        for (i = 0; i < msg.length; i++) {
            spawnCharacterIframe(msg.charAt(i));
        }
        document.body.appendChild(document.createElement("hr"));
    };
    
    var _gensymCounter = 0;
    var gensym = function() {
        var result = [], i;
        var LEN = 32;
        result.push((_gensymCounter++) + "_");
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        for (i = 0; i < LEN; i++) {
            result.push(chars.charAt(Math.floor(Math.random() * chars.length)));
        }
        return result.join('');
    };
    
    var spawnCharacterIframe = function(ch, id) {
        id = id || gensym();
        var newIframe = document.createElement("iframe");
        newIframe.setAttribute("frameborder", "0");
        newIframe.setAttribute("border", "0px");
        newIframe.setAttribute("width", "0px");
        newIframe.setAttribute("height", "0px");
        newIframe.setAttribute("src", "hello-iframe-inner.html?selfId=" + encodeURIComponent(id));
        newIframe.setAttribute("id", id);
        $(newIframe).data('ch', ch);
        document.body.appendChild(newIframe);
    };
    
    var findIframe = function(w) {
        var found;
        $('iframe').each(function() {
            if (this.contentWindow == w) {
                found = this;
            }  
        });
        return found;
    };
    
    
    
    $(window).on('message',
                 function(e) {
                     var data = e.originalEvent.data;
                     var source = e.originalEvent.source;
                     var iframe, sourceId;
    
                     if(data.match(/^([^,]+)[,](.+)$/)) {
                         sourceId = RegExp.$1;
                         data = RegExp.$2;
                         if (document.getElementById(sourceId)) {
                             iframe = document.getElementById(sourceId);
                         } else {
                             return;
                         }
                     } else {
                         return;
                     }
    
                     if (data === 'ready') {
                         iframe.contentWindow.postMessage($(iframe).data('ch'), '*');
                     } else if (data.match(/^(\d+),(\d+)$/)) {
                         var w = RegExp.$1;
                         var h = RegExp.$2;
                         if (iframe.width !== w + 'px') {
                             iframe.width = w + "px";
                         }
                         if (iframe.height !== h + 'px') {
                             iframe.height = h + "px";
                         }
                     }
                 });
    
    
    $(document).ready(run);
    </script>
    <body>
    <h1>testing iframes</h1>
    </body>
    </html>
    

    and hello-iframe-inner.html‘s content as:

    <html><head></head>
    <script>
    
    // http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
    var urlParams = {};
    (function () {
        var e,
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
            q = window.location.search.substring(1);
    
        while (e = r.exec(q))
           urlParams[d(e[1])] = d(e[2]);
    })();
    
    
    var SELF_ID = urlParams.selfId;
    window.addEventListener("message",
             function(e) {
                 if (e.data === ' ') {
                     document.body.innerHTML = "&nbsp;";
                 } else {
                     document.body.appendChild(
                         document.createTextNode(e.data));
                 }
             });
    
    
    window.onload = function() {
        document.body.style.margin = '0px';
        var w, h;
        if (window.parent && SELF_ID) {
            window.parent.postMessage(SELF_ID + ',ready', '*');
    
            setInterval(function() {
                if (h !== document.body.scrollHeight ||
                    w !== document.body.scrollWidth) {
                    w = document.body.scrollWidth;
                    h = document.body.scrollHeight;
                    if (window.parent) {
                        window.parent.postMessage(SELF_ID + ',' + w + ',' + h, '*');
                    }
                }
            }, 1000);
        }
    };
    
    </script>
    <body></body>
    </html>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I have a jquery bug and I've been looking for hours now, I can't
I have just tried to save a simple *.rtf file with some websites and
I have been unable to fix a problem with Java Unicode and encoding. The
I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I have a small JavaScript validation script that validates inputs based on Regex. I
I have this code to decode numeric html entities to the UTF8 equivalent character.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.