Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(page): fallback to default in exposeFunction when using imported module #6365

Merged
merged 8 commits into from Sep 29, 2021
2 changes: 1 addition & 1 deletion docs/api.md
Expand Up @@ -1868,7 +1868,7 @@ await page.evaluateOnNewDocument(preloadFile);
#### page.exposeFunction(name, puppeteerFunction)

- `name` <[string]> Name of the function on the window object
- `puppeteerFunction` <[function]> Callback function which will be called in Puppeteer's context.
- `puppeteerFunction` <[function]> Callback function which will be called in Puppeteer's context. Can also be a module with a default export.
- returns: <[Promise]>

The method adds a function called `name` on the page's `window` object.
Expand Down
16 changes: 14 additions & 2 deletions src/common/Page.ts
Expand Up @@ -1360,13 +1360,25 @@ export class Page extends EventEmitter {
*/
async exposeFunction(
name: string,
puppeteerFunction: Function
puppeteerFunction: Function | { default: Function }
): Promise<void> {
if (this._pageBindings.has(name))
throw new Error(
`Failed to add page binding with name ${name}: window['${name}'] already exists!`
);
this._pageBindings.set(name, puppeteerFunction);

let exposedFunction: Function;
if (typeof puppeteerFunction === 'function') {
exposedFunction = puppeteerFunction;
} else if (typeof puppeteerFunction.default === 'function') {
exposedFunction = puppeteerFunction.default;
} else {
throw new Error(
`Failed to add page binding with name ${name}: ${puppeteerFunction} is not a function or a module with a default export.`
);
}

this._pageBindings.set(name, exposedFunction);

const expression = helper.pageBindingInitString('exposedFun', name);
await this._client.send('Runtime.addBinding', { name: name });
Expand Down
14 changes: 14 additions & 0 deletions test/page.spec.ts
Expand Up @@ -1016,6 +1016,20 @@ describe('Page', function () {
);
expect(result.x).toBe(7);
});
it('should fallback to default export when passed a module object', async () => {
const { page, server } = getTestState();
const moduleObject = {
default: function (a, b) {
return a * b;
},
};
await page.goto(server.EMPTY_PAGE);
await page.exposeFunction('compute', moduleObject);
const result = await page.evaluate(async function () {
return await globalThis.compute(9, 4);
});
expect(result).toBe(36);
});
});

describeFailsFirefox('Page.Events.PageError', function () {
Expand Down