2012-04-10 140 views
1

嘿同行的Chrome Devs,如何檢測chrome.extension.sendRequest失敗的時間?我想這一點,並沒有骰子:檢測chrome.extension.sendRequest失敗

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

但是,什麼情況是,回調甚至從來沒有火災,這是我一半的預期。有什麼方法可以檢測sendRequest何時失敗?

謝謝!

+0

'chrome.extension.sendRequest'怎麼會失敗?也許你應該嘗試'try {} catch(){}'。 – 2012-04-10 03:33:02

+1

@Derek它可能會失敗,因爲接收請求的選項卡已經崩潰,被用戶關閉,或者由於某種原因未註冊該事件,或者根本沒有註冊該事件。 – 2012-04-10 10:41:12

回答

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

0

您可以用try{}catch(err){} t包圍它o捕獲拋出的任何錯誤,但如果沒有響應,則不會拋出錯誤,並且也沒有空響應。

這將通過設計完成,以允許消息接收器完成這件事。例如,它可能涉及一些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!'); 
}); 
+0

我可能最終會使用這個解決方案,但我真的不知道它需要多長時間來響應......:/ – mattsven 2012-04-17 22:57:32