2012-01-04 4 views
5

Это вопрос, который, я уверен, поможет сотням людей в будущем. Но сценарий немного за пределами моей способности jQuery. У меня есть базовые навыки jQuery, но я не могу это решить.перекрестный домен iframe динамической высоты с использованием jquery.ba-postmessage

В основном мне нужен iFrame (который размещен в отдельном домене), чтобы сесть на мой основной сайт. Я не хочу использовать iFrame, но в моей ситуации у меня нет выбора! Мне нужно, чтобы iFrame изменил размер на высоту тела внутри iframe.

В настоящее время используется Ben Alman jQuery postMessage plugin, похоже, что он может это сделать. Но в текущем примере есть ненужный код, который позволяет переключаться на изменение размера 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, но не изменяя высоту моего фрейма на высоту тела внутри моего фрейма?

А также кнопка переключения добавляется на мой сайт в мой навигационный div # nav. Когда мне нужна только высота.

Любая помощь по этому вопросу была бы удивительной, поскольку я не могу найти никаких рабочих примеров в сети, спасибо!

Это сценарий ba-postmessage.js.

ответ

0

Как вы, кажется, хотите избавиться от ссылок, вот рабочий пример с содержимым 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 (содержимое) вам, конечно, потребуется какое-то событие для подключения и вызова setHeight().

Смежные вопросы