Created
January 24, 2024 07:37
-
-
Save yaakaito/0caafe336fdb16d081ced03f905b9f5c to your computer and use it in GitHub Desktop.
Chrome 拡張で Chrome 起動中に定期的に何かをする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
service-worker と alarms を組みわせると実現できる。 | |
- https://developer.chrome.com/docs/extensions/reference/api/alarms?hl=ja#examples | |
- https://developer.chrome.com/docs/extensions/develop/concepts/service-workers/basics?hl=ja | |
service-worker が install されたタイミングで alarms を設定しておき、再起動時なども必要であれば alarms を設定し直すようにする。 | |
同一 service-worker 内で addListener しておくと定期的に特定の関数が実行される状態になる。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createAlarmIfNeeded = async () => { | |
const alarm = await chrome.alarms.get('fooAlarm'); | |
if (!alarm) { | |
await chrome.alarms.create('fooAlarm', { periodInMinutes: 1 }); | |
} | |
}; | |
chrome.runtime.onInstalled.addListener(async ({ reason }) => { | |
createAlarmIfNeeded(); | |
}); | |
createAlarmIfNeeded(); | |
chrome.alarms.onAlarm.addListener(async (alarm) => { | |
if (alarm.name === 'fooAlarm') { | |
// do something | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment