In puppeteer how to access exports from a script injected using 'page.addScriptTag'?

Viewed 179

In a puppeteer script I want to inject some utility functions to a webpage via page.addScriptTag and use some exports defined in the file.

  await page.addScriptTag({path: './utils/browser.js', type: 'module'})
  await page.evaluate(() => {
    // how do I do `import { foo } from './utils/browser.js'` here?
  })

The injected file looks like this:

export function foo() {}

I'm using '"type": "module"' in my package.json if this is relevant.

1 Answers

You can try dynamic import() with 'data:' URLs:

  await page.evaluate(async (source) => {
    const { foo } = await import(`data:text/javascript,${source}`);
  }, fs.readFileSync('./utils/browser.js', 'utf8'));
Related