最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Posting a JSON object to an iFrame - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Aug 22, 2012 at 20:36 anthonyvanthonyv 2,4651 gold badge14 silver badges18 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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

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.

I develop in .NET, then, I load the JSON file from server, I get the files from the path and convert into Base64 string, like this:

<iframe id="ifJsonFile" width="750" height="450" runat="server"></iframe>
byte[] documento_json = System.IO.File.ReadAllBytes("here is your path");
string base64_json = Convert.ToBase64String(documento_json);
ifJsonFile.Src = string.Format("data:application/pdf;base64,{0}", base64_json);

That works for me.

发布评论

评论列表(0)

  1. 暂无评论