嘿,Chrome开发者的朋友们,当chrome.extension.sendRequest出现故障时,人们该如何去检测呢?我试过了,没有发现:
chrome.extension.sendRequest({ /* message stuff here */ }, function(req){
if(req == null || chrome.extension.lastError == null){
alert("No response. :(");
}
});但发生的情况是,回调甚至从未触发,这是我所期望的一半。当sendRequest出现故障时,有什么方法可以检测到吗?
谢谢!
发布于 2012-04-10 18:25:58
你需要改变...
if(req == null || chrome.extension.lastError == null){
alert("No response. :(");
}...to...
if(req == null){
alert("No response. :( and the error was "+chrome.extension.lastError.message);
}正如文档所说的那样,sendRequest If an error occurs while connecting to the extension, the callback will be called with no arguments and chrome.extension.lastError will be set to the error message.
http://code.google.com/chrome/extensions/extension.html#method-sendRequest
http://code.google.com/chrome/extensions/extension.html#property-lastError
发布于 2012-04-10 19:06:55
您可以使用try{}catch(err){}将其括起来以捕获抛出的任何错误,但如果没有响应,则不会抛出错误,并且也没有null响应。
这应该是设计好的,允许消息接收者做它自己的事情。例如,它可能涉及几个web服务请求,或者可能需要一段时间的ajax请求。
如果您知道响应需要多长时间,就应该实现一个超时(如果sendRequest函数包含一个超时就更好了)。
所以,你可以这样做:
var noResponse = setTimeout(100, function() {
alert('No response received within 100ms!');
});
chrome.extension.sendRequest({ /* message stuff here */ }, function(req){
clearTimeout(noResponse);
alert('I have a response!');
});https://stackoverflow.com/questions/10082478
复制相似问题