たぼさんの部屋

いちょぼとのんびり

jsonの送受信:postMessage

JSON.stringify

JSON文字列をオブジェクトに変換して返します。

JSON. parse

オブジェクトをJSON文字列に変換して返します。

iframe側の送信例:iframeの高さを送信する
形式:height:***

iframeからの送信

// iframe.bodyの高scrollHeightさをpostMessageで送信します。
var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
var message = {"height":document.body.scrollHeight};//jsonオブジェクトで記述しました。
jsonmessage = JSON.stringify(message);//json形式に変換
 if (typeof target !== "undefined" && document.body.scrollHeight){
    target.postMessage(jsonmessage, "*");
 }

親documentでの受信

var json = JSON.parse(event.data);
   if (json.height) {
                   
        _iframe.style.height = json.height + "px";
   }