未发送 Chrome 扩展程序发送响应回调值

Chrome Extension sendResponse callback value not being sent

本文关键字:回调 响应 扩展 Chrome 程序      更新时间:2023-09-26

我正在编写一个与gmail api交互的chrome扩展程序(chrome 45是我的版本),但我在从后台向我的内容脚本发送消息时遇到问题.js。 异步方面是问题所在。 回调后如何发送消息?

//---------in content script---------
chrome.runtime.sendMessage({ messageId: _id }, function (response) {    
    console.log('the respose.messagePayload is: ' + response.messagePayload); 
});
//---------in background script---------
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    getMessage('me', request.messageId, function (payload) {
        //i want to send my response here
        //this executes and grabs the payload of data from the api, but isn't sending back the message to the content-script
        sendResponse({ messagePayload: payload }); 
    });
    //this synchronous call sends a message to the content-script
    //sendResponse({ messagePayload: "payload" });
    return true;
});
function getMessage(userId, messageId,callback) {
    var request = gapi.client.gmail.users.messages.get({
        'userId': userId,
        'id': messageId
    });
    request.execute(callback);
}

Chrome 扩展程序消息传递:未发送响应

您应该在回调中发送 sendResponse 函数。

getMessage('me', request.messageId, sendResponse);

然后在getMessage调用完成时执行此操作。

function getMessage(userId, messageId, sendResponse) {
    var request = gapi.client.gmail.users.messages.get({
        'userId': userId,
        'id': messageId
    });
    request.execute(function(response) {
        sendResponse({messagePayload: response.payload});
    });
}

另一种可能的解决方案:

  1. sender对象获取tab id
  2. 代替回调函数,只需将选项卡 ID 发送到getMessage函数即可。
  3. 现在,getMessage函数中的回调函数会将有效负载发送回内容脚本。
  4. 在内容脚本中添加一个类似的onMessage侦听器,该侦听器将接收有效负载,然后执行要对有效负载执行的操作。

您的代码如下所示:

//---------in background script---------
chrome.runtime.onMessage.addListener(function (request, sender,sendResponse) {
    getMessage('me', request.messageId, sender.tab.id);
});
function getMessage(userId, messageId, tabId) {
    var request = gapi.client.gmail.users.messages.get({
        'userId': userId,
        'id': messageId
    });
    request.execute(function(response) {
        // Whatever response you want to sent
        // Below URL explains your response object
        // https://developers.google.com/gmail/api/v1/reference/users/messages#resource
        // Assuming you want to send payload
        chrome.tabs.sendMessage(tab.id, {messagePayload: response.payload});
    });
}
//---------in content script---------
chrome.runtime.sendMessage({ messageId: _id });
chrome.runtime.onMessage.addListener(function (request, sender,sendResponse) {
    // Just to verify that the request is from the getMessage callback
    // Because this will listen to all request from your extension
    if (request.messagePayload) {
        console.log('the respose.messagePayload is: ' + request.messagePayload);
    }
});

我希望这有所帮助。