ServiceWorkerGlobalScope: sự kiện activate

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Note: This feature is only available in Service Workers.

Sự kiện activate của giao diện ServiceWorkerGlobalScope được kích hoạt khi một ServiceWorkerRegistration có một worker ServiceWorkerRegistration.active mới.

Sự kiện này không thể hủy và không nổi bọt.

Cú pháp

Sử dụng tên sự kiện trong các phương thức như addEventListener(), hoặc thiết lập một thuộc tính trình xử lý sự kiện.

js
addEventListener("activate", (event) => { })

onactivate = (event) => { }

Loại sự kiện

Một ExtendableEvent. Kế thừa từ Event.

Event ExtendableEvent

Thuộc tính sự kiện

Không triển khai bất kỳ thuộc tính cụ thể nào, nhưng kế thừa các thuộc tính từ giao diện cha, Event.

Ví dụ

Đoạn mã sau đây cho thấy cách bạn có thể sử dụng trình xử lý sự kiện activate để nâng cấp bộ nhớ đệm.

js
self.addEventListener("activate", (event) => {
  const cacheAllowlist = ["v2"];

  event.waitUntil(
    caches.keys().then((cacheNames) =>
      Promise.all(
        cacheNames.map((cacheName) => {
          if (!cacheAllowlist.includes(cacheName)) {
            return caches.delete(cacheName);
          }
          return undefined;
        }),
      ),
    ),
  );
});

Bạn cũng có thể thiết lập trình xử lý sự kiện bằng cách sử dụng thuộc tính onactivate:

js
self.onactivate = (event) => {
  // …
};

Đặc tả kỹ thuật

Specification
Service Workers Nightly
# service-worker-global-scope-activate-event
Service Workers Nightly
# dom-serviceworkerglobalscope-onactivate

Tương thích trình duyệt

Xem thêm