みかづきブログ その3

本ブログは更新を終了しました。通算140万ユーザーの方に観覧頂くことができました。長い間、ありがとうございました。

👆

引越し先はこちらです!

同一ドメインのiframe内にアクセスする

IEとかもろもろを考えると、iframeのcontentWindowにアクセスするのがベストな気がしています。
その際、iframeのonloadを待たないとうまくいかないのでご注意を。


JavaScript

(function(win, doc) {

    "use strict";
    
    var iframe = doc.getElementById("iframe");
    
    iframe.onload = function() {
        console.log(iframe.contentWindow.document.body);
    };
    
})(this, document);

DEMO



また、iframe内に新たな要素を追加する際、documentではなく、iframeのcontentWindow.documentをつかってcreateElementをしないとIE6でエラーになるらしいです。
自分、IE6対応をしたことがないブラウザゆとり世代なんで実際に経験したことはないですが。


JavaScript

(function(win, doc) {

    "use strict";
    
    var iframe = doc.getElementById("iframe"),
        h2 = doc.createElement("h2");
    
    h2.innerText = "Hello I'm H2.";
    h2.style.cssText = "position: relative; z-index: 1;";
    
    iframe.onload = function() {
        var h3 = iframe.contentWindow.document.createElement("h3");
        
        h3.innerText = "Hello I'm H3.";
        h3.style.cssText = "position: relative; z-index: 1;";

        iframe.contentWindow.document.body.appendChild(h2); // IE6でエラーになるらしい
        iframe.contentWindow.document.body.appendChild(h3); // IE6でもOK
    };
    
})(this, document);

DEMO



今回は以上です。