Difference between contentDocument and contentWindow javascript iframe/frame access properties

I think the <iframe> MDN documentation explains it well:

With the DOM HTMLIFrameElement object, scripts can access the window object of the framed resource via the contentWindow property. The contentDocument property refers to the document inside the <iframe>, same as contentWindow.document.

From the inside of a frame, a script can get a reference to its parent window with window.parent.

Script access to a frame’s content is subject to the same-origin policy. Scripts cannot access most properties in other window objects if the script was loaded from a different origin…

So you would use contentWindow the same way you use window and contentDocument as you use document.

Also note how it relates to the frames property

window.frames[0] is the same thing as document.getElementsByTagName("iframe")[0].contentWindow

So these statements are true:

// the window property refers to itself https://developer.mozilla.org/en-US/docs/Web/API/Window/window
window.frames[0] 
=== window.frames[0].window;

// the frames' window *is the same* as contentWindow
window.frames[0].window
=== document.querySelector("iframe").contentWindow;

// the frames' document *is the same* as contentDocument
window.frames[0].window.document
=== document.querySelector("iframe").contentDocument;

Leave a Comment