问题
This snippet helps in either bring in the app tab in focus or open a new tab with that URL. If the tab is already open, is there a way to change the URL (based on the notification the user clicked).?
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(windowClients) {
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
if (url.test(client.url) && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow('/#/chat');
}
})
);
回答1:
The WindowClient.navigate() method sounds like what you want. You should be able to do something like:
// Assume that you want to find the first window that is currently open
// to originalUrl, and navigate that window to navigationUrl.
// If there is no window currently at originalUrl, then open a new window.
event.waitUntil(
clients.matchAll({type: 'window'})
.then(clients => clients.filter(client => client.url === originalUrl))
.then(matchingClients => {
if (matchingClients[0]) {
return matchingClients[0].navigate(navigationUrl)
.then(client => client.focus());
}
return clients.openWindow(navigationUrl);
})
);
来源:https://stackoverflow.com/questions/39476963/service-worker-redirecting-a-user-to-different-url-when-he-clicks-the-notificat