How do you import local modules in the browser context with Playwright?

4k Views Asked by At

Here's an example of what I'm trying to do:

../src/Foo/Bar.ts is a local typescript file

The code in the file is meant to run in a browser context (it accesses WebSockets), so I need to run it in page.evaluate

page.evaluate( async () => {
    const { namedExportExample } = await import('../src/Foo/Bar;)

    // ...
});

I get page.evaluate: TypeError: Failed to resolve module specifier and I'm not surprised, I'm not sure how the browser can evaluate that import, but I'd like to know if there's a way to do this if possible?

2

There are 2 best solutions below

2
On

Playwright scripts run in your Playwright environment. Your page scripts run in the browser page environment. Those environments don't intersect, they are running in different virtual machines in different processes and even potentially on different computers.

In your scenario you try to import your file inside the page, which does not know anything about where to import that file. You need to stringify your function and pass it over the page to evaluate it.

See here for more information: https://playwright.dev/docs/evaluating

0
On

I'm not sure how the browser can evaluate that import, but I'd like to know if there's a way to do this if possible?

You can't import modules for reasons explained by @max-schmitt. But Playwright's "Context" provides a way to inject new functions in the browser instance.

browserContext.exposeFunction(name, callback)

https://playwright.dev/docs/api/class-browsercontext#browser-context-expose-function

Example
import * as crypto from "node:crypto" 

const browser = await chromium.launch(...)
const context = await browser.newContext()
    
// !!! Exposing a new function !!!
await context.exposeFunction("sha256", text => crypto.createHash('sha256').update(text).digest("hex")) 

const page = await context.newPage()
await page.goto(URL)

...
await someBox.evaluate((box : HTMLElement) => {
  console.log("!!!", window["sha256"]) // available !!!
  ...
})