jquery - iframe动态高度跨域使用jquery.ba-postmessage

标签 jquery iframe cross-domain height

我确信这个问题将来会帮助数百人。但该脚本有点超出了我的 jQuery 能力。我有 jQuery 基本技能,但无法解决这个问题。

基本上,我需要一个 iFrame(托管在单独的域上)来放置在我的主网站上。我不想使用 iFrame,但在我的情况下我别无选择!我需要将 iFrame 的大小调整为 iframe 内主体的高度。

当前使用Ben Alman jQuery postMessage plugin ,这个看起来可以做到。但当前的示例中有不必要的代码,可以启用切换来调整 iFrame 的大小...

我不需要这个切换,我所需要的只是将 iFrame 调整到正确的 iframe 内容主体高度。我需要随着 iframe 内的 body 高度变化而调整 iframe 高度。

这是我迄今为止发现的......

我已将其放在 iframe 内容文件中
这是在服务器上:http://myiframecontent.com/

<script src="js/jquery.ba-postmessage.js" type="text/javascript"></script>
<script type="text/javascript">

     $(function(){
       // Get the parent page URL as it was passed in, for browsers that don't support
       // window.postMessage (this URL could be hard-coded).
       var parent_url = decodeURIComponent( document.location.hash.replace( /^#/, '' ) ),
         link;

       // The first param is serialized using $.param (if not a string) and passed to the
       // parent window. If window.postMessage exists, the param is passed using that,
       // otherwise it is passed in the location hash (that's why parent_url is required).
       // The second param is the targetOrigin.
       function setHeight() {
         $.postMessage({ if_height: $('body').outerHeight( true ) }, parent_url, parent );
       };

       // Now that the DOM has been set up (and the height should be set) invoke setHeight.
       setHeight();

       // And for good measure, let's listen for a toggle_content message from the parent.
       $.receiveMessage(function(e){
         if ( e.data === 'toggle_content' ) {
           link.triggerHandler( 'click' );
         }
       }, 'http://mywebsite.com' );
     });

</script>

我已将其放在我的网站上
这是在服务器上:http://mywebsite.com/

<script src="js/jquery.ba-postmessage.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function(){

        // Keep track of the iframe height.
        var if_height,

        // Pass the parent page URL into the Iframe in a meaningful way (this URL could be
        // passed via query string or hard coded into the child page, it depends on your needs).

        src = 'http://myiframecontent.com/#' + encodeURIComponent( document.location.href ),

        // Append the Iframe into the DOM.
        iframe = $( '<iframe " src="' + src + '" width="1060" height="1000" scrolling="no" frameborder="0"><\/iframe>' )
            .appendTo( '#iframe' );

        // Setup a callback to handle the dispatched MessageEvent event. In cases where
        // window.postMessage is supported, the passed event will have .data, .origin and
        // .source properties. Otherwise, this will only have the .data property.
        $.receiveMessage(function(e){

        // Get the height from the passsed data.
        var h = Number( e.data.replace( /.*if_height=(\d+)(?:&|$)/, '$1' ) );

        if ( !isNaN( h ) && h > 0 && h !== if_height ) {
        // Height has changed, update the iframe.
            iframe.height( if_height = h );
        }

        // An optional origin URL (Ignored where window.postMessage is unsupported).
        }, 'http://myiframecontent.com/' );

        // And for good measure, let's send a toggle_content message to the child.
        $( '<a href="#">Show / hide Iframe content<\/a>' )
            .appendTo( '#nav' )
            .click(function(){
            $.postMessage( 'toggle_content', src, iframe.get(0).contentWindow );
            return false;
        });

    });
</script>

<div id="iframe" class="clear"></div>



目前,上面返回的是当前宽度 1060px,但没有将 iframe 的高度更改为 iframe 内主体的高度?

而且切换按钮也被添加到我的网站的导航 div#nav 上。当我需要的只是高度时。

对此的任何帮助都会很棒,因为我在网上找不到任何工作示例,谢谢!

这是ba-postmessage.js脚本。

最佳答案

由于您似乎想要删除链接,这里有一个工作示例,其中 iframe 内容通过 setInterval() 定期增加。

