Javascript-->iframe使用postMessage方法调整大小
Javascript --> iframe resizing using postMessage method
我正在尝试理解另一个Stackoverflow答案(跨域iframe resizer?),该答案旨在解决如何根据高度调整iframe
(托管在与其嵌入的域分离的域上)的大小。想知道是否有人能回答我下面的问题。
解决方案:
Iframe:
<!DOCTYPE html>
<head>
</head>
<body onload="parent.postMessage(document.body.scrollHeight, 'http://target.domain.com');">
<h3>Got post?</h3>
<p>Lots of stuff here which will be inside the iframe.</p>
</body>
</html>
包含iframe的父页(并想知道它的高度):
<script type="text/javascript">
function resizeCrossDomainIframe(id, other_domain) {
var iframe = document.getElementById(id);
window.addEventListener('message', function(event) {
if (event.origin !== other_domain) return; // only accept messages from the specified domain
if (isNaN(event.data)) return; // only accept something which can be parsed as a number
var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar
iframe.height = height + "px";
}, false);
}
</script>
<iframe src='http://example.com/page_containing_iframe.html' id="my_iframe" onload="resizeCrossDomainIframe('my_iframe', 'http://example.com');">
</iframe>
我的问题:
- http://target.domain.com指iframe所在的域
嵌入其中,对吧?不是iframe所在的域 在
function resizeCrossDomainIframe(id, other_domain) {
行中,我不应该将"id"与iframe
的id
交换,将"other_domain"与iframe所在的域名交换,对吧?它们只是我稍后调用函数时指定的参数。我没有在
iframe
标记中使用onload
,而是在jQuery中编写了等效的内容,它加载在嵌入iframe:的页面上$('#petition-embed').load(function() { resizeCrossDomainIframe('petition-embed','http://target.domain.com'); });
我在退货处加了括号:
if (event.origin !== other_domain) {return;} // only accept messages from the specified domain if (isNaN(event.data)) {return;} // only accept something which can be parsed as a number
看起来对吗?
我需要做一些类似的事情,并发现这个例子似乎更简单:使用postmessage刷新iframe';s母文档
以下是我在iframe中得到的结果:
window.onload = function() {
window.parent.postMessage(document.body.scrollHeight, 'http://targetdomain.com');
}
在接收父级中:
window.addEventListener('message', receiveMessage, false);
function receiveMessage(evt){
if (evt.origin === 'http://sendingdomain.com') {
console.log("got message: "+evt.data);
//Set the height on your iframe here
}
}
- jquery插件或javascript方法自动调整文本输入(而非文本区域)(固定宽度)可变高度的大小
- 我需要一种自动调整iframe大小的方法,无论我查到什么,它都不起作用
- 修复Javascript错误:未捕获的类型错误:对象[对象对象]没有“可调整大小”的方法
- 使用 Raphaël JS 和 SVG 调整扇区路径大小的更优雅方法
- 未捕获错误:无法在初始化之前调用可调整大小的方法;尝试调用方法“选项”
- 实现 Porthole 的正确方法是什么.js根据内容高度调整 iframe 的大小
- 有没有一种方法可以将每个文本区域自动调整为其大小's从数据库查询返回的数据
- 在节点或浏览器端JavaScript中调整图像大小的好方法是什么
- 在GET之前重新调整发送OPTIONS方法的角度
- Javascript-->iframe使用postMessage方法调整大小
- 如何调整jQuery加载的内容的大小's使用CSS的加载方法
- 什么'这是在不创建空白的情况下按比例调整图像大小的最佳方法
- 在jquery方法中调用窗口大小调整函数
- 如何在JQuery方法中调整窗口大小
- 每次窗口大小调整时,append方法都会继续向容器中添加内容
- 有没有一种方法可以使用JavaScript来裁剪&在显示图像之前调整图像的大小
- 动态调整svg文件大小的最佳方法是什么?
- 有没有一种方法可以“清洁”一下?可调整大小的描边矩形在HTML5画布
- 在famo.我们,什么是在表面上调整文本元素大小的最佳方法?
- 用鼠标不断调整元素大小的最佳方法是什么?