简体   繁体   中英

What's the proper way to implement Porthole.js for resizing an iframe based on content height?

I am trying to use Porthole.js ( http://ternarylabs.github.io/porthole/ ) to pass the height of an iframe's content to its parent (so the parent can resize the iframe to "fit" the contents)... but I can't get it to work.

The parent (on abc.com):

<script src="porthole.min.js"></script>
<script type="text/javascript">
            var guestDomain = 'xyz.com';
            function onMessage(messageEvent) {  
                if (messageEvent.origin == "http://" + guestDomain) {
                    if (messageEvent.data['newHeight']) {
                        el = document.getElementById('iframe-name-here');
                        newHeightvar = (messageEvent.data['newHeight'],60);
                        window.alert("PARENT RECEIVED VALUE (+60): "+newHeightvar);
                        el.setAttribute('height', newHeightvar);
                    };
                };
            };
            var windowProxy;
            // register proxy window url and iframe name
            var proxy = new Porthole.WindowProxy("http://xyz.com/proxy.html", "iframe-name-here");
            // register an event handler to receive messages
            proxy.addEventListener(onMessage);
</script>

The iframe (on xyz.com):

<script src="js/porthole.min.js"></script>
<script type="text/javascript">
    $(document).ready(function($) {
    var proxy = new Porthole.WindowProxy("http://abc.com/proxy.html");
    var heightVal = $(document).height();
    window.alert("CHILD SENT VALUE: "+heightVal);
    proxy.post({"newHeight" : heightVal});
    });
</script>

I am unsure how to test better to see if the data is being pushed from iframe to parent. The alerts fire but the parent alert isn't giving me the value of the passed data.

Basically, I want to receive the iframe's content size (messageEvent.data['newHeight']), add 60px to it, and set the iframe's height accordingly. Where am I going wrong? D:

Use window.load instead of ready event. see doc

var windowProxy;
window.onload=function(){ 
  // Create a proxy window to send to and receive 
  // messages from the iFrame
  windowProxy = new Porthole.WindowProxy(
        'http://other-domain.com/proxy.html', 'guestFrame');

  // Register an event handler to receive messages;
  windowProxy.addEventListener(onMessage);
}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM