Search code examples
javascriptgoogle-chromegoogle-chrome-extensiongoogle-chrome-devtoolschrome-extension-manifest-v3

How do you use chrome.devtools.network.onRequestFinished.addListener to read API response bodies?


I'm building a JavaScript Chrome extension (V3).

I want to be able to detect response bodies from incoming APIs whenever I'm on a website.

I'm using chrome.devtools.network.onRequestFinished.addListener but I couldn't seem to extract the response body.

Here's my code:

const getContent = async response => {
    return new Promise((resolve) => {
      response.getContent((body) => {
        resolve(body)
      })
    }) }

chrome.devtools.network.onRequestFinished.addListener(async api => {
        if (api.request.url.includes('https://developer.mozilla.org/pong/get')) {
            const responseBody = await getContent(api.response);
            console.log('Response Body:', responseBody);
        } })

I'm getting the error that 'getContent' is not a function.

Has anyone built a JavaScript Chrome extension that extracts API response bodies?


Solution

  • You need to call the .getContent() method on the variable api:

    const getContent = async response => {
        return new Promise(resolve => {
          response.getContent((body) => {
            resolve(body)
          })
        })
    }
    
    chrome.devtools.network.onRequestFinished.addListener(async api => {
        if (api.request.url.includes('https://developer.mozilla.org/pong/get')) {
            const responseBody = await getContent(api)
            console.log('Response Body:', responseBody)
        }
    })