Arh*_*han 1 mozilla firefox-addon
I\xe2\x80\x99m 正在开发一个简单的时间跟踪器扩展。当我开始时,我将所有 js 代码放在一个 popup.js 文件中,但我发现当扩展弹出窗口关闭时,计时器停止运行。我遇到了使用后台脚本与我已经创建的 popup.js 脚本结合使用的情况。我\xe2\x80\x99ve现在所做的是,我从popup.js中的HTML页面获得了evenListener逻辑,然后使用browser.runtime.sendMessage将数据发送到background.js脚本来处理计时器。这是正确的设置还是我应该采取不同的做法?
\n我能\xe2\x80\x99t弄清楚如何将点击事件从post传递到后台脚本,然后使用后台脚本中的eventListener来启动计时器。
\n这是我的 timetracker 扩展的公共 GitHub 存储库。https://github.com/krullmizter/timetracker
\n在 popup.js 文件中的 notificationBackgroundPage() 函数中,您不需要将 HTML 按钮发送到后台脚本。相反,您\xe2\x80\x99d 可能想要这样的东西:
\nconst sending = browser.runtime.sendMessage({\n action: startBtn.id\n});\nsending.then(handleRes, handleErr);\nRun Code Online (Sandbox Code Playgroud)\n这将向后台脚本发送一个对象,该对象具有以 \xe2\x80\x9cstart\xe2\x80\x9d 作为操作的消息对象。然后,在后台脚本中,您可以使用 switch 语句(如果您确实想要的话,也可以使用 if/else 语句)来调用适当的函数。
\n单击事件侦听器需要全部位于 popup.js 文件中,并且每个 onclick 都应向后台发送一条消息以执行所需的操作。
\n所以你的后台脚本将变成这样:
\nfunction popupMsgReceived(msg, sender, sendRes) {\n console.log("Msg received", msg);\n\n switch (msg.action) {\n case "start":\n handleStart();\n break;\n case "stop":\n handleStop();\n break;\n case "reset":\n handleReset();\n break;\n }\n\n sendRes({response: "Response from background script"});\n}\n\nbrowser.runtime.onMessage.addListener(popupMsgReceived);\n\n// Set the initial clock values\nlet hr = 0;\nlet min = 0;\nlet sec = 0;\n \nlet interval;\n\n/* \n* Three even listeners for the three buttons\n* The startBtn event will set an interval to run each 1000ms (1sec) and run the startTimer function\n* timerStartedAt function will also run och the btn event\n*/\nfunction handleStart() {\n timerStartedAt();\n clearInterval(interval);\n interval = setInterval(startTimer, 1000);\n}\n\nfunction handleStop() {\n clearInterval(interval);\n}\n\nfunction handleReset() {\n clearInterval(interval);\n hr = 0;\n min = 0;\n sec = 0;\n timer.innerHTML = \'00:00:00\';\n displayDate.innerHTML = \'\'\n}\nRun Code Online (Sandbox Code Playgroud)\n至于设置计时器,我\xe2\x80\x99d建议使用Alarms API,而不是使用 Javascript 超时或间隔。对于浏览器插件来说,警报更加稳定。另一个积极的方面是,您可以从 popup.js 创建和编辑警报,而无需发送消息,并且即使在弹出页面关闭后,警报也将保持活动状态。
\n未来需要考虑的另一件事是清单版本 3 最终将成为 Firefox 的标准。该版本的 API 没有持久的后台页面。因此,此时 Javascript 超时和间隔将无法在后台脚本中工作,您稍后需要更改代码。
\n| 归档时间: |
|
| 查看次数: |
451 次 |
| 最近记录: |