我正在编写与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);
}
答案 0 :(得分:-1)
您应该在回调中发送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});
});
}
另一种可能的解决方案:
tab id
对象获取sender
。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);
}
});
我希望这会有所帮助。