消息未在后台脚本和内容脚本之间传递

时间:2019-12-31 02:52:36

标签: javascript google-chrome-extension

我正在从内容脚本向后台脚本发送消息。 response.farewell是“未定义”。

response.farewell 此处未定义:

内容脚本:

var goal;

function sending(_callback){
    chrome.runtime.sendMessage({greeting: "getGoal"}, function(response) {
            goal = response.farewell;
            console.log("goal in sending(): "+ goal);//produces "goal in sending(): undefined"

            _callback(goal);
        }); 
}

后台脚本:

//get current window's id
function getCurrentWinID(callback){
  var windowId;
  chrome.windows.getCurrent(function(currentWin){
     windowId = currentWin.id;
     callback(windowId);
  });  
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {

    if (request.greeting == "getGoal"){

        getCurrentWinID(function(windId){
        var winId = windId.toString();
        var goal = windowArray[winId].getGoal2();

        console.log("2.goal from getGoal background: " +goal);
                //this above line produces what I expect, meaning the program runs as expected until this point

        sendResponse({farewell: goal});
      });

    }
});

***更新:通过使用alert()进行调试,似乎在收到响应之前,内容脚本中的回调函数正在运行。




其中response.farewell 此处已正确定义(为1):

内容脚本:

function isItOn(_callback){
    chrome.runtime.sendMessage({greeting: "checkIfOn"}, function(response) {
            isItOn = response.farewell;
            _callback(isItOn);
        }); 
}

后台脚本:

chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
         else if(request.greeting == "checkIfOn"){
             console.log("checkIfOn greeting received by background script");
             sendResponse({farewell: 1});
         }
       });

第一个代码示例有什么问题?

0 个答案:

没有答案
相关问题