![](/img/trans.png)
[英]Is it possible to pass data between custom service worker and React components?
[英]How to activate a react route and pass data from the service worker?
我有一個 SPA PWA React 應用程序。
它在移動設備(Android+Chrome)上以獨立模式安裝和運行。
假設該應用程序列出人員,然后當您單擊某個人時,它會使用/person
路由顯示詳細信息。
現在,我從服務器發送推送通知並在附加到應用程序的服務工作線程中接收它們。 通知是關於一個人的,我想在用戶點擊通知時打開那個人的詳細信息。
問題是:
/person
路由據我了解,從服務工作者notificationclick
事件處理程序中,我可以:
/person
不是物理路線,無論哪種方式 - 我都想避免刷新頁面)您可以監聽您向用戶顯示的通知的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);
}
}
檢查這些鏈接:
回答我自己的問題:我已經使用 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 其他人,我仍在尋找更好的解決方案。
我在我的項目中有類似的需求。 使用您的 postMessage 提示,每次用戶單擊 Service Worker 通知時,我都能在我的組件上獲取一個事件,然后將用戶路由到所需的路徑。
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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.