我有一个扩展,需要聚焦当前窗口才能提交表单。提交此表单可能要花费几秒钟的时间,即使另一个标签调用了chrome.runtime.sendMessage()
// content_script.js
if (!Document.visibilityState === ""visible) {
chrome.runtime.sendMessage("Focus", function(resp) {
reply_link.click()
setTimeout(function() {
// from here, let the background script know it's OK to continue
// if background.js tries to call another tab from here it is blocked from doing so
}, 1000)
})
}
// background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
chrome.tabs.update(sender.tab.id, {"active": true}, function(tab){
return sendResponse(tab)
});
return true
});
答案 0 :(得分:2)
发送时间等待同一条消息,以便后台脚本可以管理内部的队列:
content_script.js
chrome.runtime.sendMessage({action: 'focus', wait: 1000}, response => {
reply_link.click()
});
background.js
const queue = [];
const ACTIONS = {
focus(task) {
chrome.tabs.update(task.sender.tab.id, {active: true}, tab => {
task.response = tab;
callOrWait(processQueue, task.msg.wait);
});
return true;
},
};
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
queue.push({msg, sender, sendResponse});
return queue.length > 1 || processQueue();
// returning 'true' postpones the response thus pausing the sender when there is
// already a task in the queue and once that completes this one will be processed
});
function processQueue() {
while (queue.length) {
const task = queue.shift();
if ('response' in task) {
task.sendResponse(task.response);
continue;
}
const action = ACTIONS[task.msg.action];
if (action && action(task) === true) {
// this task wants an asynchronous response
return true;
}
}
}
function callOrWait(fn, wait, ...args) {
if (wait) {
setTimeout(fn, wait, ...args);
} else {
fn(...args);
}
}