最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to switch JS contexts(to iframe context of different domain) programatically using Puppeteer or Chrome console

programmeradmin2浏览0评论

I want to use Puppeteer to get data from selectors that are placed inside an iframe on a page which runs on a different domain from it's parent's frame domain. I am not the owner of any of the domains therefore - can't use frame.postMessage.

tried to refer to the selector with

document.querySelector('#selector_inside_iframe')

but since the selector inside an iframe - it is invisible from the main context. When tried to use

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

because the iframe uses different domain - it is blocked by CORS. It works when changing manually the JS context in the JS contexts dropdown on the console tab of Chrome, however, it need to be done using Puppeteer.

I expect to get reference to node '#selector_inside_iframe' but getting the following error if not changing context inside Chrome dev-tools:

'Uncaught DOMException: Blocked a frame with origin "" from accessing a cross-origin frame'

I want to use Puppeteer to get data from selectors that are placed inside an iframe on a page which runs on a different domain from it's parent's frame domain. I am not the owner of any of the domains therefore - can't use frame.postMessage.

tried to refer to the selector with

document.querySelector('#selector_inside_iframe')

but since the selector inside an iframe - it is invisible from the main context. When tried to use

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

because the iframe uses different domain - it is blocked by CORS. It works when changing manually the JS context in the JS contexts dropdown on the console tab of Chrome, however, it need to be done using Puppeteer.

I expect to get reference to node '#selector_inside_iframe' but getting the following error if not changing context inside Chrome dev-tools:

'Uncaught DOMException: Blocked a frame with origin "https://blah.some_domain." from accessing a cross-origin frame'
Share Improve this question asked Sep 1, 2019 at 15:09 Stas EzerskyStas Ezersky 3533 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

I was able to solve it by using Puppeter's ElementHandle.contentFrame() .

first get reference to the iframe selector as ElementHandle object using

const iframeHandle = await page.$('iframe')

then refer to the iframe context with ElementHandle.contentFrame() like this:

const contentFrame = await iframeHandle.contentFrame()

Now to query the html/css selectors inside the iframe just use the contentFrame such as the following:

contentFrame.$('.data_class')

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论