简体   繁体   中英

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.

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).

Eg:

chrome.webRequest.onCompleted.addListener(function (details) {
  // Process the XHR response.
  ...
}, {urls: ['<all_urls>']});

Don't forget to declare the appropriate permissions, according to your requirements.
Eg:

// In `manifest.json`:
...
"permissions": {
  ...
  "webRequest",
  "<all_urls>"   // <-- add this to listen for XHR from all pages
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM