javascript - 是否可以允许 iframe resizeTo/By moveTo/By?
问题描述
是否可以配置 iframe 的父级,以便允许 iframe 调整大小和类似功能(moveTo)?
还是我需要手动将消息传递给父母?
框架
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 和父级是同源的。我知道我可以在 iframe 内部使用 window.parent (然后调整 iframe 的大小会很容易)。我的问题更多的是关于允许自动绑定而不是自己做的 iframe 选项。
EDIT2
这可能不存在。因为用例会太窄。即使父母可以让 iframe 调整自己的大小,父母也可能希望限制区域和/或添加偏移量。
答案是:iframe 中已经有 window.resizeTo 和类似的功能,但是(由于滥用)它们可能什么都不做。
如果要在父级的上下文中调整 iframe 的大小/移动,则必须自己进行“绑定”。
没有直接绑定:您必须在更改 iframe 偏移量/宽度的函数中转换调整大小函数。如果 iframe 和父级具有相同的来源,您可以从父级本身操作父级(以及 iframe)。我不推荐这个。
更好的选择可能是向父母发送消息。
解决方案
如果 IFrame-Content 是从不同的来源加载的,则必须使用 postMessage-Event 给 IFrame 更改其大小的机会。看看MDN的起源定义。
如果 IFrame-Content 遵循同源策略,您可以window.parent.document
从 iframe 中访问并直接修改父节点处的节点。
可以使用以下方法找到父文档中的节点:
// 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
}
推荐阅读
- mongodb - MongoDb - 带有 where 子句的 $lookup
- python - 删除记录的最佳方法取决于用户拥有 MySQL 的数据权限
- node.js - Google App Engine 上的 NestJS 项目显示错误“无法写入文件”&&“EROFS:只读文件系统”
- python - 我的 itertools 产品方法不起作用?为什么?
- javascript - 页面如何从使用 Require() 的 javascript 文件中调用函数?
- python - matplotlib 绘图后的 Sklearn Regression Fit 错误
- javascript - 使用带有 jquery 的按钮的内容过滤器仍然不起作用?
- python-3.x - 如何从 ubuntu 终端中运行的 python 脚本导航?
- rust - 使用quote crate时有没有办法去掉引号?
- snowflake-cloud-data-platform - 有哪些可用的雪花版本?