Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 811
Chris Kong Avatar asked Nov 30 '13 13:11

Chris Kong


1 Answers

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
]
like image 139
gkalpak Avatar answered Sep 16 '22 18:09

gkalpak