allow import in js

This commit is contained in:
Tommy D. Rossi
2025-11-16 15:36:37 +01:00
parent 94471a43c9
commit 159eec32d0
2 changed files with 24 additions and 2 deletions
+8 -2
View File
@@ -31,6 +31,8 @@ interface VMContext {
}
accessibilitySnapshot: (page: Page) => Promise<string>
resetPlaywright: () => Promise<{ page: Page; context: BrowserContext }>
require: NodeRequire
import: (specifier: string) => Promise<any>
}
const state: State = {
@@ -230,12 +232,16 @@ server.tool(
state,
console: customConsole,
accessibilitySnapshot,
resetPlaywright: vmContextObj.resetPlaywright
resetPlaywright: vmContextObj.resetPlaywright,
require,
import: vmContextObj.import
}
Object.keys(vmContextObj).forEach(key => delete (vmContextObj as any)[key])
Object.assign(vmContextObj, resetObj)
return { page: newPage, context: newContext }
}
},
require,
import: (specifier: string) => import(specifier)
}
const vmContext = vm.createContext(vmContextObj)
+16
View File
@@ -13,6 +13,8 @@ it will control an existing user Chrome window. The js code will be run in a sa
- state: an object shared between runs that you can mutate to persist functions and objects. for example `state.requests = []` to monitor network requests between runs
- context: the playwright browser context. you can do things like `await context.pages()` to see user connected pages
- page, the first page the user opened and made it accessible to this MCP. do things like `page.url()` to see current url. assume the user wants you to use this page for your playwright code
- require: node's require function to load CommonJS modules
- import: async import function to dynamically import ES modules. for example `const fs = await import('node:fs')`
the chrome window can have more than one page. you can see other pages with `context.pages().find((p) => p.url().includes('localhost'))`. you can also open and close pages: `state.newPage = await context.newPage()`. store the page in state so that you can reuse it later
@@ -113,3 +115,17 @@ later, you can read logs that you care about. For example, to get the last 100 l
`console.log('errors:'); state.logs.filter(log => log.type === 'error').slice(-100).forEach(x => console.log(x))`
then to reset logs: `state.logs = []` and to stop listening: `page.removeAllListeners('console')`
## loading file content into inputs
you can use the `import` function to read files and fill inputs with their content:
```js
const fs = await import('node:fs'); const content = fs.readFileSync('/path/to/file.txt', 'utf-8'); await page.locator('textarea').fill(content)
```
for example, to fill a textarea with the content of a markdown file:
```js
const fs = await import('node:fs'); const readme = fs.readFileSync('./README.md', 'utf-8'); await page.locator('#description').fill(readme); console.log('Filled textarea with README content')
```