1
const puppeteer = require('puppeteer');

async function run () {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);
    await page.$eval('input[type=submit]', el => el.click());
    await page.screenshot({path: 'screenshot.png'});
    browser.close();
}
run();

When I run this with any site like 'node screenshot.js "https://github.com/login"' it works as expected but with storybook, it simply can't find elements even tho I can't select them from the console fine. Is there something with storybook not supporting puppeteer? Is there a different tool to hover/click on storybook components in headless browser?

0

1 Answer 1

2

Storybook presents the components/elements inside an iframe, which means a regular document.querySelector cannot find them.

The reason it seems to work in the console is that the console switches context for document as soon as you activate the iframe, e.g. by clicking anywhere inside of it, or focussing an element inside of it.

To solve the issue, find the iframe like this (this example uses the DOM API, you need to find the puppeteer way to do this):

const iframe = document.querySelector('#storybook-preview-iframe');

Then, to find your element:

let el = iframe.contentDocument.querySelector('input[type=submit]');

Here's what it would look like in puppeteer:

const elementHandle = await page.waitForSelector('#storybook-preview-iframe');
const frame = await elementHandle.contentFrame();
await frame.waitForSelector('input[type=submit]');
const el = await frame.$('input[type=submit]');
el.click();
2
  • ty so much, if anybody else tries this code I needed another await before "frame.$('input[type=submit]');" Commented Mar 8, 2022 at 12:24
  • Ty, edited that in.
    – connexo
    Commented Mar 8, 2022 at 12:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.