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): fix page.off method for request event #7624

Merged
merged 3 commits into from Oct 4, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 19 additions & 3 deletions src/common/Page.ts
Expand Up @@ -16,7 +16,7 @@

import type { Readable } from 'stream';

import { EventEmitter } from './EventEmitter.js';
import { EventEmitter, Handler } from './EventEmitter.js';
import {
Connection,
CDPSession,
Expand Down Expand Up @@ -459,6 +459,7 @@ export class Page extends EventEmitter {

private _disconnectPromise?: Promise<Error>;
private _userDragInterceptionEnabled = false;
private _handlerMap = new WeakMap<Handler, Handler>();

/**
* @internal
Expand Down Expand Up @@ -623,11 +624,15 @@ export class Page extends EventEmitter {
handler: (event: PageEventObject[K]) => void
): EventEmitter {
if (eventName === 'request') {
return super.on(eventName, (event: HTTPRequest) => {
const wrap = (event: HTTPRequest) => {
event.enqueueInterceptAction(() =>
handler(event as PageEventObject[K])
);
});
};

this._handlerMap.set(handler, wrap);

return super.on(eventName, wrap);
}
return super.on(eventName, handler);
}
Expand All @@ -641,6 +646,17 @@ export class Page extends EventEmitter {
return super.once(eventName, handler);
}

off<K extends keyof PageEventObject>(
eventName: K,
handler: (event: PageEventObject[K]) => void
): EventEmitter {
if (eventName === 'request') {
handler = this._handlerMap.get(handler) || handler;
}

return super.off(eventName, handler);
}

/**
* This method is typically coupled with an action that triggers file
* choosing. The following example clicks a button that issues a file chooser
Expand Down
17 changes: 17 additions & 0 deletions test/page.spec.ts
Expand Up @@ -139,6 +139,23 @@ describe('Page', function () {
// Two now because we added the handler back.
expect(handler.callCount).toBe(2);
});

it('should correctly added and removed request events', async () => {
const { page, server } = getTestState();

const handler = sinon.spy();
page.on('request', handler);
await page.goto(server.EMPTY_PAGE);
expect(handler.callCount).toBe(1);
page.off('request', handler);
await page.goto(server.EMPTY_PAGE);
// Still one because we removed the handler.
expect(handler.callCount).toBe(1);
page.on('request', handler);
await page.goto(server.EMPTY_PAGE);
// Two now because we added the handler back.
expect(handler.callCount).toBe(2);
});
});

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