是否可以配置iframe的父函数,使其允许resizeTo和类似函数(moveTo)的iframe?
还是需要手动将消息传递给父级?
伊夫拉梅
window.resizeTo = function(w,h){
parent.postMessage({
"command":"window_resizeTo",
"data":{width:w,height:h}
}, "*")
}
父级
function receiveMessage(event)
{
var message = event.data;
var command = message.command;
var properties = message.data;
switch(command)
{
case "window_resizeTo":
$(#iframe").setAttribute("style", `width:${properties.width}px;height:${properties.height}px`)
break;
// and so on for every function I wish to proxy
}
}
编辑:
如果父母是同一来源的话。我知道我可以在iframe内部使用window.parent (然后调整iframe的大小将很容易)。我的问题更多的是关于允许自动绑定的iframe选项,而不是自己去做。
EDIT2
这可能不存在。因为用例太窄了。即使父母同意让iframe自己调整大小,家长也可能希望限制面积和/或添加偏移量。
答案是:在iframe中已经有window.resizeTo和类似的函数,但是(由于滥用)它们可能什么也不做。
如果要在父级上下文中调整/移动iframe,则必须自己进行“绑定”。
没有直接绑定:您必须在更改iframe的偏移量/宽度的函数中转换调整大小的函数。如果iframe和父源是相同的,则可以操纵父(所以是iframe)的父(Iframe)。我不推荐这个。
更好的选择可能是向父级发送消息。
发布于 2021-08-15 15:30:27
如果IFrame内容是从不同的来源加载的,您必须使用postMessage事件来给IFrame改变其大小的机会。看看MDN上的原产地的定义。
如果iframe内容遵循相同的源策略,则可以从iframe内部访问window.parent.document
并直接修改父节点。
可以使用以下方法找到父文档中的节点:
// script at the iframe document
try {
const node = [...window.parent.document.querySelectorAll("iframe")]
.find(iframe => {
try { // avoid errors from inaccessible iframes
return iframe.contentWindow == window
} catch (e) {}
});
if (node) {
node.setAttribute("style", "...");
}
} catch(e) {
// unable to access parent
}
发布于 2021-08-15 15:35:49
试着用这个例子,为我工作,问候。
<script type="application/javascript">
function resizeIFrameToFitContent( iFrame ) {
iFrame.width = iFrame.contentWindow.document.body.scrollWidth;
iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}
window.addEventListener('DOMContentLoaded', function(e) {
var iFrame = document.getElementById( 'iFrame1' );
resizeIFrameToFitContent( iFrame );
// or, to resize all iframes:
var iframes = document.querySelectorAll("iframe");
for( var i = 0; i < iframes.length; i++) {
resizeIFrameToFitContent( iframes[i] );
}
});
</script>
<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>
https://stackoverflow.com/questions/68795658
复制相似问题