javascript - 如何使用 Puppeteer 或 Chrome 控制台以编程方式切换 JS 上下文(到不同域的 iframe 上下文)

标签 javascript google-chrome iframe google-chrome-devtools puppeteer

我想使用 Puppeteer 从放置在页面上 iframe 内的选择器中获取数据,该页面在与其父框架域不同的域上运行。 因此,我不是任何域的所有者 - 无法使用 frame.postMessage。

试图用

引用选择器
document.querySelector('#selector_inside_iframe')

但是由于 iframe 中的选择器 - 它在主上下文中是不可见的。尝试使用时

document.querySelector('#selector_inside_iframe').contentWindow.document

因为 iframe 使用不同的域 - 它被 CORS 阻止。 它在 Chrome 控制台选项卡上的 JS 上下文下拉列表中手动更改 JS 上下文时有效,但是,它需要使用 Puppeteer 来完成。

JS context dropdown

我希望获得对节点“#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/

相关文章:

javascript - 使用 JavaScript 从外部文件读取 CSS?

javascript - 按钮标签在脚本标签内不起作用

iframe - 内容安全策略指令: "frame-ancestors ' self'

javascript - Iframe - 在内部运行函数

html - 在 iframe 中隐藏滚动条,同时仍在滚动

javascript - 正则表达式在数组中查找对

javascript - 对整个文档进行所见即所得的 HTML 编辑?

node.js - 运行 V8 javascript 引擎示例代码时出错

javascript - 使用开发工具 - 缺少 Prop 。如何找到我的申请中要查找的类别?

android - 如何在 Android 模拟器上运行新的 Chrome for Android 4?