17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

XMLHTTPRequestとiframeとpostMessageでクロスドメイン通信

Last updated at Posted at 2012-11-23

http://vps.will-co21.net/test/html5proxy/postMessageCrossDomain.html?/formdatapost/tmp/hoge.png
html5のpostMessageとXMLHTTPRequestとiframeを組み合わせて画像のバイナリをXMLHTTPRequestで取得して
base64エンコードしたものをiframeからpostMessageで別ドメインの親ウィンドウに送って
dataURLにして画像として表示。
親ウィンドウ

window.onload = function () {
    require(["base64"], function (lib ) {
        var base64 = lib.base64;
       
        var iframe = document.createElement("iframe");
        iframe.src = "http://habrashi.s351.xrea.com/htmlproxy/proxy.html?" + encodeURIComponent(window.location.search.substr(1));
        iframe.setAttribute("id", "xhrframe");
        document.body.appendChild(iframe);
       
        window.addEventListener("message", function (e) {
            var data = e.data;
            img = document.createElement("img");
            img.src = "data:image/png;base64," + data;
            document.getElementById("content").appendChild(img);
        });
    });
}

子ウィンドウ

window.onload = function () {
    var target = (parent && parent.postMessage ? parent : (parent && parent.document.postMessage ? parent.document : undefined));
    require(["base64"], function (lib ) {
        var xhr = new XMLHttpRequest();
        var base64 = lib.base64;

        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4){
                var res = xhr.responseText;
                var bytes = [];
               
                for(var i=0, len = res.length; i < len; i++) bytes.push(String.fromCharCode(res.charCodeAt(i) & 0xff));
                var data = bytes.join("");
               
                base64String = base64.encode(data);
               
                if (typeof target != "undefined") {
                    target.postMessage(base64String, '*');
                }
            }
        }
        var url = decodeURIComponent(window.location.search.substr(1));
        xhr.open("GET", url, true);
        xhr.overrideMimeType("text/plain; charset=x-user-defined");
        xhr.send(null);
    });
}
17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?