Chrome Extension Message Passing [duplicate]

我只是一个虾纸丫 提交于 2019-12-17 21:00:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!