Warum ist iframe.contentWindow == null?

Ich benutze den folgenden Code, um dynamisch einen Iframe zu erstellen.

var iframe_jquery = $("<iframe>")
    .addClass("foo")
    .appendTo(container); // container is a jQuery object containing a <div> which already exists

Dann möchte ich auf sein contentWindow zugreifen, aber es ist null:

var iframe = iframe_jquery.get(0);
if (iframe){ // iFrame exists
    console.log(iframe.contentWindow); // Prints "null"
    var doc = iframe.contentWindow.document; // NullpointerException
}

Also dachte ich: "Vielleicht ist der Iframe noch nicht fertig?" Also habe ich versucht:

iframe_jquery.ready(function(){
    var iframe = iframe_jquery.get(0);
    console.log(iframe.contentWindow); // Prints "null"
    var doc = iframe.contentWindow.document; // NullpointerException
});

Gleiches Ergebnis.

Was ist falsch?

Antworten auf die Frage(5)

Ihre Antwort auf die Frage