2022-07-05 13:41:43 +00:00
---
sidebar_label: Page.exposeFunction
---
# Page.exposeFunction() method
The method adds a function called `name` on the page's `window` object. When called, the function executes `puppeteerFunction` in node.js and returns a `Promise` which resolves to the return value of `puppeteerFunction` .
If the puppeteerFunction returns a `Promise` , it will be awaited.
2022-08-10 21:34:29 +00:00
:::note
Functions installed via `page.exposeFunction` survive navigations.
2024-03-20 15:03:14 +00:00
:::
2022-07-05 13:41:43 +00:00
2022-10-24 07:07:05 +00:00
#### Signature:
2022-07-05 13:41:43 +00:00
```typescript
class Page {
2023-09-11 10:46:17 +00:00
abstract exposeFunction(
2022-07-05 13:41:43 +00:00
name: string,
pptrFunction:
| Function
| {
default: Function;
}
): Promise< void > ;
}
```
## Parameters
2024-03-20 15:03:14 +00:00
< table > < thead > < tr > < th >
Parameter
< / th > < th >
Type
< / th > < th >
Description
< / th > < / tr > < / thead >
< tbody > < tr > < td >
name
< / td > < td >
string
< / td > < td >
Name of the function on the window object
< / td > < / tr >
< tr > < td >
pptrFunction
< / td > < td >
Function \| { default: Function; }
< / td > < td >
Callback function which will be called in Puppeteer's context.
2022-07-05 13:41:43 +00:00
2024-03-20 15:03:14 +00:00
< / td > < / tr >
< / tbody > < / table >
2022-07-05 13:41:43 +00:00
**Returns:**
Promise< void>
2022-08-10 21:34:29 +00:00
## Example 1
2022-07-05 13:41:43 +00:00
An example of adding an `md5` function into the page:
```ts
2022-12-09 12:57:39 +00:00
import puppeteer from 'puppeteer';
import crypto from 'crypto';
2022-07-05 13:41:43 +00:00
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('md5', text =>
crypto.createHash('md5').update(text).digest('hex')
);
await page.evaluate(async () => {
// use window.md5 to compute hashes
const myString = 'PUPPETEER';
const myHash = await window.md5(myString);
console.log(`md5 of ${myString} is ${myHash}`);
});
await browser.close();
})();
```
2022-08-10 21:34:29 +00:00
## Example 2
2022-07-05 13:41:43 +00:00
An example of adding a `window.readfile` function into the page:
```ts
2022-12-09 12:57:39 +00:00
import puppeteer from 'puppeteer';
import fs from 'fs';
2022-07-05 13:41:43 +00:00
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('readfile', async filePath => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, text) => {
if (err) reject(err);
else resolve(text);
});
});
});
await page.evaluate(async () => {
// use window.readfile to read contents of a file
const content = await window.readfile('/etc/hosts');
console.log(content);
});
await browser.close();
})();
```