@@ -247,15 +247,25 @@ export function generateCSSClasses(styleMap) {
247247 * Fixes #371 (pseudos in iframe body not rendering when capturing body only).
248248 *
249249 * @param {Element } el
250- * @returns {Window }
250+ * @returns {Window|null }
251251 */
252252function getWindowForElement ( el ) {
253253 try {
254254 const doc = el ?. ownerDocument
255- const win = doc ?. defaultView
255+ if ( ! doc ) return typeof window !== 'undefined' ? window : null
256+ let win = doc . defaultView
256257 if ( win && typeof win . getComputedStyle === 'function' ) return win
258+ // In some environments (e.g. srcdoc iframe before fully ready) defaultView can be null.
259+ // Find the frame whose document is this document so we use the iframe's window.
260+ if ( typeof window !== 'undefined' && window . frames ) {
261+ for ( let i = 0 ; i < window . frames . length ; i ++ ) {
262+ try {
263+ if ( window . frames [ i ] ?. document === doc ) return window . frames [ i ]
264+ } catch { /* cross-origin */ }
265+ }
266+ }
257267 } catch { /* cross-origin etc */ }
258- return typeof window !== 'undefined' ? window : ( el ?. ownerDocument ?. defaultView || null )
268+ return typeof window !== 'undefined' ? window : null
259269}
260270
261271/**
@@ -311,7 +321,10 @@ export function getStyle(el, pseudo = null) {
311321
312322 if ( ! st && typeof window !== 'undefined' && typeof window . getComputedStyle === 'function' ) {
313323 try {
314- st = window . getComputedStyle ( el , pseudo )
324+ // Only use global window when the element belongs to the same document (e.g. avoid iframe cross-document call).
325+ if ( el . ownerDocument === document ) {
326+ st = window . getComputedStyle ( el , pseudo )
327+ }
315328 } catch {
316329 // ignore; handled below
317330 }
0 commit comments