Chrome Extension Message Passing [duplicate]

2019-01-20 07:04发布

This question already has an answer here:

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条回答
相关推荐>>
2楼-- · 2019-01-20 07:30

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.

查看更多
登录 后发表回答