gpt4 book ai didi

HTML5 跨域通信不工作

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:31 25 4
gpt4 key购买 nike

我打开 1.htm 作为 http://127.0.0.1/1.html

1.html

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<iframe id="ifr" src="http://localhost/2.html" width="100%" height="300">
</iframe>
<script>
iframe=document.getElementById("ifr");
iframe.contentWindow.postMessage("hello there", "http://localhost");
</script>
</body>
</html>

2.html

<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener("message", function(event) {

alert(hi);
if (event.data === "hello there" ) {
alert("Hi" + event.origin);
}
}, false );
</script>

<head>
<body>
Hello world
</body>

but I have that error: "Unable to post message to   http://localhost. Recipient has origin  http://127.0.0.1/ 

这是一个简单的例子。最后,我需要这样的结构:在域“A”上,我有 iframe,它的 src 是域“B”的页面。在 iframe 中,有按钮。当我单击显示在 iframe 中的那个按钮时,我需要调用域“A”的 window.addEventListener 我该怎么做?

最佳答案

如所述here .您只有以下选项。

同域或异域场景间通信:

 +-------------------------+-----------+-------------+-------------+
| | home.html | framed.html | helper.html |
+-------------------------+-----------+-------------+-------------+
| www.foo.com/home.html | N/A | YES | YES |
| www.bar.net/framed.html | NO | N/A | YES |
| www.foo.com/helper.html | YES | YES | N/A |
+-------------------------+-----------+-------------+-------------+

这纯粹是针对 CSRF(跨站请求伪造)攻击的浏览器限制。查看您的方案,即使您在同一领域工作。一种选择是遵循上面的层次结构示例,您可以在页面之间传递消息,甚至在相同或不同的域中使用父站点上的帮助页面。然后 child 可以通过这个帮助页面接收和发送消息。

关于HTML5 跨域通信不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14526542/

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