gpt4 book ai didi

javascript - 未发送 Chrome 扩展 sendResponse 回调值

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:47:48 25 4
gpt4 key购买 nike

我正在编写一个与 gmail api 交互的 chrome 扩展程序(chrome 45 是我的版本)并且我在从 background.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 Extension Message passing: response not sent

最佳答案

您应该在回调中发送 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);
}
});

希望对您有所帮助。

关于javascript - 未发送 Chrome 扩展 sendResponse 回调值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35237621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com