【问题标题】:How to activate a react route and pass data from the service worker?如何激活反应路线并从服务人员传递数据?
【发布时间】:2020-01-10 09:52:59
【问题描述】:

我有一个 SPA PWA React 应用程序。
它在移动设备(Android+Chrome)上以独立模式安装和运行。

假设该应用列出了人员,然后当您单击人员时,它会使用/person 路由显示详细信息。

现在,我正在从服务器发送推送通知,并在附加到应用程序的服务人员中接收它们。通知是关于一个人的,我想在用户点击通知时打开该人的详细信息。

问题是:

  • 如何从服务人员激活我的应用程序上的/person 路由
  • 并传递数据(例如人员 ID 或人员对象)
  • 无需重新加载应用程序

据我了解,从服务人员notificationclick 事件处理程序我可以:

  • 专注于应用程序(但我如何传递数据并激活路由)
  • 打开一个网址(但/person 不是物理路由,无论哪种方式——我都想避免刷新页面)

【问题讨论】:

标签: reactjs react-router single-page-application service-worker progressive-web-apps


【解决方案1】:

您可以监听click 事件以获取您向用户显示的通知。在处理程序中,您可以通过推送事件打开来自服务器的相应人员的 URL。

notification.onclick = function(event) {
  event.preventDefault(); 

  // suppose you have an url property in the data
  if (event.notification.data.url) {

      self.clients.openWindow(event.notification.data.url);
  }
}

检查这些链接:

【讨论】:

  • 我知道,这一切都在我的问题中说明了,但是如何将其与反应路由相匹配并避免刷新 SPA?
【解决方案2】:

回答我自己的问题:我使用 IndexedDB(不能使用 localStorage,因为它是同步的)在 SW 和 PWA 之间进行通信,但我对此不太满意。

这大概是我的 service worker 代码的样子(我正在使用 idb 库):

self.addEventListener('notificationclick', function(event) {
    const notif = event.notification;
    notif.close();
    if (notif.data) {
        let db;
        let p = idb.openDB('my-store', 1, {
            upgrade(db) {
                db.createObjectStore(OBJSTORENAME, {
                    keyPath: 'id'
                });
            }
        }).then(function(idb) {
            db = idb;
            return db.clear(OBJSTORENAME);
        }).then(function(rv) {            
            return db.put(OBJSTORENAME, notif.data);
        }).then(function(res) {
            clients.openWindow('/');
        }).catch(function(err) {
            console.log("Error spawning notif", err);
        });
        event.waitUntil(p);
    }
});

然后,在我的 react 应用程序的根目录中,即在我的 AppNavBar 组件中,我总是检查是否有要显示的内容:

componentWillMount() {
    let self = this;
    let db;
    idb.openDB('my-store', 1)
    .then(function (idb) {
        db = idb;            
        return db.getAll(OBJSTORENAME);
    }).then(function (items) {            
        if (items && items.length) {
            axios.get(`/some-additional-info-optional/${items[0].id}`).then(res => {
                if (res.data && res.data.success) {
                    self.props.history.push({
                        pathname: '/details',
                        state: {
                            selectedObject: res.data.data[0]
                        }
                    });
                }
            });
            db.clear(OBJSTORENAME)
            .then()
            .catch(err => {
                console.log("error clearing ", OBJSTORENAME);
            });
        }
    }).catch(function (err) {
        console.log("Error", err);
    });
}

一直在玩 clients.openWindow('/?id=123');clients.openWindow('/#123'); 但这很奇怪,有时应用程序会停止,所以我恢复到 IndexedDB 方法。 (clients.postMessage 也可能是要走的路,虽然我不确定如何将它插入到反应框架中)

HTH 别人,我仍在寻找更好的解决方案。

【讨论】:

    【解决方案3】:

    我的项目也有类似的需求。使用您的 postMessage 提示,每次用户单击服务工作者通知时,我都能够在我的组件上获得一个事件,然后将用户路由到所需的路径。

    service-worker.js

    self.addEventListener("notificationclick", async event => {
        const notification = event.notification;
    
        notification.close();
    
        event.waitUntil(
            self.clients.matchAll({ type: "window" }).then(clientsArr => {
                if (clientsArr[0]) {
                    clientsArr[0].focus();
                    clientsArr[0].postMessage({
                        type: "NOTIFICATION_CLICK",
                        ticketId: notification.tag,
                    });
                }
            })
        );
    });
    

    在你的 react 组件上,添加一个新的监听器:

    useEffect(() => {
        if ("serviceWorker" in navigator) {
            navigator.serviceWorker.addEventListener("message", message => {
                if (message.data.type === "NOTIFICATION_CLICK") {
                    history.push(`/tickets/${message.data.ticketId}`);
                }
            });
        }
    }, [history]);
    

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多