64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
// 存储所有客户端ID(用于定向通知)
|
||
let controlledClients = [];
|
||
// 监听安装事件
|
||
self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
|
||
|
||
// 监听激活事件
|
||
self.addEventListener('activate', e =>
|
||
e.waitUntil(clients.claim().then(() => self.clients.matchAll())
|
||
.then(clients => {
|
||
// 获取所有受控客户端ID
|
||
controlledClients = clients.map(c => c.id);
|
||
})
|
||
)
|
||
);
|
||
|
||
// 监听客户端连接变化(窗口打开/关闭)
|
||
self.addEventListener('message', event => {
|
||
if (event.data.type === 'REGISTER_CLIENT') {
|
||
if (!controlledClients.includes(event.data.clientId)) {
|
||
controlledClients.push(event.data.clientId);
|
||
}
|
||
}
|
||
});
|
||
|
||
// 核心:处理锁屏/解锁广播
|
||
self.addEventListener('message', event => {
|
||
const { action, senderId } = event.data;
|
||
|
||
if (action === 'LOCK' || action === 'UNLOCK') {
|
||
// 向所有其他客户端广播
|
||
self.clients.matchAll().then(clients => {
|
||
clients.forEach(client => {
|
||
// 排除发送者
|
||
if (client.id !== senderId) {
|
||
client.postMessage({
|
||
action: `${action}_REQUESTED`,
|
||
timestamp: Date.now()
|
||
});
|
||
}
|
||
});
|
||
});
|
||
}
|
||
});
|
||
|
||
self.addEventListener('push', event => {
|
||
const title = '新消息';
|
||
const options = {
|
||
body: event.data.text(),
|
||
// icon: '/images/icon.png',
|
||
// badge: '/images/badge.png'
|
||
};
|
||
|
||
event.waitUntil(
|
||
self.registration.showNotification(title, options)
|
||
);
|
||
});
|
||
|
||
self.addEventListener('notificationclick', event => {
|
||
event.notification.close();
|
||
event.waitUntil(
|
||
clients.openWindow('https://example.com/notifications')
|
||
);
|
||
});
|