回答我自己的问题:我使用 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 别人,我仍在寻找更好的解决方案。