如何将消息正确发布到启用了沙箱属性的 iframe 中

joj*_*ojo 3 html javascript iframe cors

请参阅下面的示例代码

  • 如果我注释掉“沙箱”属性行,一切都会运行得很好。
  • 如果我取消注释“沙箱”属性行,在 chrome 打开的开发者控制台中,我们将看到错误“无法在 'DOMWindow' 上执行 'postMessage':提供的目标源(' https://www.bing.com ')与收件人窗口的原点不匹配 ('null')。”

知道如何解决这个问题吗?

const iframeElement = document.createElement("iframe");
iframeElement.src = "https://www.bing.com"
//iframeElement.setAttribute("sandbox", "allow-forms allow-modals allow-popups allow-scripts");
iframeElement.onload = (e) => {
  iframeElement.contentWindow.postMessage("foo", "https://www.bing.com");
};

const containerElement = document.getElementById("place-holder-for-iframe");
containerElement.appendChild(iframeElement);
Run Code Online (Sandbox Code Playgroud)

您可以使用此 jsbin 链接http://jsbin.com/gafobulife/edit?js,output尝试一下

  • 在chrome中打开js bin链接
  • 打开 chrome 开发者工具 --> 转到控制台选项卡
  • 取消注释沙箱行
  • 单击 jsbin 中的“使用 js 运行”

Ste*_*eve 6

如果您未allow-same-origin在沙箱属性中设置,则内容将被视为来自唯一来源:请参阅https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#Attributes,以及https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

令人困惑的是,allow-same-origin这并不意味着 iframe 将能够访问其父级,就好像它们具有相同的来源(除非它们具有相同的来源),但这意味着它可以将其视为来自它的正常原点(在本例中为https://www.bing.com)。

所以你可以改变:

iframeElement.setAttribute("sandbox", "allow-forms allow-modals allow-popups allow-scripts")'
Run Code Online (Sandbox Code Playgroud)

iframeElement.setAttribute("sandbox", "allow-forms allow-modals allow-popups allow-scripts allow-same-origin");
Run Code Online (Sandbox Code Playgroud)

或者,如果您不希望 iframe 保持其原点,请更改:

iframeElement.contentWindow.postMessage("foo", "https://www.bing.com");
Run Code Online (Sandbox Code Playgroud)

iframeElement.contentWindow.postMessage("foo", "*");
Run Code Online (Sandbox Code Playgroud)

对我来说,如果我不使用 ,还有其他错误allow-same-origin,很可能来自bing.com配置方式。

  • @kintsukuroi,只是补充一下,我认为如果 iframe 的 url 与其父级同源,那么这只是一个安全风险。如果它具有不同的来源,它应该无法访问自己的沙箱属性。请参阅:https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-sandbox“当嵌入页面具有以下属性时,将allow-scripts和allow-same-origin关键字一起设置与包含 iframe 的页面同源允许嵌入页面简单地删除沙箱属性,然后重新加载自身,从而有效地完全摆脱沙箱。” (3认同)