Nic*_*its 0 javascript asynchronous google-chrome-extension
我在我的background.js中有这段代码:
chrome.extension.onMessage.addListener( function(request,sender,sendResponse){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var requests = getTabRequests(tabs[0].id);
//getTabRequests gets all the information i stored about a tab
sendResponse( {requests: requests});
});
});
Run Code Online (Sandbox Code Playgroud)
我想要它做的是响应popup.js.在chrome.tabs.query我使这不可能的.我意识到这是一个异步函数,但如何修复它?或者是唯一可能不发送响应,但只是另一个消息在不同的方向(这意味着我不能在mu popup.js中使用回调函数)
阅读以下文档chrome.runtime.onMessage:
function sendResponse
在有响应时调用(最多一次)的函数.参数应该是任何可以使用JSON的对象.如果同一文档中有多个onMessage侦听器,则只有一个可以发送响应.当事件侦听器返回时,此函数变为无效,除非您从事件侦听器返回true以指示您希望异步发送响应(这将使消息通道保持打开到另一端,直到调用sendResponse).
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var requests = getTabRequests(tabs[0].id);
//getTabRequests gets all the information i stored about a tab
sendResponse({requests: requests});
});
return true; // <-- Required if you want to use sendResponse asynchronously!
});
(chrome.extension.onMessage不推荐使用,chrome.runtime.onMessage相反,前者是后者的别名.)
| 归档时间: |
|
| 查看次数: |
736 次 |
| 最近记录: |