Skip to content
Advertisement

How can I listen to xhr response using chrome-extension?

I want execute a function when some a chrome window gets a XHR response.

I don’t know what exactly this request is like, because of a codified param of this request, for example: api.xxx.com/rest?random=123

So I don’t think I could use

chrome.devtools.network.onRequestFinished.addListener(function callback)

or

chrome.webRequest.onCompleted.addListener(function callback)

which both need specify the request details.

Advertisement

Answer

The listeners for those events do not need you to specify the request details. On the contrary, they provide you with those details, when the get called.

Since you want to listen for any XHR request, you can define the special <all_urls> match pattern (or *://*/* to limit them to just http/https requests).

E.g.:

chrome.webRequest.onCompleted.addListener(function (details) {
  // Process the XHR response metadata. The request body is not available
  ...
}, {urls: ['<all_urls>']});

Don’t forget to declare the appropriate permissions, according to your requirements.
E.g.:

// In `manifest.json`:
...
"permissions": {
  ...
  "webRequest",
  "<all_urls>"   // <-- add this to listen for XHR from all pages
]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement