How do I use postMessage() in Javascript?

余生长醉 提交于 2019-12-07 20:39:50

问题


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?


回答1:


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.




回答2:


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;
};


来源:https://stackoverflow.com/questions/8172613/how-do-i-use-postmessage-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!