ServiceWorkerGlobalScope:sync 事件

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

备注: 此特性仅在 Service Worker 中可用。

当页面(或 worker)使用 SyncManager 注册的事件正在运行,并且一旦网络连接可用时,将触发 ServiceWorkerGlobalScope 接口的 sync 事件。

此事件不能取消,也不会冒泡。

语法

addEventListener() 一样在方法中使用事件名称,或设置事件处理器属性。

js
addEventListener("sync", (event) => {});

onsync = (event) => {};

事件类型

事件属性

自其父级 ExtendableEventEvent 继承属性

SyncEvent.tag 只读

返回此 SyncEvent 的开发人员定义的标识符。

SyncEvent.lastChance 只读

如果用户代理在当前尝试之后不再进行进一步的同步尝试,则返回 true

示例

以下示例显示了如何在 Service Worker 中响应同步事件。

js
self.addEventListener("sync", (event) => {
  if (event.tag === "sync-messages") {
    event.waitUntil(sendOutboxMessages());
  }
});

你也可以通过 onsync 属性设置事件处理器:

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

规范

Specification
Web Background Synchronization
# dom-serviceworkerglobalscope-onsync

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
sync event

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.

参见