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

发布于 2024-12-25 10:05:51 字数 4225 浏览 0 评论 0原文

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

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

目前使用 Ben Alman jQuery postMessage 插件,这看起来可以做到它。但是当前的示例中有不必要的代码,可以启用一个开关来调整 iFrame 的大小...

我不需要这个开关,我需要的只是将 iFrame 的大小调整到正确的 iframe 内容主体高度。我需要随着 iframe 内身体高度的变化来调整 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 脚本。

This is a question that I'm sure will help hundreds of people in the future. But the script is a little outside my jQuery ability. I have jQuery basic skills but can't work this out.

Basically I need an iFrame (which is hosted on a separate domain) to sit on my main website. I don't want to use an iFrame, but in my situation I have no choice! I need the iFrame to resize to the height of the body inside the iframe.

Currently using Ben Alman jQuery postMessage plugin, this looks like it can do it. But the current example has got unnecessary code in there which enables a toggle to resize the iFrame...

I do not need this toggle, all I need is for the iFrame to resize to the correct iframe content body height. I need the iframe height to adjust as the body height changes inside the iframe.

This is what I found so far...

I have put this on the iframe content file
This is on server: 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>

I have put this on my website
This is on server: 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>

Currently the above is returning the current width 1060px but not changing the height of my iframe to the height of the body inside my iframe?

And also the toggle button is being added into my site on my navigation div#nav. When all I need is the height.

Any help on this would be awesome as I can't find any working examples on the net, Thanks!

This is the ba-postmessage.js script.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尛丟丟 2025-01-01 10:05:51

由于您似乎想要删除链接,这里有一个工作示例,其中 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/< /code>

<!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(内容)页面中,您当然需要某种事件来挂钩并调用 setHeight()

As you seem to want to get rid of the links, here is a working example with iframe contents that increases periodically through a setInterval().

This should go to main website / server 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>

And this should go to "iframe" site / server 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>

Be aware that in your real-life implementation, in you IFrame (contents) page, you will of course need some kind of event to hook on and call setHeight().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文