要获得一个动态创建的 <iframe> 的 window 对象,你可以在监听到该 <iframe> 被添加后,直接使用其 contentWindow 属性。以下是如何获取并使用这个 window 对象的示例代码:
示例代码
// 创建一个 MutationObserver 实例
const observer = new MutationObserver((mutationsList, observer) => {
    for (let mutation of mutationsList) {
        // 判断是否是子节点添加了新节点
        if (mutation.type === 'childList') {
            mutation.addedNodes.forEach(node => {
                // 检查新添加的节点是否为 iframe
                if (node.nodeName === 'IFRAME') {
                    console.log('新的 iframe 被创建:', node);
                    
                    // 获取 iframe 的 window 对象
                    const iframeWindow = node.contentWindow;
                    // 在这里可以执行其他操作,比如与 iframe 内部通信
                    if (iframeWindow) {
                        console.log('iframe 的 window 对象:', iframeWindow);
                        // 可以调用 iframe 中的方法或访问其内容等
                        // 例如,获取文档对象:
                        const iframeDocument = iframeWindow.document;
                        
                        // 可以进一步进行操作,例如打印输出 document.title:
                        console.log('iframe 文档标题:', iframeDocument.title);
                    }
                }
            });
        }
    }
});
// 配置观察选项:需要观察子节点的变化
const config = { childList: true, subtree: true };
// 启动观察,目标是 document.body 或者其他具体元素
observer.observe(document.body, config);
// 可选:在适当的时候停止观察,例如:
/* 
observer.disconnect();
*/
解释
获取
window对象:- 当检测到新创建的 
<iframe>后,通过node.contentWindow来访问该<iframe>的window对象。 
- 当检测到新创建的 
 访问内容和方法:
- 使用得到的 
window对象,你可以进行多种操作,比如访问它内部的文档(通过contentWindow.document)或者调用其方法。 
- 使用得到的 
 
注意事项
- 确保你有权限访问该 
<iframe>的内容。如果<iframe>指向不同域(跨域),则由于同源策略(Same-Origin Policy),你将无法访问其中的任何内容,包括其window和document。 - 如果是跨域情况,可以考虑使用 postMessage API 进行安全的数据传输。
内容由零声教学AI助手提供,问题来源于学员提问 


        
        
        
        
        
        
        
        
        
        
                
                
                
                
                
                
                