简体   繁体   English

实现Porthole.js根据内容高度调整iframe大小的正确方法是什么?

[英]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. 我正在尝试使用Porthole.js( http://ternarylabs.github.io/porthole/ )将iframe内容的高度传递给它的父级(以便父级可以调整iframe的大小以“适合”内容)。 。但是我无法正常工作。

The parent (on abc.com): 父项(在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): iframe(在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. 我不确定如何更好地测试以查看是否将数据从iframe推送到父级。 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. 基本上,我想接收iframe的内容大小(messageEvent.data ['newHeight']),向其中添加60px,然后相应地设置iframe的高度。 Where am I going wrong? 我要去哪里错了? D: D:

Use window.load instead of ready event. 使用window.load而不是ready事件。 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);
}; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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