我正在编写一个与 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);
}
请您参考如下方法:
您应该在回调中发送 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});
});
}
另一个可能的解决方案:
- 从
sender
对象中获取tab id
。 - 只需将选项卡 ID 发送到您的
getMessage
函数,而不是回调函数。 - 现在,您在
getMessage
函数中的回调函数会将有效负载发送回您的内容脚本。 - 在您的内容脚本中添加一个类似的
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);
}
});
希望对您有所帮助。