<分区>
我有一个带有 iframe 的简单 HTML5 页面,其 src 属性最初为空字符串。页面呈现时没有任何 JavaScript 错误。
iframe 元素的 src
属性仅在窗口加载时设置,因此最初加载一个空的 iframe。 iframe src 被设置为来自另一个域的页面。
我面临的问题是 postMessage
方法工作时不会抛出任何错误,但是源页面没有触发 message
事件,即使它是在iframe 页面开始加载。我正在显示来自 iframe 页面的警告消息,这意味着 postMessage 方法没有抛出任何错误。
问题
订阅源页面中的消息事件时我错过了什么?
源页面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Cross domain iframe messaging</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
var iframec = null;
window.addEventListener("load", function () {
iframec = document.getElementById("iframec");
//set up event listener for iframe object so it can receive message from page shown in iframe
iframec.contentWindow.addEventListener("message", function (event) {
alert("received: " + event.data);
}, false);
//load the iframe page but after you have set up to receive messages
iframec.src = "http://www.abcx.com";
});
</script>
</head>
<body>
<form id="form1">
<div>
<h1>Testing iframe messaging in a Cross Domain scenario</h1>
<p> Trying to send a message to an iframe that comes from a page in another domain. The postMessage method does not throw an error when called from the other domain page, but it's not being received by the page having iframe element in it.</p>
<div id="divComments"></div>
<iframe src="" id="iframec" name="iframec" style="border:none;margin:0;padding:0;width:100%; "></iframe>
</div>
</form>
</body>
</html>
没有抛出任何错误的 Iframe 页面 JavaScript(即位于 http://www.abcx.com
的页面)
<script>
$( document ).ready(function() {
alert("loaded the iframe page on another domain. Just before postMessage");
window.postMessage("Some message was sent from other domain message", "*");
alert("loaded the iframe page on another domain. Just after postMessage");
});
</script>