Closed1

Chrome 拡張 manifest v3 で setTimeout が動かない

junkawajunkawa

本家マニュアル

It's common for web developers to perform delayed or periodic operations using the setTimeout or setInterval methods. These APIs can fail in service workers, though, because the scheduler will cancel the timers when the service worker is terminated.

Web開発者がsetTimeoutやsetIntervalメソッドを使って遅延や周期的な操作を行うのはよくあることです。しかし、これらのAPIはサービス・ワーカーでは失敗することがあります。なぜなら、サービス・ワーカーが終了したときにスケジューラーがタイマーをキャンセルするからです。

https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/

対策方法

setTimeoutの代わりに、Alarms API を使用する。

chrome.alarms.create({ delayInMinutes: 3, periodInMinutes: 2 });
chrome.alarms.onAlarm.addListener(() => {
  // 処理
});

3分後にアラーム開始。その後、2分おきにアラーム。

マニフェストv3 について

manifest.json v2
  "background": {
    "scripts": [ "background.js" ]
  }
manifest.json v3
  "background": {
    "service_worker": "background.js"
  }

マニフェストv3 では、バックグラウンド処理をサービスワーカーで処理する。

このスクラップは2021/06/30にクローズされました