JS Anvil.Call Error - anvil is not defined

A service worker doesn’t have access to the window namespace. It essentially runs in a different JavaScript context and has no access to the JavaScript context where the app is running apart from via the JavaScript messaging api.

You can read more about that api here: Client: postMessage() method - Web APIs | MDN


/** service worker */
async function postMessage(data) {
    const clients = await self.clients.matchAll({
        includeUncontrolled: true,
        type: "window",
    });

    for (const c of clients) {
        c.postMessage(data);
    }
}

/** client (native-libraries or another js file) */
function messageHandler(e) {
    const {data} = e;
    console.log(data);
    // now do some thing - anvil.call is available here since we're in the client
}

navigator.serviceWorker.addEventListener("message", messageHandler)

One thing to keep in mind is that a service worker can outlive its client(s)
e.g. if you lock your phone, the service worker might persist in the background
but the client is no longer available
so no message would be received and the implementation might fall over



You might want to explore anvil-labs experiments with service workers
You can do background/periodic syncs from python code
It’s definitely a wip and not production ready and no documentation :grimacing:
but it might make things easier :crossed_fingers:
If you go down this route - definitely start a discussion over at anvil-labs and we can try to point you in the right direction with your use case.

3 Likes