问题
I have a chrome extension that's sending a login message:
chrome.runtime.sendMessage data, (response) ->
debugger
if response.api_key
$("body").fadeOut 1000, -> window.close()
else
App.Ui.clearForm()
App.Ui.showErrorMessage()
However, the callback is never hit:
chrome.runtime.onMessage.addListener (request, sender, sendResponse) ->
if request and request.action is "login"
$.ajax(
type: "POST"
url: App.Config.authUrl()
data: request.data
dataType: "json"
).then( (data) ->
App.Storage.saveSession(data.user)
sendResponse(data.user)
, (data) ->
sendResponse(data)
)
Am I doing something wrong?
回答1:
See documentation for onMessage about sendResponse
:
This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).
So, to fix your code, you need to return true
in the listener after your async call.
来源:https://stackoverflow.com/questions/22864520/chrome-extension-message-passing