Это вопрос, который, я уверен, поможет сотням людей в будущем. Но сценарий немного за пределами моей способности 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.