我想使用 Puppeteer 从放置在页面上 iframe 内的选择器中获取数据,该页面在与其父框架域不同的域上运行。 因此,我不是任何域的所有者 - 无法使用 frame.postMessage。
试图用
引用选择器document.querySelector('#selector_inside_iframe')
但是由于 iframe 中的选择器 - 它在主上下文中是不可见的。尝试使用时
document.querySelector('#selector_inside_iframe').contentWindow.document
因为 iframe 使用不同的域 - 它被 CORS 阻止。 它在 Chrome 控制台选项卡上的 JS 上下文下拉列表中手动更改 JS 上下文时有效,但是,它需要使用 Puppeteer 来完成。
我希望获得对节点“#selector_inside_iframe”的引用,但如果不更改 Chrome 开发工具中的上下文,则会出现以下错误:
'Uncaught DOMException: Blocked a frame with origin "https://blah.some_domain.com" from accessing a cross-origin frame'
最佳答案
我能够使用 Puppeter 的 ElementHandle.contentFrame()
解决它。
首先使用
作为ElementHandle
对象获取对 iframe
选择器的引用
const iframeHandle = await page.$('iframe')
然后使用 ElementHandle.contentFrame()
引用 iframe
上下文,如下所示:
const contentFrame = await iframeHandle.contentFrame()
现在查询 iframe 中的 html/css 选择器只需使用 contentFrame
例如:
contentFrame.$('.data_class')
关于javascript - 如何使用 Puppeteer 或 Chrome 控制台以编程方式切换 JS 上下文(到不同域的 iframe 上下文),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57747143/