fix: sw init fix
This commit is contained in:
parent
1dec929582
commit
5aceec38b0
4 changed files with 27 additions and 3 deletions
|
@ -1,7 +1,9 @@
|
|||
import type { SwMessage } from './main.ts'
|
||||
import { asNonNull, Deferred } from '@fuman/utils'
|
||||
import { waitForServiceWorkerInit } from './register.ts'
|
||||
|
||||
export function getServiceWorker() {
|
||||
export async function getServiceWorker() {
|
||||
await waitForServiceWorkerInit()
|
||||
return asNonNull(navigator.serviceWorker.controller)
|
||||
}
|
||||
|
||||
|
@ -9,8 +11,8 @@ let registered = false
|
|||
let nextId = 0
|
||||
const pending = new Map<number, Deferred<any>>()
|
||||
|
||||
export function swInvokeMethod(request: SwMessage) {
|
||||
const sw = getServiceWorker()
|
||||
export async function swInvokeMethod(request: SwMessage) {
|
||||
const sw = await getServiceWorker()
|
||||
if (!registered) {
|
||||
navigator.serviceWorker.addEventListener('message', (e) => {
|
||||
const { id, result, error } = (e as MessageEvent).data
|
||||
|
|
|
@ -88,3 +88,11 @@ self.onmessage = async (event) => {
|
|||
event.source!.postMessage({ id: msg.id, error: unknownToError(e).message })
|
||||
}
|
||||
}
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(self.skipWaiting())
|
||||
})
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(self.clients.claim())
|
||||
})
|
||||
|
|
|
@ -1,5 +1,12 @@
|
|||
import { Deferred } from '@fuman/utils'
|
||||
import workerUrl from '../../sw.ts?worker&url'
|
||||
|
||||
const swInitDeferred = new Deferred<void>()
|
||||
|
||||
export async function waitForServiceWorkerInit() {
|
||||
await swInitDeferred.promise
|
||||
}
|
||||
|
||||
export function registerServiceWorker() {
|
||||
if (!('serviceWorker' in navigator)) {
|
||||
document.body.innerHTML = `
|
||||
|
@ -35,5 +42,10 @@ export function registerServiceWorker() {
|
|||
url.searchParams.delete(FIX_KEY)
|
||||
history.pushState(undefined, '', url)
|
||||
}
|
||||
|
||||
swInitDeferred.resolve()
|
||||
}).catch((err) => {
|
||||
console.error('Failed to register service worker', err)
|
||||
swInitDeferred.reject(err)
|
||||
})
|
||||
}
|
||||
|
|
|
@ -10,6 +10,7 @@ import { nanoid } from 'nanoid'
|
|||
import { renderSVG } from 'uqr'
|
||||
import { $accounts, $activeAccountId } from '../store/accounts.ts'
|
||||
import { swInvokeMethod } from '../sw/client.ts'
|
||||
import { waitForServiceWorkerInit } from '../sw/register.ts'
|
||||
import { createInternalClient, deleteAccount, importAccount } from '../utils/telegram.ts'
|
||||
import { emitEvent } from './utils.ts'
|
||||
|
||||
|
@ -216,6 +217,7 @@ export class ReplWorkerTelegram {
|
|||
}
|
||||
|
||||
async fetchAvatar(accountId: string) {
|
||||
await waitForServiceWorkerInit()
|
||||
const res = await fetch(`/sw/avatar/${accountId}/avatar.jpg`)
|
||||
if (!res.ok) {
|
||||
return null
|
||||
|
|
Loading…
Reference in a new issue