【发布时间】:2018-12-29 19:12:45
【问题描述】:
我有一个脚本打算包含在创建 iframe 的第三方网站中(在我们的来源上)。像这样的:
// this script exists on the *host site*
const iframe = document.createElement("iframe");
iframe.src = "https://us.com/iframe";
parent.appendChild(iframe);
该脚本公开了一个 API,该 API 通过postMessage 与 iframe 进行内部通信,类似于:
// This script exists on the *host site*
function getSomeProperty()
{
return new Promise(function (resolve, reject)
{
theIFrame.postMessage("getSomeProperty", "us.com")
window.addEventListener("message", function (event)
{
// ... get the response, making sure its from us.com, etc.
// This is just pseudo code, we don't create a new listener
// on every call in our real code.
resolve(answer);
}
});
}
这一切都很好,我的问题是关于 iframe 的相应“消息”侦听器。具体来说,我想仅尊重来自创建窗口/来源的请求。换句话说,如果某个独立来源(例如广告)上的某个并行 iframe 为我们构造了一个postMessage,我们当然希望忽略它。我的问题是是否足够简单地检查发送window是否是window.parent:
const parent = window.parent;
// This event handler is in the *embedded iframe*
window.addEventListener("message", function (event)
{
// This is being sent from a window other than
// the one that created us, bail!
if (event.window !== parent)
return;
// it is safe to respond...
}
据我了解, 不是充分检查的唯一方法是 window.parent 是否有可能 更改来源 同时保持我们周围。我可以想象可以从一个主机中删除 iframe 并将其附加到另一台主机上的场景,但我相信这只有在 DOM 操纵器位于同一来源(因此可以访问所述 DOM)并将我们置于另一个同源窗口。
目前,我们采用了一种额外的偏执防御,即通过查询字符串将原始来源传递给 iframe:
const iframe = document.createElement("iframe");
iframe.src = `https://us.com/iframe?location=${window.location.href}`;
因此允许我们检查window === window.parent 和origin === originalOrigin。但是,我们真的很想摆脱这种模型,因为它必然会破坏不同站点之间的缓存(因为每个站点都会由于不同的查询字符串而生成不同的 src URL)。那么,我们只检查window === window.parent 是否安全?
【问题讨论】:
标签: javascript iframe cross-domain same-origin-policy postmessage