我开始与postMessage()
进行跨域/站点通信,在这里我的代码可以正常工作>
发件人窗口
<p>
<button id="send">Send Message</button>
</p>
<iframe id="receiver" src="http://reciever.example.com/index.html" width="500" height="200">
<p>Your browser does not support iframes.</p>
</iframe>
<script>
window.onload = function() {
var receiver = document.getElementById('receiver').contentWindow;
var btn = document.getElementById('send');
function sendMessage(e) {
e.preventDefault();
receiver.postMessage('Hello Stranger!', 'http://receiver.example.com');
}
function
btn.addEventListener('click', sendMessage);
}
</script>
接收器窗口
<div id="message"></div>
<script>
window.onload = function() {
var messageEle = document.getElementById('message');
function receiveMessage(e) {
if (e.origin !== "http://sender.example2.com")
return;
messageEle.innerHTML = "Message Received: " + e.data;
}
window.addEventListener('message', receiveMessage);
}
</script>
这很好用,并且在iframe窗口中显示了消息。但是我希望能够将发送到该域的每条消息记录到txt文件中,并且我不知道该如何处理。我需要你的帮助。代码信用归于Matt West
Check out his live demo here