1

我正在尝试使用 Porthole.js(http://ternarylabs.github.io/porthole/)将 iframe 内容的高度传递给其父级(因此父级可以调整 iframe 的大小以“适应”内容).. .但我无法让它工作。

家长(在 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>

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>

我不确定如何更好地测试以查看数据是否从 iframe 推送到父级。警报触发,但父警报没有给我传递数据的值。

基本上,我想接收 iframe 的内容大小(messageEvent.data['newHeight']),为其添加 60px,并相应地设置 iframe 的高度。我哪里错了?丁:

4

1 回答 1

0

使用 window.load 而不是 ready 事件。见文档

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);
}; 
于 2016-10-12T10:30:06.780 回答