Chrome扩展:后台脚本捕获网络和HTTP错误 [英] Chrome Extensions: Background Script Catch Network and HTTP Errors
问题描述
我正在为非常具体的案例(网站自动化)开发一个小型Chrome扩展程序供个人使用,但我有一个问题。我如何在后台脚本上捕获网络错误并调用某个功能。
我已经实现了这种方法:
pre>
chrome.webRequest.onErrorOccurred.addListener(
handleNetworkError,
{urls:[http:// * / *,https:// * / *]
});
它捕获一些网络错误,从我看到的男人 :: net
错误,DNS失败,网络更改等。
但是今天我注意到HTTP错误如:
GET https://example.com 522(Origin Connection Time-out)
没有触发听众,我该怎么做也可以这样做?
在用户@Xan的帮助下,我设法提出了这一点:
function extractStatus (行){
var match = line.match(/ [^] *(\d {3})(。*)/);
if(match)
return {code:match [1],message:match [2]};
else
return undefined;
}
chrome.tabs.query({active:true,lastFocusedWindow:true},function(tabsArray){
tab = tabsArray [0];
scope = {urls:[https://example.com/*],tabId:tab.id};
console.log(Listening for errors ...);
// :: net errors
chrome.webRequest.onErrorOccurred.addListener(handleNetworkError,scope);
// HTTP错误
chrome.webRequest.onHeadersReceived.addListener(function(细节){
var status = extractStatus(details.statusLine);
if(!status)
return;
if(status.code。 charAt(0)=='5'|| status.code.charAt(0)=='4')
handleNetworkError();
},scope);
});
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 script and call a certain function.
I've implemented this method:
chrome.webRequest.onErrorOccurred.addListener(
handleNetworkError,
{urls: ["http://*/*", "https://*/*"]
});
It catches some network errors, from what I see manly ::net
errors, DNS failing, networks changed etc.
However today I noticed that HTTP errors like:
GET https://example.com 522 (Origin Connection Time-out)
didn't trigger the listener, how can I make it work on those too?
With help of the the user @Xan, I managed to come up with this:
function extractStatus(line) {
var match = line.match(/[^ ]* (\d{3}) (.*)/);
if (match)
return {code: match[1], message: match[2]};
else
return undefined;
}
chrome.tabs.query({active: true, lastFocusedWindow: true }, function(tabsArray) {
tab = tabsArray[0];
scope = {urls: ["https://example.com/*"], tabId: tab.id};
console.log("Listening for errors...");
// ::net errors
chrome.webRequest.onErrorOccurred.addListener(handleNetworkError, scope);
// HTTP errors
chrome.webRequest.onHeadersReceived.addListener(function(details) {
var status = extractStatus(details.statusLine);
if (!status)
return;
if (status.code.charAt(0) == '5' || status.code.charAt(0) == '4')
handleNetworkError();
}, scope);
});
这篇关于Chrome扩展:后台脚本捕获网络和HTTP错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!