使用postmessage发回消息

时间:2014-08-06 14:23:23

标签: javascript iframe cross-browser sendmessage postmessage

我目前正在制作一个应用程序,需要在两个域之间发送信息(将在加载页面时)。

网站1: 创建iFrame> 将Postmessage发送到网站2

window.onload =  function () {

iframe = document.createElement("IFRAME");
iframe.setAttribute("src", "WEBSITE 2");
iframe.style.width = "200px";
iframe.style.height = "200px";
iframe.style.border = "none"; //please do not show the iframe JS.
 iframe.id = "lol";
document.body.appendChild(iframe);
document.getElementById("test").innerHTML = "Test!"
window.addEventListener("message", listener, false);

window.setTimeout(sendMessage,100)
}
function sendMessage(e) {
  var receiver = document.getElementById('lol').contentWindow;
receiver.postMessage('Hello Treehouse!', 'WEBSITE 2');
}

function listener(event){
if ( event.origin !== "WEBSITE 2" )
return //website isn't ours bro

  document.getElementById("test").innerHTML = event.data

}

网站2 从网站1获取Postmessage> 创建iFrame(?)> 将Postmessage发送到网站1(?)

window.onload =  function createiframe() {
 window.addEventListener("message", listener, false);
}

function listener(event){
  if ( event.origin !== "WEBSITE 1" )
  return //website isn't ours bro

  document.getElementById("test").innerHTML = event.data

  window.setTimeout(createiFrame,1000)
}
  function createiFrame() {
 iframe = document.createElement("IFRAME");
  iframe.setAttribute("src", "WEBSITE 1");
  iframe.style.width = "230px";
  iframe.style.height = "203px";
  iframe.style.border = "none"; //please do not show the iframe JS.
  iframe.id = "lol";
  document.body.appendChild(iframe);
  document.getElementById("test").innerHTML = "Test!"
  window.setTimeout(sendMessage,1000)
  }
  function sendMessage(e) {
         var receiver = document.getElementById('lol').contentWindow;
    receiver.postMessage('Hello ', 'WEBSITE 1');
    console.log('Message sent')
  }

iFrame是在网站2上创建的,之后是网站1和网站2的循环,但是从网站2发送到网站1的Postmessage显示在额外的iFrame中,是否可以发回消息到浏览器中打开的网站1?

显示的内容示例:

测试!   测试!     你好       测试!

谢谢!

2 个答案:

答案 0 :(得分:2)

如果我正在查看此权限,请在sendMessage()函数的网站2中,看起来您正在获取新创建的iframe元素,然后向其发布消息。实际上你真的想在网站1上发帖子。

从网站2 ...尝试类似

window.parent.postMessage("hello website 1", "*");

答案 1 :(得分:0)

要响应 Event.origin 域,请使用消息Event.source

// Child website:
window.addEventListener("message", evt => {
    // if (evt.origin !== "http://example.com") return;

    console.log(evt.data) // "Question!"
    evt.source.postMessage("Response!", evt.origin);
});

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#The_dispatched_event

  

source
  对发送消息的窗口对象的引用;您可以使用它在两个起源不同的窗口之间建立双向通信。