首页 > 解决方案 > 是否可以允许 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)。我不推荐这个。
更好的选择可能是向父母发送消息。

标签: javascriptiframewindowparentpostmessage

解决方案


如果 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
}

推荐阅读