Chrome Extension Message Passing [duplicate]

2019-01-20 07:05发布

问题:

This question already has an answer here:

  • Chrome Extension Message passing: response not sent 3 answers

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.