Skip to content

Commit

Permalink
puppeteer: added support for cooperative mode. (#2281)
Browse files Browse the repository at this point in the history
  • Loading branch information
akornatskyy committed Oct 18, 2021
1 parent 83015b6 commit 66c340c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 15 deletions.
4 changes: 4 additions & 0 deletions package.json
Expand Up @@ -36,6 +36,10 @@
{
"name": "Anton Lazarev",
"email": "antonok35@gmail.com"
},
{
"name": "Andriy Kornatskyy",
"email": "andriy.kornatskyy@live.com"
}
],
"license": "MPL-2.0",
Expand Down
41 changes: 26 additions & 15 deletions packages/adblocker-puppeteer/adblocker.ts
Expand Up @@ -105,6 +105,8 @@ export class BlockingContext {
*/
export class PuppeteerBlocker extends FiltersEngine {
private readonly contexts: WeakMap<puppeteer.Page, BlockingContext> = new WeakMap();
// Defaults to undefined which preserves Legacy Mode behavior
private priority: number | undefined = undefined;

// ----------------------------------------------------------------------- //
// Helpers to enable and disable blocking for 'browser'
Expand Down Expand Up @@ -277,6 +279,9 @@ export class PuppeteerBlocker extends FiltersEngine {
} while (true);
};

public setRequestInterceptionPriority = (defaultPriority = 0) =>
(this.priority = defaultPriority);

public onRequest = (details: puppeteer.HTTPRequest): void => {
const request = fromPuppeteerDetails(details);
if (this.config.guessRequestTypeFromUrl === true && request.type === 'other') {
Expand All @@ -289,32 +294,38 @@ export class PuppeteerBlocker extends FiltersEngine {
request.isMainFrame() ||
(request.type === 'document' && frame !== null && frame.parentFrame() === null)
) {
details.continue();
details.continue(details.continueRequestOverrides(), this.priority);
return;
}

const { redirect, match } = this.match(request);

if (redirect !== undefined) {
if (redirect.contentType.endsWith(';base64')) {
details.respond({
status: 200,
headers: {},
body: Buffer.from(redirect.body, 'base64'),
contentType: redirect.contentType.slice(0, -7),
});
details.respond(
{
status: 200,
headers: {},
body: Buffer.from(redirect.body, 'base64'),
contentType: redirect.contentType.slice(0, -7),
},
this.priority,
);
} else {
details.respond({
status: 200,
headers: {},
body: redirect.body,
contentType: redirect.contentType,
});
details.respond(
{
status: 200,
headers: {},
body: redirect.body,
contentType: redirect.contentType,
},
this.priority,
);
}
} else if (match === true) {
details.abort('blockedbyclient');
details.abort('blockedbyclient', this.priority);
} else {
details.continue();
details.continue(details.continueRequestOverrides(), this.priority);
}
};

Expand Down

0 comments on commit 66c340c

Please sign in to comment.