gpt4 book ai didi

javascript - 用postMessage检查window.parent的起源有什么意义吗?

转载 作者:行者123 更新时间:2023-12-01 15:27:13 24 4
gpt4 key购买 nike

我有一个脚本打算包含在创建 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 是否安全? ?

最佳答案

使用 postMessage 时API,确保消息来自他们所说的地方的唯一真正安全的方法是使用严格的 targetOrigin .这样,您可以确保消息来自您控制的窗口。

你说得对,这种情况会阻止来自创建它们的窗口以外的传入消息。但是,带有 src="https://us.com/iframe"; 的 iFrame仍然可以在任何来源上创建。如果它是在恶意页面上创建的怎么办?这仍将满足 window.parent === parent 的条件。是 true .

关于javascript - 用postMessage检查window.parent的起源有什么意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51460070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com