Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept a certain request and get its response (puppeteer)

Once that puppeteer goes to a certain url, I want that it listens to all the requests that are made, then find a specific request and return its response. The response should be a json object.

I managed in listening to all the requests and intercepting the desired one, but I don't know how to get its response. Here's my attempt: I get the error TypeError: Cannot read property 'then' of null.

Any suggestion?

page.on('request',async(request)=>{
    console.log(request.url())

    if (request.url().includes('desiredrequest.json')){
        console.log('Request Intercepted')
        request.response().then(response => {
            return response.text();
        }).then(function(data) {
        console.log(data); // this will be a string
        alert(data)
        });
    }

    request.continue()
})
like image 272
Drun Avatar asked Mar 07 '20 16:03

Drun


1 Answers

Since the response may have not arrived yet, the better method would be listening on the response event and get the request object from it.

page.on('response', async(response) => {
    const request = response.request();
    if (request.url().includes('desiredrequest.json')){
        const text = await response.text();
        console.log(text);
    }
})
like image 170
mbit Avatar answered Nov 16 '22 15:11

mbit