Chrome Extensions: Background Script Catch Network and HTTP Errors

后端 未结 2 809
再見小時候
再見小時候 2021-01-07 04:11

I\'m developing a small Chrome extension for personal use on a very specific case (website automation) but I\'ve a problem. How can I catch a network error on a background s

2条回答
  •  不知归路
    2021-01-07 05:07

    I assume that from the perspective of webRequest / Chrome's network stack, this request actually completed. So you need to hook to some other event, e.g.

    function extractStatus(line) {
      var match = line.match(/[^ ]* (\d{3}) (.*)/);
      if(match) {
        return {code: match[1], message: match[2]};
      } else {
        return undefined;
      }
    }
    
    chrome.webRequest.onHeadersReceived.addListener(
      function(details) {
        var status = extractStatus(details.statusLine);
        if(status) {
          // Do something based on status.code
        }
      },
      {urls: [""]}
    );
    

    Note that this event is optionally blocking: you can redirect the request if needed.

    Obviously, this will create a lot of work for your extension; in the above snippet, the listener is not blocking, but if you do make it blocking it will slow down your Chrome considerably - only use it when absolutely necessary and filter by URL when appropriate.

提交回复
热议问题