问题
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