在 iframe 父窗口(window.top/window.parent)上调用函数

有没有办法规避页面(域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


MYYA
浏览 406回答 1
1回答

12345678_0001

规避此问题的正确方法是使用Window.postMessage - 本质上,将消息从 iframe 发送到其父窗口,如果它具有 的事件侦听器"message",则可以相应地做出反应。IE。:a.com/index.html<!DOCTYPE html><html>&nbsp; <body>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; let someFunc = t => document.querySelector("#test").text = t;&nbsp; &nbsp; &nbsp; window.addEventListener("message", event => someFunc(e.data));&nbsp; &nbsp; </script>&nbsp; &nbsp; <span id="test">This is some dummy text.</span>&nbsp; &nbsp; <iframe src="https://b.com/index.html"></iframe>&nbsp; </body></html>b.com/index.html<!DOCTYPE html><html>&nbsp; <body>&nbsp; &nbsp; <button id="btn">Test</button>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; document.querySelector("#btn")&nbsp; &nbsp; &nbsp; &nbsp; .addEventListener("click", event => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.parent.postMessage("Changed text", "http://a.com");&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; </script>&nbsp; </body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript