Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. All the methods seem to require me to use form elements to put my data in.

like image 706
anthonyv Avatar asked Aug 22 '12 20:08

anthonyv


2 Answers

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

To actually post to a iframe you have to do

myIframe.contentWindow.postMessage(...)

fiddle

html

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

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), '*');
}​
like image 165
Liviu T. Avatar answered Nov 02 '22 17:11

Liviu T.


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

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

like image 32
dstj Avatar answered Nov 02 '22 17:11

dstj