我有一个扩展,我想在不同时间关注标签几秒钟 .
我能够更改选项卡,但是,我想传递一个回调函数,以便在选项卡聚焦时 .
我已经尝试将函数传递给 sendMessage
但它似乎立即执行(见下文) . 一旦选项卡聚焦,如何传入回调函数以在内容脚本中执行?
content_script.js
chrome.runtime.sendMessage("Do something", function(resp) {
console.log(resp)
})
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
chrome.windows.update(sender.tab.windowId, {"focused": true}, function(window){ });
chrome.tabs.update(sender.tab.id, {"active": true}, function(tab){
// callback function
});
});
1 回答
Return true from onMessage listener保持响应通道打开,然后从chrome API回调中调用
sendResponse
. 请注意,chrome API回调始终运行asynchronously,即在主函数完成后运行 .在现代浏览器中,这通常使用Promise API来解决 .
您可以通过加载Mozilla WebExtension polyfill将其与Chrome API一起使用 .
polyfill还允许您使用await / async语法: