我正在创建一个番茄钟计时器程序,但在取消聚焦弹出窗口后,我无法弄清楚如何让计时器在后台运行。
我已经为此工作了一段时间,但我目前在后台脚本中拥有实际计时器的所有代码。我希望使用 popup.js 中的运行时 API 发送一次性消息以启动 background.js 中的计时器,然后每当用户打开扩展程序时,返回计时器设置的内容。
我也不完全确定我是否正确地解决了这个问题。
代码不起作用,因此我将其简化为仅发送消息并尝试获得响应,我发现这是问题所在。
代码:
popup.js:
chrome.runtime.sendMessage({greeting: 'hello'}, function(response) {
console.log(response.farewell)
});
background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.greeting == 'hello') {
sendResponse({farewell: 'goodbye'})
toggleClock();
}
});
//working toggleClock() function
manifest.json:
"browser_action": {
"default_popup":"popup.html",
"default_title":"Flexidoro",
"default_icon":"flexidoro.png"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [ "storage", "alarms" ]