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

Viewed 938

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?

1 Answers

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

Related