1

嘿,Chrome 开发人员,如何检测何时chrome.extension.sendRequest失败?我试过这个,没有骰子:

chrome.extension.sendRequest({ /* message stuff here */ }, function(req){
    if(req == null || chrome.extension.lastError == null){
        alert("No response. :(");
    }
});

但是发生的情况是回调甚至从未触发,这是我一半的预期。有什么方法可以检测 sendRequest 何时失败?

谢谢!

4

2 回答 2

0

你可以用 a 包围它try{}catch(err){}来捕获任何抛出的错误,但如果没有响应,则不会抛出错误,也没有空响应。

这本来是按设计完成的,以允许消息接收者做这件事。例如,它可能涉及几个 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!');
});
于 2012-04-10T11:06:55.207 回答
0

你需要改变......

if(req == null || chrome.extension.lastError == null){
    alert("No response. :(");
}

...至....

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-10T10:25:57.967 回答