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

Deadly 提交于 2021-02-10 05:22:30

问题


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:


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'));


来源:https://stackoverflow.com/questions/65414739/in-puppeteer-how-to-access-exports-from-a-script-injected-using-page-addscriptt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!