Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(page): fix page.off method for request event (#7624)
This patch fixes page.off for request event

Closes: #7572
  • Loading branch information
edgardmessias committed Oct 4, 2021
1 parent 30ac9d1 commit d0cb943
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
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

0 comments on commit d0cb943

Please sign in to comment.