Skip to content

Instantly share code, notes, and snippets.

@yaakaito
Created January 24, 2024 07:37
Show Gist options
  • Save yaakaito/0caafe336fdb16d081ced03f905b9f5c to your computer and use it in GitHub Desktop.
Save yaakaito/0caafe336fdb16d081ced03f905b9f5c to your computer and use it in GitHub Desktop.
Chrome 拡張で Chrome 起動中に定期的に何かをする
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 しておくと定期的に特定の関数が実行される状態になる。
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