Javascript 如何将邮件正确地发送到启用了沙盒属性的iframe中

Javascript 如何将邮件正确地发送到启用了沙盒属性的iframe中,javascript,html,iframe,cors,Javascript,Html,Iframe,Cors,请参见下面的示例代码 如果我注释掉“sandbox”属性行,一切都会正常运行 如果我在chrome open developer控制台中取消注释“sandbox”属性行,我们将看到错误“未能在“DOMWindow”上执行“postMessage”:提供的目标源(“”)与收件人窗口的源('null')不匹配。” 你知道怎么解决这个问题吗 const iframeElement = document.createElement("iframe"); iframeElement.src = "ht

请参见下面的示例代码

  • 如果我注释掉“sandbox”属性行,一切都会正常运行
  • 如果我在chrome open developer控制台中取消注释“sandbox”属性行,我们将看到错误“未能在“DOMWindow”上执行“postMessage”:提供的目标源(“”)与收件人窗口的源('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);
您可以使用这个jsbin链接进行尝试

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

如果未在沙盒属性中设置
允许相同来源
,则内容将被视为来自唯一来源:请参阅和

令人困惑的是,
允许同一原点
并不意味着iframe将能够访问其父级,就好像它们是同一原点一样(除非它们是同一原点),但这意味着它将能够被视为来自其正常原点(在本例中,
https://www.bing.com

因此,您可以更改:

iframeElement.setAttribute("sandbox", "allow-forms allow-modals allow-popups allow-scripts")'

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

iframeElement.contentWindow.postMessage("foo", "https://www.bing.com");


对我来说,如果我不使用
允许相同来源
,则会出现额外的错误,很可能是由于
bing.com
的配置方式造成的。

请记住,“允许脚本”和“允许相同来源”组合会产生安全风险,沙盒可以删除。iframelement.contentWindow.postMessage(“foo”、“*”;非常适合我,谢谢@kintsukuroi,我想补充一点,如果iframe的url与其父url的来源相同,那么这只是一个安全风险。如果它来自不同的来源,它应该不能访问自己的沙盒属性。请参阅:“当嵌入页面与包含iframe的页面具有相同的原点时,同时设置allow脚本和allow home-origin关键字,允许嵌入页面简单地删除sandbox属性,然后重新加载自身,从而有效地完全脱离沙盒。”
iframeElement.contentWindow.postMessage("foo", "https://www.bing.com");
iframeElement.contentWindow.postMessage("foo", "*");