javascript 将 JSON 对象发布到 iFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12081016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:16:33  来源:igfitidea点击:

Posting a JSON object to an iFrame

javascriptjsonhttppostiframe

提问by anthonyv

I've seen different methods for posting data to an iframe but I can't find one where I can just send a JSON object. All the methods seem to require me to use form elements to put my data in.

我已经看到了将数据发布到 iframe 的不同方法,但我找不到可以只发送 JSON 对象的方法。所有的方法似乎都要求我使用表单元素来放入我的数据。

回答by Liviu T.

Take a look at postMessageand use JSON.stringify for your message and JSON.parse in the event handler.

查看postMessage并在事件处理程序中为您的消息和 JSON.parse 使用 JSON.stringify。

To actually post to a iframe you have to do

要实际发布到 iframe,您必须执行

myIframe.contentWindow.postMessage(...)

fiddle

小提琴

html

html

<button onclick="_sendMessage ()">Send</button>
<iframe src="" id="myIframe">?

javascript

javascript

var myIframe = document.getElementById('myIframe');
myIframe.contentWindow.addEventListener('message', function(event) {
    console.log(JSON.parse(event.data));
}, false);


window._sendMessage = function() {
    var json = {payload:'Hello World'};
    myIframe.contentWindow.postMessage(JSON.stringify(json), '*');
}?

回答by dstj

You can use the PortholeJS library. It describes itself as a "JavaScript Library for Secure Cross Domain iFrame Communication".

您可以使用PortholeJS 库。它将自己描述为“用于安全跨域 iFrame 通信的 JavaScript 库”

It uses postMessage()if available, but reverts to a "hidden proxy" workaround for browsers that don't.

postMessage()如果可用,它会使用,但对于不使用的浏览器,它会恢复为“隐藏代理”解决方法。