Resize iframe based on content

One thing that many are using easyXDM (and other cross-domain hacks) for, is to dynamically change the size of embedded iframes based on the contents size, so as to avoid the scrollbars.

With easyXDM this is really easy:

Instead of embedding the iframe using plain HTML like ..

<iframe src="http://......."></iframe>

.. you do it using easyXDM ..

<br /><!-- use css to style this and its contained iframe --><br /><div id="container">/div><br />
new easyXDM.Socket({
    remote: "http://provider.easyxdm.net/example/resized_iframe.html",
    container: document.getElementById("container"),
    onMessage: function(message, origin){
        this.container.getElementsByTagName("iframe")[0].style.height = message + "px";
    }
});

.. and then in the document to embed, after the content, you put

var socket = new easyXDM.Socket({
    onReady:  function(){
        socket.postMessage(document.body.scrollHeight)
   }
});

You can see at demo of this in action here.

If you plan on navigating the inner window, be aware that this will break the connection and subsequent pages won’t cause the iframe to resize. Therefor the example uses an intermediary frame to facilitate this.

This entry was posted in Examples/How-to's and tagged , , , , , . Bookmark the permalink.
  • I'm trying to figure out how to also change the width of the div to match the iframe contents, in addition to the height.

    Is it as easy as adding “socket.postMessage(document.body.scrollWidth);” to the onReady area, and “this.container.getElementsByTagName(“iframe”)[0].style.width = message + “px”;” to the remote site code?

  • Thats pretty much it – but you should send both the width and height in the same message, eg “200×400” and the split it before setting the width and height respectively.

  • Ah, ok, I get it. There is one text message that can be sent back, and it's up to me to parse it if it contains multiple values. Thanks for the quick response. I'm building a JS/DIV widget for my site, and if your solution works, I'll definitely write it up and link to it in my blog/site. Great work!

  • It works 🙂
    But note that this sample uses the simple Socket, which only transmit plain text messages. If you want more advanced functionality go for the Rpc class, this lets you invoke methods and pass arbitrary data

  • Thanks. I meant if it works for my own complicated needs! I'll just be needing one thing sent back (for now) so the plain text will work. I'll also contact you when it's live, so you can show it off in your 'Used By' area.

  • Sam Lee

    I tested the scripts and it works perfect on simple text in your example. However, I found some issue in IE6,7,8, where the iframe auto resizing work in first time, but if you refresh it, it stop working. I copy the sample to link to a page in different domain, and the iframe is linking to a ASPX file. I can see error message showing on the browser said is related to file name.html. I wonder if you know what's going on?

  • Its not to easy to debug with that little information, are you able to share
    the code, or point me to it?

    Regarding the refreshing, are you refreshing the entire window or only the
    iframe? The latter one will cause problems since the main window is unaware
    of it happening.
    Do you have any of the same problems with the official examples?

    In any case, seeing the actually logs or error messages would be of great
    help.

  • dorian

    hi, can we run Javascript on the contents of the iframe ? does easyXDM allow this ?

    for instance, what if I need to load an external html page (complete with javascript render) in an iframe on my site, and run javascript on the contents of iframe ? does easyXDM make it possible ? Currently, I am using http proxy, it's really clunky and slow !

  • As long as both sides has added the framework, and taken steps to allow such interaction, then yes. But if you are looking for a solution so as to access random pages, then I'm afraid your'e out of luck. That is not allowed due to the SOP. A server side proxy is your only choice in this case.

  • Shap

    Hi all,

    I have tried to get this working for a week now but the resizing isn't working at all.

    In the above example you say that you put the second part of the code into the “iframe” to embed after content. I don't understand this part of the instructions. Is there a simple remote and local bit of code that I can see for myself or download to get the iframe to change size?

  • It means that you need the first section of code in the 'hosting' document, and the second one in the 'hosted' document.
    You can either view the source of the example at http://consumer.easyxdm.net/current/example/res… or review the two example files from the download, /example/resize_iframe.html and /example/resized_iframe.html.

  • Shap

    Hi, Further to this, here is what i am trying. What am I missing here?

    here is my code from calling page:

    <body>
    <script type=”text/javascript”>

    var socket;

    function onContentEvent(status)
    {
    document.getElementById('txt').value = status;
    }

    window.onload = function()
    {
    socket = new easyXDM.Socket({
    remote: “http://www.mydomainhere.com/remotesite/test_js.html”,
    remoteHelper: “http://www.mydomainhere.com/remotesite/name.html”,
    container: document.getElementById('remoteContainer'),
    onReady: function(){
    // you need to wait for the onReady callback before using the socket
    //socket.postMessage(“foo-message”);
    },
    onMessage: function(message, origin) {
    function(message, origin){
    this.container.getElementsByTagName(“iframe”)[0].style.height = message + “px”;
    }
    });
    };

    </script>

    Updated 3.25pm

    <div id=”remoteContainer”>
    <iframe></iframe>
    <frameset>

    </frameset>
    this inside the remoteContainer DIV
    </div>

    </body>

    And here is the code from the remote site

    updated thur 3.21 pm

    Lorem ipsum dolor sit amet, dui nulla ipsum quis amet magnis, sit amet tellus, et sit libero placerat. Enim vel orci mauris mauris arcu, platea nec, eius mi scelerisque, dolor et lobortis at turpis quis ut, erat vel massa. Lacinia suscipit pellentesque ut morbi velit, lorem facilisis. Dolorem sem mi per, suscipit enim nibh turpis, maecenas vitae nulla morbi amet quam, commodo dolor purus metus tincidunt venenatis vestibulum. Donec dui, in et tortor urna proin egestas, laboris odio integer etiam id, metus maecenas. Lacinia pede adipiscing viverra lorem non ante, placerat pretium ut blandit interdum viverra volutpat, ante luctus, at posuere, ut a duis vel luctus molestie. Vulputate dis tempor ut massa ante, veniam proin senectus purus arcu donec, cras nec wisi, pharetra lectus ut non pede dapibus tempus, ipsum nunc ac magna magnis. Sit eros luctus vitae, sed magna non ante ut, sollicitudin nibh, tempus eget a nec, sit felis nunc vitae at. Convallis tristique interdum mattis, massa eleifend placerat diam pede sed, nisi pharetra dictum. Pede ante sollicitudin nisl pellentesque sociis vehicula, tristique ut adipiscing nec maecenas, eros parturient ipsum scelerisque, etiam commodo quis, sed mollis.
    Tincidunt metus sem et tincidunt, id elit wisi praesent sollicitudin, etiam venenatis vulputate consequat elementum. Arcu et ut justo suspendisse sed volutpat. Lectus nascetur vel risus suspendisse, ultrices mauris, sit sed nascetur dolor. Vestibulum netus ac, ut pellentesque magna mauris quis nec lorem, pellentesque cras nullam nunc. Et nec mauris, lorem condimentum, in tempus sed fringilla. Ligula arcu et risus bibendum mus. Vel donec ullamcorper. A porttitor quis, magna luctus est est fusce bibendum sit.
    Sed commodo est auctor, in amet pellentesque urna, quis tempus velit eget sed interdum eu. Risus urna sed sed rutrum tincidunt, lorem sed sapien reiciendis lacus. Ut ipsum neque molestie, volutpat tellus amet sit. Justo sapien integer vel. Sit mi, sapien sed, felis convallis ut sed. Ante hac posuere, justo senectus velit, ut vulputate quam id.
    Commodo ligula vel iaculis viverra vestibulum, proin bibendum morbi sociosqu nulla tincidunt, amet non. Nam dui amet vitae, pede ac suscipit integer elit, urna in at, eu dolor dui consectetuer, sapien nulla. Libero vulputate quam et viverra fermentum eu, arcu quisque luctus semper id, dignissim in hac ac curabitur, wisi blandit tortor erat quam aenean, volutpat eu feugiat. Vivamus magna enim pharetra non lorem erat, quam arcu lorem eget nullam. Mi quis erat. Conubia nec habitant nam sed id sociis, nunc sem malesuada, magna placerat mollis convallis praesent porttitor, commodo lobortis ipsum. Vitae feugiat lectus pede et scelerisque. Est tempor.
    <script type=”text/ecmascript”>
    var socket = new Socket({
    onReady: function(){
    socket.postMessage(document.body.scrollHeight);
    }
    });
    </script>

  • Ouch, a frameset? That is invalid HTML, and also, the iframe with missing src will cause all sorts of strange issues.
    Just remove everything inside the remoteContainer and easyXDM will create it's own iframes.

    Please send such samples on email instead, and in its entirety as the broken code here is hard to debug 🙂

  • And do not use 'text/ecmascript' as the script type, that is also invalid. In a browser it SHOULD be 'text/javascript'. That could also explain in all…

  • Shap

    Hi there,
    I've uploaded used the examples you mentioned and it still wasn't working for me. I then did a view source on the page from the example site and my site and did a windiff on the source files. The only difference i could see was that i was using the easyXDM.min.js so I changed to use the debug. The only different now is the domains. I am still not having any luck in getting this to work. In the example there is all this code to do with switching if not a domain. I don't need any of that and don't think it is causing a problem anyway. I really need some help on this so if anyone can show me where to get two simple files working that would be great.

    Cheers,

    Shap.

  • It really is quite simple – in the local file (resize_iframe.html) you set the :remote property to the url of the remote document (resized_iframe.html) – that's it.

    You should be more specific when you say that it isn't working, what is happening? What does the console log say? Are there any javascript errors? What does the easyXDM trace log say? And if you could, please supply a link 🙂

  • James Yu

    Hi,

    I've gotten this to work on the first load of the iframe. However, I'm unable to get it to resize the iframe for every page load within the iframe.

    When I click on a link inside the iframe, and then the new content loads in the iframe (with the same socket with onReady), I get this error:

    TypeError: Result of expression 'url' [undefined] is not an object.

    It looks like that in prepareTransportStack on this line: config.remote = resolveUrl(config.remote); it is passing config.remote, which is undefined.

    It appears like the new Socket on the next load of the iframe is expecting remote to be set for some reason. And it can't communicate with the socket that was initiated from the parent frame earlier. Any ideas? I basically want every page load inside the iframe to resize the iframe in the parent window.

  • This is simply due to how easyXDM works – easyXDM sets up the iframe and passes all the necessary information in the query string, and when you navigate this information is lost.

    But more important here is the fact that it has to be this way to ensure the security and reliability of the connection – each connection is persistent and will break if any of the pages are navigated.
    So, the normal solution in your case is to use an intermediate frame that holds the connection, and which again has a iframe where the 'real' content lies. As long as those documents are on the same domain as the intermediary frame, then they can use parent.foo to accesses the parent frame, which in turn can use easyXDM to access its parent.

    Does that make sense?
    I should probably write a real post on this 🙂

    • ghostCoder

      um, doesnt make much sense to a newbie actually. pls write a real post on it. its quite a common problem as depicted by the number of posts on it on the net.

  • Mike

    Please do. Or provide and example thanks for all your hard work.

  • Did you see the above comment about http://consumer.easyxdm.net/experiments/example… ?

  • Mike

    Sorry missed that link. That should work for me. Thanks.

  • Petrogad

    Documentation is pretty sparse… I really want to implement this but looking at the example for the REMOTE = I’m uncertain of what that should be. I’m excited to give this a shot, and will continue to struggle through it, but wish that there was a bit more to the documentation IE something that matched your examples explaining everything that you were working through.

    • The REMOTE variable is just a variable pointing to the correct endpoint domain. This is resolved programmatically so that it will work on deployment to consumer.easyxdm.net, as well as in my test environment.
      You can probably drop it and include the entire path in the `remote` property used by the Socket constructor.

      Does this make sense?

      But yeah, the documentation is sparse and pretty fragmented… So far I’ve opted for loads of examples in hope that people are able to deduce the workings based on the examples.
      But I’me working on this..

  • Terence

    I am getting a permission error..

    Permission denied for to get property Window.transport from

    I am trying to do cross domain iframe resizing, but it gives me permission error..

    • Okay? I have no idea what you are doing, and easyXDM doesn’t use any references to `window.transport` – you might want to read up on how to ask good questions 🙂

  • Endang_markonah

    Hello .. I’ve succeeded with one iframe, but .. Can I set up 2 or more different iframe on one page and at the same time?, what should I do?, thank you …

    • Two (or more) iframes is no different from one – just new up more easyXDM objects.

      • Endang_markonah

        If I copy the exact same code on 2 object iframe, which appear only object (iframe), the first course.

        If I change the name of the container (<div id) with different names, only show first object iframe.

        If I use 2 different url target, 2 object (iframe) disappeared (not shown).

        How do I had "new up easyXDM new objects" like the one you mean?

        (sorry, my english translated using google translate).

        • The translation isn’t to good, it’s hard to understand – but this is what I mean:

          var socket1 = new easyXDM.Socket({
          remote: “http://provider.easyxdm.net/example/resized_iframe.html”,
          container: document.getElementById(“container_a”),
          onMessage: function(message, origin){
          this.container.getElementsByTagName(“iframe”)[0].style.height = message + “px”;
          }
          });

          var socket2 = new easyXDM.Socket({
          remote: “http://provider.easyxdm.net/example/resized_iframe.html”,
          container: document.getElementById(“container_b”),
          onMessage: function(message, origin){
          this.container.getElementsByTagName(“iframe”)[0].style.height = message + “px”;
          }
          });

          The important thing here is that the `this.container.getElementsByTagName(“iframe”)[0].style.height = message + “px”;` needs to reference the two different iframes, either by different containers (as in this example) or by different indexes (there are numerous ways to access the iframes).

          • Endang_markonah

            SUCCESS….!!!! “easyXDM” IS A GREAT CODE, THANK YOU VERY MUCH….

          • Endang_markonah

            TESTED WITH IE8 AND FIREFOX V.3.6.13

      • Endang_markonah

        Sorry…error at second post…

        If I copy the exact same code on 2 object iframe, which appear only object (iframe), the first course.
        If I change the name of the container (div id) with different names, but only show one object only.
        If I use 2 different url target, the second object (iframe) disappeared (not shown).

        How do I had more ups easyXDM new objects. like the one you mean?

        (sorry, my english translated using google translate).

      • Endang_markonah

        Hey … success with IE8 (different div id), but not success with Firefox 3.6.13 (only one object shown).

  • Loveisliving

    I tried using the second example, but the URL get´s wrong.
    instead of support.mydomain.de it goes to support.mydomain.de/workfolder/index.php?xdm_e=http%3A%2F%2Fmydomain.de&xdm_c=default4600&xdm_p=1

    What am i missing?

    • What do you mean by second example? There’s only one..

      And please rephrase your question as I am unable to deduce anything as no other details than two url’s are provided. Always supply all the needed context when asking questions as not everyone would even respond to questions lacking this.

      • Loveisliving

        Hello, thank you for your response.

        Sorry for being so vague with the answer.

        I have this on http://www.mydomain.de
        and then i have a subdomain, support.mydomain.de

        I put this on http://www.mydomain.de

        new easyXDM.Socket({
        remote: “http://support.mydomain.de”,
        container: document.getElementById(“embedded”),
        onMessage: function(message, origin){
        this.container.getElementsByTagName(“iframe”)[0].style.height = message + “px”;
        }
        });

        And then this on http://www.mydomain.de

        var socket = new Socket({
        onReady: function(){
        socket.postMessage(document.body.scrollHeight)
        }
        });

        Just like in your example above.
        But i get “Socket is not defined” on support.mydomain.de

        • Loveisliving

          Ur sorry, of couse i miss-wrote, it should be:

          And then this on support.mydomain.de

          var socket = new Socket({
          onReady: function(){
          socket.postMessage(document.body.scrollHeight)
          }
          });

          • You mean `easyXDM.Socket` and not just `Socket`?
            And do use the debug version for, well, debugging… it does give some insights into what is happening…

          • Loveisliving

            Now i got the page, but it wouldnt resize the window. I used the debug script this time, and firebug shows me this:

            mydomain.de – 14:06:34.232:… deferred messages …
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.233:easyXDM.Socket: constructor
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.234:{Private}: preparing transport stack
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.235:{Private}: resolved url ‘http://support.mydomain.de’
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.235:{Private}: selecting protocol: 1
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.236:easyXDM.stack.PostMessageTransport: constructor
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.237:easyXDM.stack.QueueBehavior: constructor
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.237:{Private}: firing dom_onReady
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.238:… end of deferred messages …
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.238:easyXDM.stack.PostMessageTransport: init
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.239:{Private}: adding listener message
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.240:{Private}: creating frame: http://support.mydomain.de?xdm_e=http%3A%2F%2Fmydomain.de&xdm_c=default200&xdm_p=1
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:34.242:{Private}: HAS_NAME_PROPERTY_BUG: false
            easyXDM.debug.js (rad 904)
            mydomain.de – 14:06:36.112:{Private}: firing dom_onReady
            was denied to get the property Window.socket from .
            was denied to get the property Window.socket from .

          • Could you provide me with a url where I could see this? It’s close to impossible for me to debug like this..

          • Loveisliving

            I am not allowed to put it public until release.

            Do i need to have the easyxdm script file on support.mydomain.de too?

          • Well then I cannot really spend more time debugging like this.
            The script doesn’t need to be hosted there no, but it will of course need to be included.

            But in your code sample, did you mean `new easyXDM.Socket`? You had `new Socket` which is obviously wrong.

          • Loveisliving

            I finally got it working, it was new socket that was wrong, and that i had put the script at top, not bottom of the page.

            Only problem now is that the iframe window does now adapt its width to the div width, how can i fix that?

          • That’s up to you to decide – the sample shows how to use the cross-domain channel to pass data – what data, and what you do with it is up to you.

          • Loveisliving

            Just wanted to make shure i didn´t miss anything, i fixed it with adding:
            this.container.getElementsByTagName(“iframe”)[0].style.width = “100%”;
            Probably would be good to include that as standard, since you mention in the guide that you only need to style the container div, but that´s not entirely true.

            I noticed now that clicking any link inside the iframe will break the connection, do i need to use the name.html file for the connection to be sustained?

          • “.. style this and its contained iframe ..” – you use a selector as in `.div iframe` to apply styles to the iframe. Alternatively you can use props: {style:width:”100%”}}.

            See http://easyxdm.net/wp/frequently-asked-questions/ regarding the navigation.

            Are you always in a habit of going straight for the comments instead of actually reading the docs, and browsing the provided examples? Just wondering..

          • Loveisliving

            Sorry for my brutish behaviour on this, i havent slept for 2 days and have a deadline tomorrow. The client requested a seamless working iframe, so im trying to deliver that. I am sure there is a lot of great things to learn about easyXDM, iframes, ajax etc. but im so stressed i cant think straight. That is the honest answer…

            I dont quite understand how this nested approach works, do i have an iframe in an iframe?

          • Look through the sample referenced in the FAQ, view the code that comes as part of the download. But yes, an iframe inside an iframe..

            Think of the amount of time I spend providing this kind of support to people who really ought to be able to read some simple docs…

          • Loveisliving

            I will read the docs properly now as to not waste more of your time. It´s not that i haven´t read them, it´s much more that i don´t understand how it works, all this is completely new to me and i get confused.

            I am very grateful for all the help, and this script is amazing stuff, i am really impressed. I hope i haven´t ruined your day too much.

            I´ll donate to this project when my project is finished and i have some cash, it´s the least i can do.

          • If this is company work, then use company money 😉
            The alternative is you spending a helluva lot more hours doing this…

          • Loveisliving

            Im a freelancer so it´s coming from my own pocket.

            I don´t usually do this, hopefully a one-time situation.

            Again, thanks, have a good day!

          • It should be the client’s – if he demands it, he pays.
            Cheers

          • Loveisliving

            This url looks wierd, could it be because of character conversion?
            Im using UTF-8 on the site.

            http://support.mydomain.de/?xdm_e=http%3A%2F%2Fmydomain.de&xdm_c=default200&xdm_p=1

          • The url is correct. This is just encoded. I cannot do more without actually seeing all the code and seeing it run.

  • Loveisliving

    Took a while before i found and understood the intermediary frame page.
    Perhaps print the URL to it, and explanation to the example page?

    • That is really left as an exercise for the reader.

      Øyvind Sean Kinsey
      oyvind@kinsey.no
      http://kinsey.no/blog/index.php/about/

    • Jake

      Can anyone post a link to the ‘intermediary frame’ page?  It seems the only way to resize an iframe when navigating around in the framed page.  The link provided in the article is broken.   

      Thanks!

      • This was incorporated into the example – I’ve updated the post.

      • the intermediate.html just has the iframe being added to the dom. it receives the src as a query parameter from the url with which it is called.
        also it houses the socket.  the page loaded in the iframe of intermediate.html just uses the ‘parent.socket’ to send messages. 

  • Loveisliving

    I can´t seem to shake off the scrollbar in IE when using the double iframe technique. The second iframe always get a scrollbar in Internet explorer 7, 8 and 9. Ive set overflow:hidden on both body and iframe. Any tips on how to solve that?

    • Loveisliving

      Not much scrollbar though, like 10px.

      • Loveisliving

        Setting height to 110% on the second iframe fixed the problem on all IE browsers.

        • That’s not a real fix – set your html and body’s margin to 0, the frame’s
          border to 0, and it should work fine.

          If my example is working, go through that and see what makes it tick.

          Sent from my Android

  • Giuseppe Neri

    I have a problem with the js called in the onMessage function:

    var socket = new easyXDM.Socket({
    remote: “contained.htm”,
    onMessage: function(message, origin) {
    self.scrollTo(0, 0);
    alert(‘massege:’ + message);
    }
    });

    I get the alert, but the window doesn’t scroll. In debug I get “undefined” when I execute “self.scrollTo(0,0);” in the context of the onMessage function.
    I have also a link in the container page that do the same js command and works fine.

    Any ideas?

    Thank you in advance,
    Giuseppe.

    • You have written massege instead of message 😉

      Sent from my Android

      • Giuseppe Neri

        ok… but I don’t think that a typo in a string constant is the problem…

        • Sorry, was reading on my cell, and it looked like it was the Identifier being misspelled, which would have caused a ReferenceError.

          I really have no idea why you get an ‘undefined’ in _your_ code, perhaps it is because `self` does does not point to `window`, that the proxy object presented by `self` not proxying that exact method, or just something else.

          Btw, do you get a TypeError (accessing a property on an undefined object), or does the scrollTo method return the _value_ ‘undefined’?

          • Giuseppe Neri

            the scrollTo method returns ‘undefined’ (in the immediate window of vs2008)
            I’ve alredy tried with “window.scrollTo(0,0);” and “window.parent.scrollTo(0,0);” but with the same result.

          • To be honest, I have no idea what you are trying to do and what is expected, but I know that this is not an issue with easyXDM. If you are looking for advice on javascript/DOM, please use a suitable forum.

  • Joseph de Ronde

    Hi There,

    I am having a little bit of an issue and have been working through this trying to understand what is happening and why.

    I have set up the iframe inside an ifame so that i can navigate, all seems to be working correctly. I am using ASP.NET 2.0 and an example of my solution is availible at: http://www.tellallmyfriends.com/wc.php/products/personalised-gifts/special-date-newspaper-books/year-edition-newspaper-book?u_sp=unreg

    So i have the code on the original iframe page which is the clients page. This links to another page called Intermidary.aspx located at http://www.gonedigging.co.uk

    So heres the dealio.
    My iframe publishes a height that is far to tall for the content. Now i have a feeling its because i have some jquery bits going on like a tab container which takes div’s and turns them into tabs. aslo theres an image scroller. Now what i think is happening is that the page is rendering and taking the page height before the Jquery has done its buisness. so the height is massive.

    Any thoughts on this.

    Ill post code on request 😉

    Joe.

    • You are probably correct in that the body’s height is sent prior to the DOM
      being adjusted by jq.
      This isn’t an issue with easyXDM (as it’s only a tool for transporting
      data), but I’ll give you a pointer.

      Make sure that the value isn’t passed back from the innermost window through
      intermediary.aspx *before* the layout has been done – that is, you need to
      hook into the events of your components, and only compute and pass back the
      value once you *know* that the layout has been completed.

      Øyvind Sean Kinsey
      oyvind@kinsey.no
      http://kinsey.no/blog/index.php/about/

      • Joseph de Ronde

        Brill, at least im on the right track,

        Cheers
        Joe.

        • Joseph de Ronde

          Ok,

          So i wanted to post on the issues i have had mind not with easyXDM but with my own site and the implimentation of the tech.

          1. I had a bit of a problem with JQuery altering the DOM objects after easyXDM had posted the height.

          2. I had another problem with some ajax controls that delayed the rendering of an image as the image needed to be generated on a server then loaded into an image control. So again XDM posted the height before it rendered the image

          3. There was another issue with a JQuery tab container, if the initial tab was shorter than all of the other tabs, it would create a scroll bar when the tab changed to one with longer content.

          4. Im sure there were more instances of this but i managed to clear it all up.

          Solution

          I created a function call checkIframe on the master page (so it appeard on all content pages)
          function checkIframe()
          {
          if(parent.transport != null)
          {
          var page = document.getElementById(“page”), height = page.scrollHeight || page.offsetHeight;
          parent.transport.postMessage(height);
          }
          }

          then i set an interval of one second going to check to make sure the height was allways correct.

          setInterval(‘checkIframe()’, 1000);

          I also invoked the checkIframe() method whenever a click on the tab happened, and whenever i need anm istant check.

          Hope this helps anyone who comes accross the same issues

          Joe.

          • First of all, never use `setTimeout` with a string as the first argument –
            it forces the engine to perform an eval, and you don’t get to use closures.
            setTimeout really takes a function reference, so the correct syntax would be
            `setInterval(checkIframe, 1000);`.

            The other thing is : never do something you do not need to do. In this case
            it means that you should only invoke the resize behavior if the height has
            indeed changed – if it’s the same as last time you checked then just exit.

            If I were you, I would just hook into the windows resize event with a buffer
            (so that multiple events during a short time only triggers one event)…
            But hey, that’s me 🙂

  • Hi, awesome library.
    I was trying to use it for resizing iframes based on content too using this.
    It works fine for firefox and chrome, but in IE7 when i try to run it, it gives me an error on Line 275
    url is undefined or empty, and the iframe is not resizing.
    pls help.

    • I’m guessing you are navigating the inner frame? Take a look at the FAQ.

    • Geoff

      I also got this same error when trying to set up simple iframe resizing. It was working, but I would also get the error “url is undefined or empty.”

      I was not navigating the iframe and the example page worked fine. The cause was that I was not setting a “container” parameter in my socket code, and adding this fixed the problem.The documentation says: container {String || DOMElement} – Set this to an id or element if you want the iframe to be visible for interaction.The text makes it sound like this is optional, but it appears that it is required – perhaps the docs should be updated to reflect this?

      • Geoff

        Er, correction: That was not the solution. What was making the error go away was adding a “remote” var to the other page (so both pages have a “remote” value set).

        I’m unsure why my page is not working the same as the example where only 1 page sets a remote value.

        • Geoff

          Ok, here’s the issue:
          I already had code that inserted an iframe into the page, and I assumed that easyXDM would be a separate thing, but I now see that creating the socket also creates the iframe, which was causing my iframe to initialize twice: 

          Once as a provider and once as a consumer (since the url params were missing in the initial request, which is why it was looking for the remote url and throwing the error.

  • Naman

    Hi, i’ve been working with your library for the past days. i’ve been using it for iframe resizing based on content. I’ve integrated it into my code and it works fine. I used that nested iframe approach you suggested.
    I just wanted to ask, is there any way around intermediary.html?
    i mean can we do something like socket rebinding on the reloading of window or something when we navigate in the iframe, so that the socket connection that breaks when we navigate the inner iframe is ‘rebinded’. that way we wont need to use intermediary.html which contains the inner iframe code. any suggestions??

    • No that is not possible as the setup is a one-time event (due to security). To enable such a feature on some of the transports we would have to open up the system to hijacking, and I really don’t want to do that.

      But, there is one other architecture that will allow this behavior:
      Use easyXDM to create a hidden iframe (and connection) from domain A to domain B.
      Open iframes from A to B the way you would regularly open them.
      In the documents at B, use `parent.frames[“framename”].foo` to signal that the easyXDM provider needs to notify A of the size.

      This requires that you set an explicit channel name on the consumer in order for the name of the iframe to be consistent.

      • Guest

        can u please tell the security concerns  because of which the setup of sockets is a one time event? and can we ‘rebind’ the socket by putting the code for socket in the jsp of the link being loaded in the iframe which will be resized? Like for only hashtransport, the _listenerWindow name will still be the same and so will be the config, so it can still pass messages using the url of the window. isnt such a thing possible? please correct me if i am wrong.

      • Guest

        can u please tell the security concerns  because of which the setup of sockets is a one time event? and can we ‘rebind’ the socket by putting the code for socket in the jsp of the link being loaded in the iframe which will be resized? Like for only hashtransport, the _listenerWindow name will still be the same and so will be the config, so it can still pass messages using the url of the window. isnt such a thing possible? please correct me if i am wrong.

        • The one-time setup is to ‘lock’ the connection to avoid spoofing attacks. This is needed on transports that require shared secrets, such as the FlashTransport and others (don’t recall the details right now).

          If you need to re-establish a connection, then the odds are that you can easily refactor the code so that you don’t, just like the example shows using an intermediary frame.
          Other ways to do this is to use two parallel iframes instead of nested ones, and using `parent.frames[“easyXDM-iframe-name”].foo(..` instead of `parent.foo(..`.

      • Paul

        Hi, great library.

        Is there any way that you can provide a quick example of the “other architecture” mentioned here in order to avoid the intermediary. The current framework of my environment has an issue with passing the url as a query to intermediary.

        greatly appreciated – Paul

      • Miron Moderau

        When I try calling parent.frames[“framename”] in IE9 it throws SCRIPT70 permission denied error. Also, line 1018 in easyXDM.debug.js (“var doc = logWin.document;”) throws SCRIPT70. Works fine in FF.

    • Roger Russel

      Hi,

      For not lose the socket connection, I take the xdm GET vars and put it into every link of my page with JavaScript, because the easyXDM use those for identify the socket connection, those vars are xdm_e,  xdm_c and xdm_p.

      Also I couldn’t use the body.scrollHeight, because the body sends the Iframe’s height if it was set, or if the body is bigger than that, my workaround to this was put a div into html and take the scrollHeight from it.

      I would prefer do this in a diferent way, but my time was really short.

      I hope this be useful.

  • Shafir Yoav

    Hi there,
    in the ‘ Resize iframe… ‘ example, the message is being sent from the iframe to it’s parent.
    How do i send a message from the parent to the iframe content?

    When i use HTML5 postMessages i have a something like that:

    var win = document.getElementById(“iframe”).contentWindow;
    win.postMessage(‘some message’, ‘target origin’);

    and for sending from the iframe to it’s back parent i use :

    window.parent.postMessage(……….

    hope you can help.
    thanks.

  • Sannan Khalid

    Waooooooo…. wht a post.. really appreciate your good work.. at last my 4 days of searching came to an end.. thanks a lot

  • Alex77_t

    Hi,
    i was acually facing the problem with getting the iframe resized in IE7 (win Xp), if i use debug version of EasyXDM it works fine, but if i switch to minified version it stops resizing without any changes to the code. I believe your sample pages will not work in IE7 with non-debug version as well.

    I;m using the lastest version – 2.4.15

    thanks,
    Alex

    • I have just tested the resize-iframe examle in IE7(XP) using the .min scripts – as expected it worked just fine. 

      If you can point me to a test setup that doesn’t work then I might be able to take the time to look at it.

    • Alex77_t

      i can confirm the issue was not related to Easyxdm library, apologies.

      Alex

      • Was the reason any interesting in relation to easyXDM?

        • Alex77_t

          for intermediate iframe it has the following CSS statement
                  iframe {
                          width:100%;
                          height:100%;
                          border:0px;
                          overflow:hidden;
                      }

          which was causing (somehow) the inner iframe to report its dimensions as 0x0 always in IE7.

          adding position:absolute to the intermediate iframe like below

                  iframe {

                          width:100%;

                          height:100%;

                          border:0px;

                          overflow:hidden;
          position:absolute;

                      }

          solved the problem.

          Alex

  • Example
    • You are mistaking (and the answer contains some grave errors too) – this will not work cross domain, which is what easyXDM does.

      Sent from my Android

  • Eran

    Hi
    Is it possible to asign a unique name to the iframe which is dynamically generated?
    We have a page with several iframes, for example 2 rows:
    first row : iframe_a , iframe_b
    second row: iframe_c
    In the content of iframe_a we need to isse URL with a target – which should be opened in iframe_c,
    When we generate iframe_c with easyxdm, how can we assign this iframe its name?
    Thanks

    Eran

    • Eran

      just to clarify: we would like to assign a predefined fixed name to the generated iframe (as easyxdm creates a dynamic iframe name  )
      Thanks

      Eran

    • If you set the ‘channel’ property then the windows will receive deterministic names.
      But: you really shouldn’t navigate easyXDM’s frames this way since you will be messing with easyXDM’s logic – consider using a nested frame for this..

  • Chudguy

    first off, your work is a godsend, thank you. Secondly, i’ve run into an issue i cant seem to solve: I’ve mimicked your example so that i can display PHP paged results into my iframe. the php pages are setup to alternate exactly like your red and green example frames, passing queries back and forth from the mirroring code to fire the onload event. the frame resizes perfectly when the page loads, but not when i click the next button that loads the alternate page. Im sorta noob still but any thought would be much appreciated… my links below:
    alternating iframes:
    http://zephyrworks.com/ss/arts.php & http://zephyrworks.com/ss/arts2.php (query would change the height)
    Intermediate:
    http://zephyrworks.com/ss/Ninter.html
    Parent:
    http://sciencestudio.org/N1.htm

  • Chudguy
  • Ryan

    hello, I have this working with an HTML file, but when I load a WordPress page (php) it does not resize itself.  It is stuck thinking the height of the page is 150px for some reason.

    Any ideas?

    • David Myers

      I’m getting the same thing, it appears its getting the height of the resize intermediate html file. I’ll let you know if I can come up with a solution.

      • Thanks To Phil Rasmussen, figured out what the problem was, my css in the framed site for html, body was set to height:100% and this caused the problem.

  • Brilliant library this has saved my arse big time in an iFrame heavy project, so thankyou 🙂  Also in case anyone runs into the same issue that caught me unstuck for several hours, having height:100% in the body/html css of the framed site causes weird things to happen with the polling.  My reset.css had a height:100%; width:100% declaration and the polling would pick a strange initial height and then adjust the iframe height every poll and get smaller and smaller till it vanished off the screen. After stripping back all js and css finally found the culprit in the reset and all working perfectly now in all browsers.

  • KJ

    Hi,

    Your iframe resize example has NO TRACE LOG POPUP when I view it in IE…

    I have successfully got easyxdm working across two different domains, however even with the latest easyxdm.min.js, I keep getting the trace log popup in IE (FF,Chrome and safari do not display the popup)

    Any ideas what could be causing this issue ONLY IN IE?

  • Emilbozo

    Hi,
    great script, tnx.
    I wish to use the intermediary system, but I don’t understand something: swf file and the intermediate.htm, could be in the main domain (the domain wich guest iframe) or in remote domain?
    very kind
    E

  • jspicher

    I keep getting “easyxdm is not defined” errors when trying to test this, what am l doing wrong?

  • Srajus84

     Hi Kinsey,
    I have few doubts in iframe. I have one jsp file which includes iframe.
    For example,
    In index1.jsp, i used like this

    Note: I have use IFrameHandler.js,IFrameCaller.js in my application. I called these js in index1.jsp.

    I want to call this index1.jsp in different application. So i used like this

    In index2.jsp

    But my problem is, i am not able to get  full page of main.html. I cannot able to resize the frame.

    I dont know the problem. This is the function which i used for  resizeIframe present in  (IFrameHandler.js)

    function resizeIframe(calledByElement) {

        var allIFrames = document.getElementsByTagName(“iframe”);
        alert(allIFrames[0].contentDocument.body.innerHTML);
        //var allIFrames = document.getElementById(“contentiframe”);
        //alert(allIFrames.contentDocument.body.innerHTML);
        //alert(allIFrames.contentDocument.body.innerHTML);
        for(var i = 0; i 0) {
                IFrameElement.height = sourceHeight;       
            }
        }
           
        // hack for IE6 to re-render the footer. (otherwise it’ll be placed wrong after resizing iframe)
        var footerElement = document.getElementById(“footer”);
        footerElement.style.display = “none”;
        footerElement.style.display = “block”;
    }

    Please do needful help.

  • pleae can you confirm if this does work with google custom search element (CSE) iframe ???

    Thank you

  • Hemchand

    Hi
    I am trying to use easyXDM to resize an Iframe whose src is from a differnt domain, I am trying to use the resize_intermediate.html soultion; because consumerwill be interacting with the iframe and it is a multipage; page one is submitted and then there is a page 2.
    So here is the scenario.
    Assuming our domain is http://somedomain.com
    I have a jsp called standardCampaign.jsp
    Inside of standardCampaign.jsp I have an IFrame:

    Then inside of clientSpecificCampaign.jsp I have another Iframe (we need this beause we need to dynamically generate the IFrame source)
    Our client test1.com include our javascript file(http://somedomain.com/clientIframeInclude.js) inside of their page for us.
    My question is given the above scenario how can i resize shellIFrame and innerFrame using easyXDM.
    I tried posting a message to the clientSpecificCampaign.jsp which works for page1 of the iframe but doesnt work on page2 of the iframe.i tried using the resize_intermediate.html solution but gets a Permission denied when i tried calling parent.socket from the clientIframeInclude.js file.
    Any help will be much appreciated.
    Thanks

  • Maggie

     
    I tried the examples resize_iframe.html and resize_intermediate.html. The frame resize works if loading resized_iframe_1.html  or resized_iframe_2.html as the frame content. But the frame size is always 150 px if it loading contents from other domain such as amazon.
    In the page resize_iframe.html:
     
    var transport = new easyXDM.Socket(/** The configuration */{
    remote: REMOTE + “/resize_intermediate.html?url=http://www.amazon.com”,
    swf: REMOTE + “http://localhost:8080/ReportsPortal/easyXDM/easyxdm.swf”,
    container: “embedded”,
    onMessage: function(message, origin){
    this.container.getElementsByTagName(“iframe”)[0].style.height = message + “px”;
    this.container.getElementsByTagName(“iframe”)[0].style.width = “100%”;
    this.container.getElementsByTagName(“iframe”)[0].scrolling=”no”;
    this.container.getElementsByTagName(“iframe”)[0].frameborder = 0;
    }
    });
     
    And in resize_intermediate.html:
     
    var socket = new easyXDM.Socket({
    swf: “http://localhost:8080/ReportsPortal/easyXDM/easyxdm.swf”,
    onReady: function(){
    iframe = document.createElement(“iframe”);
    iframe.frameBorder = 0;
    document.body.appendChild(iframe);
    iframe.src = easyXDM.query.url;
     
    //postMessage  as the height
    socket.postMessage(document.body.clientHeight || document.body.offsetHeight || document.body.scrollHeight);
    },
    onMessage: function(url, origin){
    iframe.src = url;
    }
    });
     
    If  loading contents from other domain that I don’t have control such as amazon.com. How to post the message back?
     
    I’ve removed height: 100% from the css.
    Is it doable to load other domain web site such as amazon.com?
     
    Thanks! Maggie

  • Kay

    Sorry in advance for my noob question. How do I use the code in WordPress. I just get lost with the code. If possible, help me in detail. Thanks!

  • Elliot Fleming

    In your nested example, you link to the ‘easyxdm.swf’ file on the remote domain rather than a local copy. Does it matter where it is loaded from? (i.e. can I load it locally instead?)