Skip to content
Permalink
Browse files
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 d0cb9436a302418086f6763e0e58ae3732a20b62
Showing with 36 additions and 3 deletions.
  1. +19 −3 src/common/Page.ts
  2. +17 −0 test/page.spec.ts
@@ -16,7 +16,7 @@

import type { Readable } from 'stream';

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

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

/**
* @internal
@@ -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);
}
@@ -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
@@ -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 () {

0 comments on commit d0cb943

Please sign in to comment.