gdoron
gdoron

Reputation: 150293

Block video requests on puppeteer

I want to block(abort) all requests to video resources, how can I achieve it with puppeteer?

I see there is an example in the documentation:

An example of a naïve request interceptor that aborts all image requests:

page.on('request', interceptedRequest => {
    if (interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg'))
      interceptedRequest.abort();
    else
      interceptedRequest.continue();
});

But I can't seem to find an example on how to block videos.
Only the response headers says the content-type and I don't want to waste the bandwidth for vain.

Upvotes: 3

Views: 3485

Answers (1)

gdoron
gdoron

Reputation: 150293

Great question, had the same issue myself.😉

The main problem is videos URLs don't have to end with a specific suffix and indeed they don't on many websites (YouTube for example).

But there this function:

request.resourceType()

Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the following: document, stylesheet, image, media, font, script, texttrack, xhr, fetch, eventsource, websocket, manifest, other.

A bit of Googling and found this MDN:

media

Resources loaded by a <video> or <audio> element.

And as I don't mind on blocking audio requests as well (thanks God, they are not in use in normal web pages...)

Eventually this is what I ended up doing:

page.on('request', request => {
    const url = request.url().toLowerCase();
    const resourceType = request.resourceType();

    if (
        resourceType === 'media' ||
        url.endsWith('.mp4') ||
        url.endsWith('.avi') ||
        url.endsWith('.flv') ||
        url.endsWith('.mov') ||
        url.endsWith('.wmv')
    ) {
        console.log(`ABORTING: video`);
        request.abort();
    } else {
        request.continue();
    }
});

Upvotes: 11

Related Questions