【问题标题】:Call function on iframe parent window (window.top/window.parent) (circumvent cross-origin object access security)iframe父窗口(window.top/window.parent)调用函数(规避跨域对象访问安全)
【发布时间】:2020-01-19 15:21:42
【问题描述】:

有没有办法绕过页面(域B)上的iframe(域A)尝试访问属性时出现的跨域安全错误window.top?

我想调用一个函数,即。 someFunc,属于域B,通过域A的iframe中的一个事件,在域B的上下文中。

例子:

a.com/index.html

<!DOCTYPE html>
<html>
  <body>
    <script>
      var someFunc = t => document.querySelector("#test").text = t;
    </script>
    <span id="test">This is some dummy text.</span>
    <iframe src="https://b.com/index.html"></iframe>
  </body>
</html>

b.com/index.html

<!DOCTYPE html>
<html>
  <body>
    <button id="btn">Test</button>
    <script>
      document.querySelector("#btn").addEventListener("click", (e) => {
        window.top.someFunc("This text has been changed through a cross-origin")
      });
    </script>
  </body>
</html>

此示例在 Firefox 上引发以下错误:
SecurityError: Permission denied to access property "someFunc" on cross-origin object

【问题讨论】:

  • 没有......
  • 这是您需要使用 postMessage 并在两个域上都有代码的地方。
  • 我知道这一定看起来很傻,但我很欣赏这个答案,否则我可能不会找到 postMessage ......我稍后会写答案

标签: javascript iframe cross-domain postmessage


【解决方案1】:

规避此问题的正确方法是使用Window.postMessage - 本质上,将消息从 iframe 发送到其父窗口,如果它具有"message" 的事件侦听器,则可以做出相应的反应。

即:

a.com/index.html

<!DOCTYPE html>
<html>
  <body>
    <script>
      let someFunc = t => document.querySelector("#test").text = t;
      window.addEventListener("message", event => someFunc(e.data));
    </script>
    <span id="test">This is some dummy text.</span>
    <iframe src="https://b.com/index.html"></iframe>
  </body>
</html>

b.com/index.html

<!DOCTYPE html>
<html>
  <body>
    <button id="btn">Test</button>
    <script>
      document.querySelector("#btn")
        .addEventListener("click", event => {
          window.parent.postMessage("Changed text", "http://a.com");
        });
    </script>
  </body>
</html>

【讨论】:

    猜你喜欢
    • 2012-04-05
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2010-11-20
    • 2013-03-13
    相关资源
    最近更新 更多