简体   繁体   English

将JSON对象发布到iFrame

[英]Posting a JSON object to an iFrame

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. 我已经看到了将数据发布到iframe的不同方法,但是找不到在其中可以发送JSON对象的方法。 All the methods seem to require me to use form elements to put my data in. 所有方法似乎都要求我使用表单元素来放入数据。

Take a look at postMessage and use JSON.stringify for your message and JSON.parse in the event handler. 看一下postMessage并在事件处理程序中将JSON.stringify用于您的消息和JSON.parse。

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), '*');
}​

You can use the Porthole JS library. 您可以使用Porthole JS库。 It describes itself as a "JavaScript Library for Secure Cross Domain iFrame Communication" . 它将自己描述为“用于安全跨域iFrame通信的JavaScript库”

It uses postMessage() if available, but reverts to a "hidden proxy" workaround for browsers that don't. 如果可用,它将使用postMessage() ,但对于没有此功能的浏览器,它将恢复为“隐藏代理”解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM