简体   繁体   中英

Listening for button click in PWA service worker

I am trying to follow the following example for PWA Push Notifications but have a general question regarding service workers

https://developers.google.com/web/fundamentals/codelabs/push-notifications/

Within my Service Worker, I want to add a listener to a button/anchor tag

My Service Worker is initialised as follows:

if ("serviceWorker" in navigator && "PushManager" in window) {
    navigator.serviceWorker
        .register("./scripts/my.serviceworker.js", { scope: "/" })
        .then(function (swReg) {
            console.log("Service Worker Registered: ", swReg);
            swRegistration = swReg;
            initializeUI();
        });
};

And the function initializeUI() needs to contain a listener for the click event so that the user can subscribe/unsubscribe

function initializeUI() {
    var pushButton = document.querySelector(".pwa-pushbutton");
    pushButton.addEventListener("click", function () {
        console.log("Button pushed");
        if (isSubscribed) {
            // TODO: Unsubscribe user
        } else {
            subscribeUser();
        }
    });

But the pushButton variable is not defined.

How can I add a listener event to an element on the DOM within my service worker JS file?

Service Workers cannot listen to nor interact with DOM directly. All DOM activity (like clicks) would need to be sent to Service Workers with postMessage()

App:

function onClick(event => {
  navigator.serviceWorker.controller.postMessage({
    value1: 'hello',
    value2: 'there'
  });
})

Service Worker:

self.addEventListener('message', event => { 
  const val1 = event.data.value1,
        val2 = event.data.value2;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM