ServiceWorkerAPI#

Interface ServiceWorkerAPI

The ServiceWorkerAPI controls the webvis service worker, which caches delivery-service responses locally so that previously loaded data can be served from the browser's Cache Storage instead of being re-fetched from the backend. This speeds up subsequent loads and reduces network traffic.

The service worker is a single, origin-global instance shared by every tab and context. Changing its configuration or clearing its cache therefore affects all of them, and changes are broadcast so each context stays in sync.

Cached responses are grouped into caches: each loaded resource has its own cache, and the individual responses for it are the entries within that cache. This is reflected in the statistics, which report both a ServiceWorkerCacheStats.cacheCount and an ServiceWorkerCacheStats.entryCount.

The service worker script (webvis.serviceworker.js) is not bundled with your application — it is delivered by the instant3Dhub backend. Your application is responsible for registering it at runtime from the URL your backend exposes. This is a prerequisite for everything below: until a worker is registered, activated and controlling the page, the API has nothing to talk to (see ServiceWorkerAPI.isServiceWorkerConnected and ServiceWorkerConnectedEvent).

A service worker can only be registered from a URL on the same origin as your application, and the hub is a different origin — so you cannot register the hub URL directly. Instead, ship a tiny service worker of your own (served from your origin) that acts as a wrapper and loads the hub-delivered worker via importScripts. Unlike a module import, importScripts can fetch a cross-origin script without CORS, so the wrapper must be a classic service worker (do not pass { type: "module" }). Pass the hub worker URL to the wrapper as a query parameter at registration time so it doesn't have to be hard-coded.

Your same-origin wrapper, e.g. webvis-sw.js:

// Served from your own origin. Loads the backend-delivered worker, whose URL is passed as a query
// parameter. importScripts is synchronous, so the imported worker's install/activate/fetch handlers
// are registered before the install event fires.
const hubUrl = new URL(self.location.href).searchParams.get("hubUrl");

if (hubUrl) {
  importScripts(new URL("/repo/webvis/webvis.serviceworker.js", hubUrl).href);
}

Registering the wrapper from your application:

// The instant3Dhub origin that delivers the worker.
const hubUrl = "https://your-hub.example.com";

if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register(
      `/webvis-sw.js?hubUrl=${encodeURIComponent(hubUrl)}`, // your same-origin wrapper
      {updateViaCache: "none"},                             // Update-check against the network, not the HTTP cache
  ).catch((error) => {
    console.error("Failed to register the webvis service worker", error);
  });
}

const context = webvis.getContext();

// The connection is established automatically once the worker controls the page.
context.registerListener(
  [webvis.EventType.SERVICE_WORKER_CONNECTED],
  () => console.log("Service worker connected:", context.isServiceWorkerConnected())
);

Once connected, the API also detects when the running worker is older than the one shipped with the current application and automatically asks the browser to update it (see ServiceWorkerAPI.isServiceWorkerStale). This relies on the webvis bundle and the worker being delivered together, so the version baked into this build reflects the backend's current one.

Local caching only works if all the following hold:

  • Secure context: the app is served over HTTPS (or from localhost).
  • Same-origin wrapper: the registered script is a classic worker (not {type: "module"}) on the app's origin that loads the hub worker via importScripts.
  • Scope: the registration's scope covers the pages that run webvis.
  • One registration per origin: CacheStorage and the metadata database are per-origin, so a second webvis registration — even on another scope — shares the same cached data and counters, and its worker runs its own maintenance (eviction, expiry) against that shared storage. Prefer a single registration to avoid redundant or conflicting maintenance.
  • Fixed script URL: always register the same wrapper URL, including ?hubUrl=. A different URL installs a new worker that takes over all pages in the scope.
  • Existing service worker: if the app already has one on that scope, call importScripts for the webvis worker in it before adding the app's own fetch listeners, or make sure those don't answer any hub requests.
  • CSP: worker-src allows the wrapper, and script-src allows the hub URL used by importScripts.
  • IndexedDB available: without it the worker passes every request through to the network.

Data served from the local cache does not reach the delivery service, so the delivery service cannot check access for it. For backends that authorize only at data level (late authorization), this would skip the only authorization check. The service worker therefore confirms a grant before it serves the first cache hit for a resource: it replays the request's credentials in one uncached HEAD request to the delivery service, once per resource and signature. A successful network request for the resource counts as confirmation as well. If the HEAD is rejected, its status is returned to webvis instead of the cached data and the resource enters NodeState.ERROR_AUTHORIZATION.

The check runs inside the worker, so it costs nothing while caching is disabled, while the page is controlled by another service worker, or for data that is not cached. It is controlled by SettingStrings.LOCAL_CACHE_AUTH_CHECK_ENABLED (enabled by default), which is passed to the worker when it connects and applies to every tab of the origin; later changes of the setting are ignored. Backends that authorize when a resource is added can disable it to save that request, e.g. centrally in the hub's webvis.config.json:

{ "localCacheAuthCheckEnabled": false }
  • Enabling or disabling local caching at runtime
  • Configuring the cache expiration and the service worker's log level
  • Quota-based automatic eviction (least-recently-used) and age-based expiration cleanup
  • Clearing all cached data, or only data not accessed within a given window
  • Querying cache statistics and the current storage usage
  • Reporting the running worker's version and whether it is outdated
  • Surfacing failures of background operations (clear, eviction, expiration)
  • Optional authorization check per resource before cached data is used
// Get the webvis context
const context = webvis.getContext();

// Disable local caching
await context.changeServiceWorkerConfig({cachingEnabled: false});

// Read the current cache statistics
const stats = await context.requestServiceWorkerStats();
console.log(`${stats.entryCount} entries, ${stats.totalTransferSize} bytes`);

// Clear all locally cached data
await context.clearServiceWorkerCache();

The API triggers the following events:

interface ServiceWorkerAPI {
    changeServiceWorkerConfig(
        config: Partial<ServiceWorkerConfig>,
    ): Promise<void>;
    clearServiceWorkerCache(notAccessedForMs?: number): Promise<void>;
    isServiceWorkerAuthCheckEnabled(): Promise<boolean>;
    isServiceWorkerConnected(): boolean;
    isServiceWorkerStale(): Promise<boolean>;
    requestServiceWorkerConfig(): Promise<ServiceWorkerConfig>;
    requestServiceWorkerStats(): Promise<ServiceWorkerCacheStats>;
    requestServiceWorkerVersion(): Promise<ServiceWorkerVersionInfo>;
    resetServiceWorkerConfig(): Promise<void>;
}

Hierarchy (View Summary)

Index

Methods

  • Experimental

    Changes the service worker configuration.

    Only the given fields are updated; omitted fields keep their current value. A change is applied to the single, origin-global service worker, so it affects every tab and context, and it is persisted across restarts.

    Triggers a ServiceWorkerConfigChangedEvent containing only the fields whose value actually changed. Setting a field to its current value is a no-op and triggers no event.

    Example usage:

    // Get the webvis context
    const context = webvis.getContext();
    
    // Disable caching and shorten the cache lifetime to one day
    await context.changeServiceWorkerConfig({
      cachingEnabled: false,
      cacheExpirationMs: 24 * 60 * 60 * 1000,
    });
    

    Invalid field values (e.g. a negative expiration or an out-of-range quota fraction) are ignored, keeping the previous value.

    Parameters

    Returns Promise<void>

    A promise that resolves once the change has been applied and persisted, and rejects if it could not be persisted.

  • Experimental

    Clears data cached locally by the service worker.

    Without an argument, removes every webvis cache from Cache Storage along with its metadata. With notAccessedForMs, removes only caches that have not been read within that window (based on last access, i.e. least-recently-used), leaving recently-used caches intact — useful for reclaiming space on demand without discarding hot data. Because the service worker is shared, this affects all tabs and contexts. A cache that an active load is still filling is skipped and keeps everything it holds, including the entries cached before the clear; the load continues to cache as usual.

    Clearing can take a while on large stores, so the returned promise resolves once the operation has been accepted by the service worker, not once it has finished. Listen for ServiceWorkerCacheClearedEvent to know when the caches have actually been cleared (it carries a summary of what was removed).

    Parameters

    • OptionalnotAccessedForMs: number

      Optional. Only clear caches not read within the last this-many milliseconds. Must be a non-negative number; an invalid value is ignored and no caches are cleared. Omit it to clear all.

    Returns Promise<void>

    A promise that resolves once the clear has been accepted (see above).

  • Experimental

    Returns whether the service worker checks the authorization before it serves cached data (see the Authorization section above).

    This is the running worker's actual state. It can differ from this context's SettingStrings.LOCAL_CACHE_AUTH_CHECK_ENABLED: the worker applies (and keeps across restarts) the value of the last context that connected, from any tab of the origin, and the setting is only read when this context connects.

    Returns Promise<boolean>

    A promise that resolves with true if the authorization check is active.

  • Experimental

    Returns whether the connection to the service worker is currently established.

    Reflects whether the CONNECT handshake has completed successfully. A service worker that registers later (see ServiceWorkerConnectedEvent) may flip this to true after it was initially false, so prefer reacting to the event for live updates.

    Returns boolean

    True if the service worker is connected.

  • Experimental

    Returns whether the service worker controlling the page is out of date.

    Compares the running worker's revision with the revision this webvis build expects. A stale worker is updated automatically, so this is primarily for diagnostics/display.

    Returns Promise<boolean>

    A promise that resolves with true if the running service worker is stale.

  • Experimental

    Resets the service worker configuration to its installation defaults.

    Triggers a ServiceWorkerConfigChangedEvent containing only the fields whose value changes as a result. If the configuration already matches the defaults, this is a no-op.

    Returns Promise<void>

    A promise that resolves once the configuration has been reset and persisted.