How do I use postMessage() in Javascript?

2019-02-20 10:07发布

Is it possible to use the postMessage() method in Javascript to do cross-domain POST, GET, PUT, etc. calls? If so, how? And how do I pass headers and data?

2条回答
Summer. ? 凉城
2楼-- · 2019-02-20 10:49

This is a two way implementation, meaning that the page you want to call needs to have a callback that listens to such a message and give an appropriate response. You can't simply use it as a swap replacement for AJAX. The best method for that is to use a server-side proxy.

See this page for an explanation of how postMessage works.

查看更多
闹够了就滚
3楼-- · 2019-02-20 11:07

Yes, it is possible.

There is a nice demo of what exactly you want, here

document.getElementById("iframe").contentWindow.postMessage(
        document.getElementById("message").value,
        "http://anotherdomain.com"
);

handled on the second side with

window.onmessage = function(e){
  if ( e.origin !== "http://html5demos.com" ) {
    return;
  }

  document.getElementById("test").innerHTML = e.origin + " said: " + e.data;
};
查看更多
登录 后发表回答