这应该转到主网站/服务器 A:http://mywebsite.com/

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Container on domain A (http://mywebsite.com/)</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/cowboy/jquery-postmessage/master/jquery.ba-postmessage.js"></script>
<script type="text/javascript">
    $(function(){

        // Update this constant to match your IFrame (contents) URL (no '#' here please)
        var if_url = 'http://myiframecontent.com/';

        // Keep track of the iframe height.
        var if_height;

        // Pass the parent page URL into the Iframe in a meaningful way (this URL could be
        // passed via query string or hard coded into the child page, it depends on your needs).
        var src = if_url + '#' + encodeURIComponent( document.location.href );

        // Append the Iframe into the DOM.
        var iframe = $( '<iframe " src="' + src + '" width="200" height="100" scrolling="no" frameborder="0"><\/iframe>' )
            .appendTo( '#iframe' );

        // Setup a callback to handle the dispatched MessageEvent event. In cases where
        // window.postMessage is supported, the passed event will have .data, .origin and
        // .source properties. Otherwise, this will only have the .data property.
        $.receiveMessage(
            function(e){
                // Get the height from the passsed data.
                var h = Number( e.data.replace( /.*if_height=(\d+)(?:&|$)/, '$1' ) );

                if ( !isNaN( h ) && h > 0 && h !== if_height ) {
                    // Height has changed, update the iframe.
                    iframe.height( if_height = h );
                    // Some user feedback if we want to...
                    $("#ticker").text("has been informed that IFrame contents height is now " + h + " and (re)acted accordingly.");
                }
            }, 
            // An optional origin URL (Ignored where window.postMessage is unsupported).
            if_url 
        );

    });
</script>
</head>
<body>
<p>Container <span id="ticker"></span></p>
<div id="iframe"></div>
<p>Container</p>
</body>
</html>

这应该转到“iframe”站点/服务器 B:http://myiframecontent.com/

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Contents on domain B (http://myiframecontent.com/)</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/cowboy/jquery-postmessage/master/jquery.ba-postmessage.js"></script>
<script type="text/javascript">
$(function(){
   // Get the parent page URL as it was passed in, for browsers that don't support
   // window.postMessage (this URL could be hard-coded).
   var parent_url = decodeURIComponent( document.location.hash.replace( /^#/, '' ) ),
     link;

   // The first param is serialized using $.param (if not a string) and passed to the
   // parent window. If window.postMessage exists, the param is passed using that,
   // otherwise it is passed in the location hash (that's why parent_url is required).
   // The second param is the targetOrigin.
   function setHeight() {
     $.postMessage({ if_height: $('body').outerHeight( true ) }, parent_url, parent );
   };

   // Let's increase height, and inform the parent document of new height, every 3 second
   var i = 1;
   function increaseHeight() {
       $("#iframecontents").append("<p>Increase #" + i + "</p>");
       i = i + 1;
       // Now that the DOM has been set up (and the height should be set) invoke setHeight.
       setHeight();
   };
   var timer = window.setInterval(increaseHeight, 3000);
});
</script>
</head>
<body>
<p>iframe starts here</p>
<div id="iframecontents"></div>
<p>iframe ends here</p>
</body>
</html>

请注意,在现实生活中的实现中,在 IFrame(内容)页面中,您当然需要某种事件来 Hook 并调用 setHeight()

关于jquery - iframe动态高度跨域使用jquery.ba-postmessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8731952/

相关文章:

jquery - 使用 jQuery 添加 html 元素 OOP 样式

javascript - 无法使用 javascript 解决 No 'Access-Control-Allow-Origin' 错误

javascript - jQuery .load() 方法不适用于/CMS 文章

node.js - 如何为 socket.io-client 连接设置自定义来源?

javascript - 按钮点击伪装

php - 数据表错误

jquery - Rails - 同步 - Faye、Juggernaut、Cool.io、普通的旧 eventmachine

iframe - indexedDB 可以在 Safari 的 iframe 内工作吗?

javascript - 使用 Jquery 更改 iframe 中的 div

jquery - 悬停时下拉子菜单隐藏在 iframe 后面