首页 > 解决方案 > 如何确定在 JavaScript 中调用另一个窗口上的函数的窗口

问题描述

我正在努力解决 JavaScript 中的一个复杂问题:有没有办法确定哪个窗口确实调用了另一个窗口上的函数?考虑一个a.com/foo嵌入从a.com/bar. 两个框架是同源的,因此可以访问彼此的全局窗口对象。

现在,在其上运行的 iframea.com/bar调用该函数foo,该函数在其父窗口的全局范围内。有什么方法可以确定fooiframe 调用的函数内部吗?具体来说,我需要从foo函数中引用 iframe 的窗口。

有两个限制:

  1. 我们无法更改函数调用window.parent.foo(),因为我们无法更改源代码a.com/bar
  2. 我们不能简单地window.frames[0]foo函数中运行来获取引用,因为有很多 iframe,我们需要知道哪个 iframe 调用了foo函数(在本例中,iframe on a.com/bar)。
// a.com/foo embeds a.com/bar as iframe

// Running on a.com/foo
window.foo = function() {
    // window.location.href = "a.com/foo"
    // Q: How to get a reference to caller's window (the iframe on a.com/bar)?
}

// Running on a.com/bar
window.parent.foo(); // This call is fix, we cannot make changes in this iframe.

非常感谢任何帮助或想法。提前致谢!

祝你有美好的一天!

标签: javascriptdom

解决方案


推荐阅读