见下面的示例代码
- 如果我注释掉“sandbox”属性行,一切都会正常运行。
- 如果我取消注释“sandbox”属性行,在 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);
你可以用这个 jsbin 链接试试 http://jsbin.com/gafobulife/edit?js,output
- 在 chrome 中打开 js bin 链接
- 打开 chrome 开发者工具 --> 转到控制台标签
- 取消注释沙盒行
- 点击jsbin中的“run with js”
最佳答案
如果您没有在沙盒属性中设置 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")'
到
iframeElement.setAttribute("sandbox", "allow-forms allow-modals allow-popups allow-scripts allow-same-origin");
或者如果您不希望您的 iframe 保持其原始状态,请更改:
iframeElement.contentWindow.postMessage("foo", "https://www.bing.com");
到
iframeElement.contentWindow.postMessage("foo", "*");
对我来说,如果我不使用 allow-same-origin
,就会出现其他错误,很可能是因为 bing.com
的配置方式。
关于javascript - 如何正确地将消息发布到启用了沙箱属性的 iframe 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50480198/