如何使用跨域 postmessage 和 iframes?
因此,在您的错误域页面上包含一个 iframe,该 iframe 将带有 cookie 数据的消息发布回来。
这是跨域 postmessages 的一个可靠示例:http ://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage
现场示例:
http ://codepen.io/anon/pen/EVBGyz //分叉的发件人代码,有一个tiiiiiny变化:):
window.onload = function() {
// Get the window displayed in the iframe.
var receiver = document.getElementById('receiver').contentWindow;
// Get a reference to the 'Send Message' button.
var btn = document.getElementById('send');
// A function to handle sending messages.
function sendMessage(e) {
// Prevent any default browser behaviour.
e.preventDefault();
// Send a message with the text 'Hello Treehouse!' to the new window.
receiver.postMessage('cookie data!', 'http://wrong-domain.com');
}
// Add an event listener that will execute the sendMessage() function
// when the send button is clicked.
btn.addEventListener('click', sendMessage);
}
接收器代码:
window.onload=function(){
var messageEle=document.getElementById('message');
function receiveMessage(e){
if(e.origin!=="http://correct-domain.com")
return;
messageEle.innerHTML="Message Received: "+e.data;
}
window.addEventListener('message',receiveMessage);
}